跳到正文
DEV Community· vadim albarov·· 1 小時前AI 評分53

AI 找出漏洞快過修補,BehaviorLock 封鎖 API 未記錄的行為

AI Finds Holes Faster Than We Can Patch Them. So My API Blocks Everything It Has Not Done Before

AI 導讀

作者 Vadim Albarov 公開 ASP.NET Core 開源函式庫 BehaviorLock,以測試記錄 API 端點的 SQL 及外連行為,並封鎖未列入設定檔的存取。

正文

Facts in the opening, and how far each was checked on 2026-11-19:

  • 63 / 44 / 32 / 5 days: read on the Google Cloud page itself (post of 2024-10-15, 138 vulnerabilities, mean, measured against the patch release). The page also says that the 2023 mean is 47 days when the outliers stay in. I left that out. Decide if you want it.
  • Minus 1 (2024) and minus 7 (2025, an estimate): read on Help Net Security, which gives Google's threat team as the source. I did not open M-Trends 2026 itself. [check]
  • DARPA: 54 of 63 found, 43 patched, 18 real ones, about $152 per task, patches in 45 minutes on average: read on the darpa.mil page.
  • Anthropic: "thousands of zero-day vulnerabilities", "every major operating system and every major web browser", announced 2026-04-07: read on anthropic.com/glasswing.
  • "More than 10,000 high- or critical-severity": read on Help Net Security (2026-05-26). It links to an Anthropic update that I did not open. [check]

Everything about the repo is from v1 and was checked there: 197 tests passed and 2 skipped, the real-server tests passed, 80,000 / 8,334 / 58 / 0 from articles/behaviorlock/v1compare, the log line and status codes from the sample API in Enforce mode. Performance numbers are copied from the README and were not run again.

Yours to fix:

  • "What I plan to do" is my guess. I built it from the Limits section of the README. Replace it with your real plan and order.
  • The opening states an opinion in your name ("I think we should plan for a world where..."). Make it as strong or as careful as you mean it.
  • No NuGet package found, so no install line. No cover image yet. -->

In 2018 and 2019, attackers needed 63 days on average to exploit a vulnerability after its patch came out. Google's Mandiant team measures this every year. In 2021 and 2022 it was 32 days. In 2023 it was 5 days. For 2024 the number was minus 1, and the estimate for 2025 is minus 7.

A negative number means that the average attack starts before the patch exists.

Most of that drop happened before AI did much in security. Now add AI.

  • August 2025. In the final of DARPA's AI Cyber Challenge, fully automatic systems found 54 of 63 planted vulnerabilities and patched 43. They also found 18 real ones that nobody had planted. The average cost was about $152 per task.
  • April 2026. Anthropic said that its Mythos Preview model had found thousands of zero-day vulnerabilities, many of them critical, "in every major operating system and every major web browser". By the end of May the count was above 10,000 high or critical findings.

Both of these are the defending side, with a disclosure process and time for the vendors. But a skill like this does not stay on one side. I think we should plan for a world where an automatic scanner can find an unknown hole in almost any system, on any day, for little money.

Now look at how we defend. Someone reports the hole. Someone writes the fix. Someone reviews it, tests it and deploys it. There is a person in every step, and the whole loop takes days when it goes well. When the attack takes hours, the engineer has no time to react. It does not matter how good the engineer is.

So I asked another question. What kind of defense needs no time to react?

It must work without knowing the attack, because the attack is new. It must work without a person, because no person is fast enough. I see one design that fits both: do not look for bad things at all. Know what the system does when it works correctly, and stop everything else at the moment it happens.

I cannot build that for an operating system or a browser. I can try it for the layer that I write myself: the API. The result is BehaviorLock, a small open source library for ASP.NET Core.

Block what is not proven

An API endpoint is a boring thing, and that is its strength. An endpoint that returns one order runs one SELECT on one table. It did that yesterday and it will do that tomorrow. It has no reason to ever read the Users table, and no reason to call a host it has never called.

So BehaviorLock writes down what each endpoint touches, and blocks the rest. "Proven" has a simple meaning here: a test sent a legal request, and this is what the endpoint did.

  1. Record. Your integration tests send one legal request per legal path. The guard is in Learn mode and records every SQL statement and every outbound HTTP call of each endpoint.
  2. Commit. The result is a file, behavior.lock.json. It works like a package lock file, but it pins behavior, not versions.
  3. Enforce. In production the guard checks each access before it runs. An access that is not in the file never runs. The request gets a 403, and an alert is raised.

A part of the file from the sample app:

{
  "GET /orders/{id:int}": [
    "sql: SELECT \"o\".\"Id\", \"o\".\"Total\", \"o\".\"UserId\" FROM \"Orders\" AS \"o\" WHERE \"o\".\"Id\" = ? LIMIT ?"
  ],
  "GET /products/search": [
    "sql: SELECT * FROM Products WHERE Name LIKE ?"
  ],
  "POST /orders": [
    "http: POST https://payments.example.com",
    "sql: INSERT INTO \"Orders\" (\"Total\", \"UserId\") VALUES (?) RETURNING \"Id\""
  ]
}

A sql entry is the shape of a statement: the SQL text with every value replaced by ?. An http entry is the method, scheme, host and port of an outbound call.

The guard has no list of attacks. It cannot be out of date, because it has nothing to update. A new attack technique is still blocked on its first day, as long as it makes an endpoint touch something new.

What I have today

It is an MVP. It targets .NET 11 and covers EF Core and IHttpClientFactory. The setup is three calls:

builder.Services.AddBehaviorLock(options =>
    builder.Configuration.GetSection("BehaviorLock").Bind(options));

builder.Services.AddDbContext<ShopDb>((services, options) => options
    .UseSqlite(connectionString)
    .UseBehaviorLock(services));

app.UseBehaviorLock();

The repo has a small shop API with weaknesses built in on purpose. The tests run each attack twice: with the guard off, to prove the harm is real, and in Enforce mode, to prove it is stopped.

Weakness Request What the guard sees
SQL injection in a string UNION SELECT ... FROM Users New SQL shape
SQL injection in a string '; DELETE FROM Users; -- A second statement
SQL injection in login alice@example.com' -- New SQL shape
Blind SQL injection in ORDER BY CASE WHEN (SELECT ...) THEN Name ELSE Price END New SQL shape
Mass assignment PATCH /users/1 with "IsAdmin": true UPDATE sets a new column
Plain bug DELETE /orders/0 DELETE without WHERE
Forgotten debug switch GET /orders/1?debug=true The endpoint reads a new table
SSRF url=http://169.254.169.254/... New outbound host
SSRF Another port on a legal host New outbound port
Compromised dependency An order with a high total New outbound host

Ten rows, and the guard has no rule for any of them. Two rows show the point best.

The debug switch. Someone left a ?debug=true in the order endpoint, and it returns every user with their password. There is nothing bad in that request. No quote, no payload, nothing a signature could match. The guard does not look at the request. It sees that an endpoint which reads Orders now wants to read Users:

BehaviorLock violation (blocked): endpoint 'GET /orders/{id:int}' attempted
'sql: SELECT "u"."Id", "u"."DisplayName", "u"."Email", "u"."IsAdmin", "u"."Password" FROM "Users" AS "u"'

The dependency. The payment client in the sample stands for a package that was taken over. It works as expected, but it copies every order above 1000 to another host. The tests place an order of 120, so no test ever sees that code run. This is the closest thing to a zero-day at this layer: bad code inside something you trust, on a path that nobody has looked at. In production the first large order tries to call a host that is not in the profile. The call never leaves the server.

The cost is small. On a local SQLite file, which is the worst case for the guard, one EF Core query loses about 2% to 3% of throughput. Latency percentiles differ by 0.04 ms or less. A blocked injection is about 2% faster than the same API without the guard, because blocking the attack costs less than running it.

Where the person went

The blocking needs no person. That was the goal.

Learning new legal behavior does need a person, and that is on purpose. Tests never cover every legal path, so the default mode is Audit: report, but allow. The guard writes each unknown access to a pending file. A person reads it and decides: this is a legal path that the tests missed, or this is an attack. Legal paths get a test and move into the profile. When the pending file stays empty, the endpoint goes to Enforce.

If the guard could approve new behavior by itself, an attacker would teach it. So the human work did not go away. It moved. It now happens before the attack, in a pull request where the profile diff shows that an endpoint touches something new. And it happens after the attack, in a review of what was blocked. It does not happen during the attack, when there is no time.

The guard is code too

A world where scanners find holes everywhere includes the hole in my guard. I had one in the first version.

To turn WHERE Name = 'alice' into WHERE Name = ?, the guard must find the end of the string at the same place as the database. The first version used the rule of standard SQL. MySQL, by default, reads a backslash as an escape. So take a query that is built from two form fields, send one backslash as the name, and send OR 1=1 -- as the city:

SELECT Name FROM Users WHERE Name = '\' AND City = ' OR 1=1 -- '

The guard saw two strings and the legal shape, WHERE Name = ? AND City = ?. MySQL saw one string, '\' AND City = ', then OR 1=1, and returned every row. The attacker did not need a single quote character.

A backslash rule does not fix it, because MySQL and PostgreSQL can turn that escape on and off with a server setting, and the guard cannot see the setting. So the guard now reads each string both ways. When the two readings end at different places, it does not normalize the command. It keeps the whole text, which can then only match the exact same text in the profile.

I did not want to trust my own reading of the manuals again, so the repo has a test where the database is the judge. It builds commands from random pieces, runs each one on a real server, and counts the rows. A command that returns every row ran injected code, so its shape must differ from the legal shape.

First version Current version
Random commands on MySQL 8.4 and PostgreSQL 17 80,000 80,000
Commands that returned every row 8,334 8,334
Of those, with the legal shape 58 0

58 of 8,334 is 0.7%. It looks small. A random test tries things blind. An attacker with a good model needs one of the 58, and will find it.

Pros and cons

What speaks for it

  • It needs no knowledge of the attack. The first use of a new technique is blocked like the thousandth.
  • It needs no person and no patch at the moment of the attack.
  • It also stops things that are not attacks: a bug that deletes a table, a debug switch, a package that changed.
  • The profile is in git. A change in what an endpoint touches is a line in a diff that a reviewer can question.
  • It is cheap at run time.

What speaks against it

  • An attack that stays inside the profile passes. Reading the order of another user has the same SQL shape as reading your own. Broken authorization, business logic errors, XSS and DoS are invisible to it. The repo keeps two such cases in a test class named KnownLimitTests, so nobody forgets them.
  • It guards my endpoints, not the operating system, the runtime or the web server below them. Most of the zero-days from the first section are down there. The guard also runs inside the app process, so an attacker with code execution can turn it off.
  • Today it only sees EF Core and IHttpClientFactory. Dapper, raw ADO.NET, a new HttpClient(), files and processes are not checked.
  • It is as good as your tests. A legal path that no test covers gets a 403 in Enforce mode. Audit mode and the pending file exist for that reason, and they cost review time.
  • The profile records what the code does, not what it should do. If a harmful path runs during recording, it becomes legal.
  • The SQL part is a small scanner, not a parser. The random test finds many errors. It does not prove that there are none.

So this does not replace parameters, authorization checks or patching. It is a layer for the hours when all of those are late.

What I plan to do

  • Cover more ways out of the process: Dapper and raw ADO.NET, a directly created HttpClient, HTTP redirects, file access, process start.
  • Cover code outside a request, such as background jobs.
  • Build a tool that collects the pending files of many instances and moves reviewed entries into the approved file. Today both steps are done by hand.
  • Compare the SQL Server rules with a real server, as I did for MySQL and PostgreSQL.
  • Publish a NuGet package.

The question

I do not know if the world of the first section arrives in one year or in five. I do think that "find, report, patch, deploy" will lose to a scanner that needs an hour. Something has to stand in the request path that needs no person and no update.

BehaviorLock is my attempt at one piece of that. The code is at github.com/valbarov/BehaviorLock, under Apache-2.0. If you find a request that makes an endpoint do something new and still passes, please open an issue. That is the bug I most want to hear about.

If a scanner found a hole in your API tonight, what would stop the request before anyone on your team is awake?

來源:DEV Community · dev.to