C# SelfHost how to restrict all external requests?

142 views Asked by At

I have a program that works as a background service. It hosts a self-hosted service. But there is an issue. When I host this service it becomes available for all locale network. And, everyone in the same network can get access to this API. Here is how I host the service :

First I Register the url with netsh

string frm = string.Format(@"http add urlacl url={0}:{1} user={2}\{3}", address, port, domain, user);
            Process.Start(new ProcessStartInfo("netsh", frm)
            {
                Verb = "runas",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            }).WaitForExit();

Then I host the service

 _hostConfiguration = new ExtendHttpSelfHostConfiguration(
                string.Concat(url, ":", port))
            {
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue 
                
            };
            _server = new HttpSelfHostServer(_hostConfiguration);
            _hostingTask = _server.OpenAsync();
            _hostingTask.Wait();

The structure of ExtendHttpSelfHostConfiguration is :

public class ExtendHttpSelfHostConfiguration : HttpSelfHostConfiguration
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="baseAddress"></param>
        public ExtendHttpSelfHostConfiguration(string baseAddress) : base(baseAddress) => Configure();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="baseAddress"></param>
        public ExtendHttpSelfHostConfiguration(Uri baseAddress) : base(baseAddress) => Configure();

        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpBinding"></param>
        /// <returns></returns>
        protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
        {
           
            if (BaseAddress.ToString().ToLower().StartsWith("https://"))
            {
                httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
            }
            return base.OnConfigureBinding(httpBinding);
        }

        private void Configure()
        {
            ConfigureCors();
            ConfigureRoutes();
            ConfigureFormatters();
            ConfigureFilters();
            ConfigureProviders();
            ConfigureSwagger();
            ConfigureLogger();
        }



        private void ConfigureSwagger()
        {
            #if DEBUG
            this.EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "Host services");
                c.DescribeAllEnumsAsStrings();
                c.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Concat(Assembly.GetExecutingAssembly().GetName().Name + ".xml")));
            }).EnableSwaggerUi();
            #else
            #endif
        }

        private void ConfigureLogger() => XmlConfigurator.Configure();

        private void ConfigureProviders() => FluentValidationModelValidatorProvider.Configure(this);

        private void ConfigureFilters() => Filters.Add(new ValidationFilter());

        private void ConfigureCors() => this.EnableCors(new EnableCorsAttribute("*", "*", "*"));

        private void ConfigureRoutes() => this.MapHttpAttributeRoutes();

        private void ConfigureFormatters()
        {
            Formatters.JsonFormatter.SupportedMediaTypes.Clear();
            Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
            Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }

It works completely for local machine.
But when I scan the network nmap can detect this port.

enter image description here

The problem is how to make it work only on the computer. The others shouldn't get access to this port. As I understand for doing this, instead of 0.0.0.0 there should be 127.0.0.1.

How can I solve this problem?

How the other services in my PC works like that?
enter image description here

0

There are 0 answers