Lds.IpAccess 0.2.1
Lds.IpAccess
Who may open a web application from where. One ASP.NET Core middleware turns away requests:
- from countries an administrator has not allowed (geo-fencing);
- through a VPN, a data centre or Tor, which would hide the real country;
- from anywhere but a person's own addresses, for a person limited to them;
- to a restricted path (a page that signs in a shared PC, say) from anywhere but that path's addresses.
An address on a person also lets that person in from anywhere: an employee abroad, at a known hotel address. Every address carries a description ("Anna home", "Office 4G"), so the lists can be accounted for.
Whoever is turned away sees a plain page, in English or Danish, that says why and shows their IP address and the time, to pass on to an administrator.
This package has no database and no screens. The stores are ports: Lds.IpAccess.MongoDb implements them on
MongoDB, and the default keeps them in memory. An application on the Lds framework gets the administration screens
from Lds.Web.IpAccess; any other application builds its own (see What the application builds).
It came out of EW Insight, where it has run in production since October 2026.
Contents
- The order of the checks
- It fails closed
- The lists
- Address entries
- Adding it
- What the application builds
- Switching it on
- Hosting
- What it does not do
The order of the checks
The middleware runs after UseAuthentication and before UseAuthorization: the cookie has been read, so the
person is known when there is one. A Blazor circuit is opened by an HTTP request too, so the interactive pages are
covered.
- Exempt paths pass untouched: a health check, a webhook called by a machine (
IpAccessOptions.ExemptPaths). - A restricted path answers only from its own addresses or from the server itself. Nothing else is checked there: the path's addresses are the stricter list, and a person's own addresses do not open it. Only HTTP requests to the path are checked: a Blazor component reached by navigation inside an open circuit is not a request to its path, so put the action that matters (a form post, an endpoint) under the path.
- localhost passes. It is the way back in for an administrator who has locked everybody out.
- A signed-in person with addresses of their own:
- an address that matches one of theirs lets them in, and no other check runs;
- otherwise, if they are limited to their own addresses, they are turned away;
- otherwise the general rules decide.
- The general rules, when geo-fencing is on:
- a private address passes (10/8, 172.16/12, 192.168/16, 169.254/16, IPv6 unique-local and link-local);
- an address on the organisation's allowed list passes, past the country and VPN checks;
- Tor and VPN or data-centre addresses are turned away, except iCloud Private Relay;
- the country must be known, and on the allow list.
- A request without a signed-in person that failed step 5 passes only if its address is on somebody's list.
Why step 6. Somebody abroad whose address is on their own record has no cookie yet, so the application does not know who they are. Step 6 lets them as far as signing in. Once they are signed in, step 4 decides; anybody else who signs in from that address fails step 4 and step 5, and is turned away after signing in.
Speed. The lists are sorted ranges in memory, so a lookup costs microseconds. The union of everybody's addresses
(step 6) is kept in memory and read again when the application calls IUserAddressIndex.Invalidate(), and at the
latest every five minutes.
The decision is one pure function, IpAccessRules.Decide, which the middleware and the self-lockout guard both use.
It fails closed
- An unknown country is turned away, unless the address is on the person's own list.
- Lists that have never been loaded let no outside address in. On a new server, before the first download, only the exceptions get in: private addresses, people's own addresses, the allowed addresses and localhost. The page says "Your address cannot be checked right now."
- Old lists stay in use. A failed download, or one that cannot be read, never replaces a good list, however old.
A list older than 45 days shows as a warning (
IpListState.IsOld) and is raised to the observer. - A pattern that cannot be read matches nothing.
The lists
| What | Source | Licence | Checked | Format |
|---|---|---|---|---|
| IP → country | DB-IP IP to Country Lite | CC BY 4.0 | Daily for a new month | MMDB, read with MaxMind.Db |
| VPN and data centres | X4BNet lists_vpn, output/datacenter/ipv4.txt |
MIT | Daily | One CIDR per line |
| Tor exit nodes | https://check.torproject.org/torbulkexitlist |
Public | Daily | One address per line |
| iCloud Private Relay | https://mask-api.icloud.com/egress-ip-ranges.csv |
Published by Apple | Weekly | CSV: range, country, region, city |
- The server must reach
download.db-ip.com,raw.githubusercontent.com,check.torproject.organdmask-api.icloud.comover HTTPS. The addresses areIpAccessOptions.Lists; setLists.UserAgentto name the application. - DB-IP's licence requires a link to db-ip.com wherever the result is used. The turned-away page carries "IP geolocation by DB-IP"; so must every screen that shows a country from it.
- Why DB-IP: MaxMind GeoLite2 needs an account and a licence key, and its terms are stricter.
- iCloud Private Relay is let through the VPN check. It goes out through Apple's partners, whose ranges are on the
data-centre list too, so Apple's list is checked first. Its addresses carry the user's real country, so the country
check still applies. Every request let in this way is counted per day (
IAccessLogStore.PrivateRelayDaysAsync), to decide on facts whether to keep allowing it. - A broken download is refused: fewer ranges than a real list has (1000 for the data centres and Apple, 100 for Tor), a line that is not an address, or a country database that does not know 8.8.8.8.
- The last good copy is kept in the
IIpListStore, so a restart puts the lists in place within seconds.
Address entries
An entry is IpEntry { Ip, Description, CreatedBy, Created }, a value stored inside whatever owns it, never an entity
of its own. IpPattern reads Ip:
- a single address:
85.191.12.40,2a02:aa7:4000::1; - an IPv4 address ending in wildcards:
192.168.*,85.191.12.*,85.191.*.*(not85.*.12.1); - CIDR:
85.191.0.0/16,2a02:aa7:4000::/48.
Anything that would match every address (*, /0) is refused, and so is 85.191.12.40/16 (with "Did you mean
85.191.0.0/16?"). An IPv4 address that arrives as IPv6 (::ffff:1.2.3.4) counts as IPv4.
Before saving, IpAccessRules.CheckEntry and CheckEntries refuse an entry that is not a pattern, has no
description, or a description over 100 characters; the same address twice; and a person limited to their own
addresses with none. They return an EntryProblem; IpAccessText.Describe puts it into words. The application sets
CreatedBy and Created; they are never typed.
A person's addresses are IpRestriction { OnlyFromTheseAddresses, Entries }. When OnlyFromTheseAddresses is off,
the entries are extra ways in; when it is on, nothing else lets the person in.
Adding it
The usual way: the package keeps the rules. The administrator's policy and people's addresses are kept by the
package (AddIpAccessStoredRules), in MongoDB with Lds.IpAccess.MongoDb, and the screens change them through
IpAccessAdministration:
builder.Services.AddIpAccess(builder.Configuration, o =>
{
o.ApplicationName = "Tempuro";
o.ExemptPaths.Add("/health");
o.ClientIpClaimType = "client-ip"; // the lockout guard needs the address without HttpContext
o.TimeZoneId = "Europe/Copenhagen";
o.Lists.UserAgent = "Tempuro (https://tempuro.example)";
o.RestrictPathToStoredAddresses("/station");
});
builder.Services.AddIpAccessStoredRules(); // the person's identity: Entra ID's object id, or o.IdentityClaim
builder.Services.AddIpAccessMongoDb(database); // without it, everything is kept in memory
app.UseAuthentication();
app.UseIpAccess();
app.UseAuthorization();
- A person is known by their identity claim (
StoredRulesOptions.IdentityClaim; Entra ID's object id by default,oidas well), the key ofPersonAddresses.Person. A signed-in person without that claim cannot be matched: a limit kept for them does not apply, and the general rules decide. The first such sign-in is logged as a warning; setIdentityClaimto the claim the sign-in carries.IpAccessAdministration.PersonOfreads it the same way. - A change through
IpAccessAdministrationapplies to the next request on the server that made it, and within a minute (StoredRulesOptions.MaxAge) on another server sharing the database. An address removed from a person may still let a request without a signed-in person as far as signing in (step 6) for up to five minutes more there. IpAccessAdministrationchecks, stamps and saves. It does not authorize: who may change the rules, and recording that they did, is the caller's (an application on Lds:Lds.Application.IpAccess).- Two administrators at once: the policy and each person are saved whole. A save over a record somebody else
saved after it was read is refused (
EntryProblemKind.ChangedMeanwhile, naming who), rather than overwriting their change. Read it again, and make the change again. PathAddressesmay only hold the paths registered withRestrictPathToStoredAddresses(IpAccessAdministration.StoredPaths); another is refused (UnknownPath), so a typo cannot be saved and do nothing.
The other way: the application keeps the rules where it likes (on its own user and settings records), and
answers the ports itself instead of calling AddIpAccessStoredRules. What it supplies, registered
before or after AddIpAccess:
| Port | Lifetime | What it answers | Without it |
|---|---|---|---|
IIpAccessSettings |
Singleton or scoped | The GeoFence: on or off, the allowed countries, the allowed addresses. Asked on every request that is not exempt, static files included: answer from the application's cached settings, never from the database each time, and never from a copy kept in a field |
Geo-fencing is off, with one warning in the log at start-up |
IUserAddresses |
Singleton or scoped | A signed-in person's UserAddresses. Asked on every request by a signed-in person: answer from claims put on them at sign-in, or a cache |
Nobody has addresses of their own |
IUserAddressSource |
Singleton | Every address on anybody's list, for step 6. Read through a scoped database context by creating a scope with IServiceScopeFactory. Call IUserAddressIndex.Invalidate() when somebody's addresses change |
Step 6 never lets anybody in |
IIpAccessObserver |
Singleton | Told when a list fails to download, when a list is out of date (at most once a day each), and of a burst of 50 blocks from one address within 10 minutes. For monitoring; all of it is in the log already. Burst is called on the request that reached the count: queue the work and return |
Nothing beyond the log |
IIpListStore, IAccessLogStore |
Singleton | Where the lists' last good copies and the access log are kept | In memory |
A port registered as scoped where only a singleton will do makes Build() throw in Development, and would be shared
across requests elsewhere.
Configuration section IpAccess (IpAccessOptions): AlwaysAllowLocalhost, ApplicationName, ExemptPaths,
ClientIpClaimType, TimeZoneId, and Lists (Download, CountryUrl, DataCentreUrl, TorUrl,
PrivateRelayUrl, UserAgent, TimeoutSeconds). The defaults work.
An exempt or restricted path must begin with a slash, and may not be empty or / alone, which would match every
request: the application refuses to start rather than run with the check switched off.
AlwaysAllowLocalhost can be switched off only in the Development environment. Elsewhere it is always on, whatever
the configuration says. Switched off, a developer's machine can test a person's limits and the restricted paths; not
geo-fencing, since localhost is an internal address, which the general rules let in.
In the application's own tests, set IpAccess:Lists:Download to false (or replace IIpListSource), or every
test run that starts the host downloads 25 MB from four hosts.
The turned-away page is a 403 with Cache-Control: no-store, without layout, scripts or files of its own, so it
needs nothing that is itself behind the check. It is Danish when the request's culture is Danish
(UseRequestLocalization) or the browser asks for Danish before English, and English otherwise. A restricted path may
give its own reason. IpAccessOptions.TurnedAwayPage replaces the whole page; it must still credit DB-IP. Being
turned away does not sign anybody out: the same cookie works again from an allowed address.
What the application builds
An application on the Lds framework takes these from Lds.Web.IpAccess. Any other builds them, over
IpAccessAdministration when the package keeps the rules:
- The settings: geo-fencing on or off, the allowed countries (ISO codes, e.g.
DK), the allowed addresses with descriptions. Also the addresses of each restricted path. (GetPolicyAsync,SavePolicyAsync.) - Addresses per person: the entries with descriptions, and only from these addresses. Show the address and
country of the person's last sign-in, so an administrator adds the right entry. (
ListPeopleAsync,GetPersonAsync,SavePersonAsync,RemovePersonAsync.) - The self-lockout guard. Before saving a change to the settings, or to an administrator's own addresses, run
IpAccessAdministration.CheckOwnAccessAsync(or, with rules of the application's own,IpAccessRules.CheckOwnAccess) with the administrator, their current address, the rules as they would be after the change, and the path the screen is on, so a restricted path's addresses count too. Anything butVerdict.Allowedrefuses the save, withIpAccessText.OwnAccesssaying why. Show the administrator's own address, its country and its verdict at the top of the settings.- The current address: set
ClientIpClaimType, and read the claim, since a component should not useHttpContext. localhostAlwaysAllowed: fromIOptions<IpAccessOptions>, where it is forced on outside Development, never from the configuration.
- The current address: set
- The state of the lists:
IpListOverview.GetAsync()gives each list's edition, its number of ranges, when it was downloaded and checked, and its last error;IpAccessAdministration.CheckListsNowAsyncdownloads them now. A list that is not in use, orIsOld, shows as a warning, with an icon and a word, never colour alone. - The access log:
IAccessLogStore.LatestBlockedAsync(filter by verdict, search by address or person) andPrivateRelayDaysAsync. Each verdict shows as an icon and a word. - The DB-IP credit on every screen that shows a country: "IP geolocation by DB-IP", linking to db-ip.com.
IpAccessText has the package's sentences in English and Danish (Describe for a verdict, a pattern problem or an
entry problem; OwnAccess for the lockout guard). A screen with words of its own uses its own.
Switching it on
Geo-fencing is off until an administrator switches it on, so a deployment changes nobody's access. Switch it on when the lists are loaded (the state of the lists shows them in use), from an address that is allowed: the lockout guard refuses otherwise.
If everybody is locked out anyway: sign in to the server, and open the application there, so the request comes from
127.0.0.1 or ::1. The site's name must then reach it locally, not through the router; a hosts entry on the
server pointing the name to 127.0.0.1 keeps a Microsoft sign-in returning to the usual address.
Hosting
- The address checked is the one the server sees,
HttpContext.Connection.RemoteIpAddress. Directly in IIS or Kestrel, that is the client's. - Behind a reverse proxy or a load balancer, every request would come from the proxy. Add
UseForwardedHeadersbeforeUseIpAccess, withKnownProxiesorKnownNetworksset to that proxy only: trustingX-Forwarded-Forfrom anybody lets anybody choose their address. - Several servers sharing one database share the lists' copies and the access log. Each keeps its own lists in memory, and reads people's addresses again within five minutes of a change made on another.
What it does not do
- Free lists do not catch every VPN. The data-centre list catches most commercial VPNs, because they rent servers there, but also everything that goes out through a cloud provider. An address on the person lets them in.
- X4BNet's data-centre list is IPv4 only: a VPN reached over IPv6 is not caught by it.
- An open page keeps its connection until it drops, so a new rule reaches an open Blazor circuit at the latest on the next reload.
- A caller without the person's address (a bot whose messages come from the platform's servers, a webhook) cannot be checked by address. Exempt its path and secure it another way.
- Real time. The lists are checked hourly and downloaded daily; that is enough for the purpose.
Showing the top 20 packages that depend on Lds.IpAccess.
| Packages | Downloads |
|---|---|
|
Lds.IpAccess.MongoDb
The MongoDB store of Lds.IpAccess: the downloaded lists' last good copies and the access log, on the plain MongoDB driver, so it works beside any version of MongoDB.Entities.
|
44 |
|
Lds.IpAccess.MongoDb
The MongoDB store of Lds.IpAccess: the downloaded lists' last good copies and the access log, on the plain MongoDB driver, so it works beside any version of MongoDB.Entities.
|
27 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
24 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
10 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
9 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
6 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
5 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
4 |
|
Lds.IpAccess.MongoDb
The MongoDB store of Lds.IpAccess: the downloaded lists' last good copies and the access log, on the plain MongoDB driver, so it works beside any version of MongoDB.Entities.
|
3 |
|
Lds.Application.IpAccess
IP access for the Lds framework: the operations an administrator changes Lds.IpAccess's rules through, each authorized with a permission the solution supplies, answering with a Result and recorded in the audit trail. No web type, so a business layer calls them as a page does.
|
3 |
.NET 10.0
- MaxMind.Db (>= 5.2.0)