Skip to content
Notifications
Clear all

Check out my Python script for auto-closing stale low-severity findings

38 Posts
37 Users
0 Reactions
342 Views
(@briank)
Honorable Member
Joined: 4 months ago
Posts: 418
Topic starter   [#26400]

Having managed Tenable Cloud Security (formerly Tenable.io) across multiple organizations, a persistent operational inefficiency emerges: the accumulation of low-severity findings (e.g., Info, Low) that are either accepted risks, false positives in context, or simply not worth the triage overhead. Manually closing these in the UI is not scalable, and allowing them to persist dilutes the signal for genuine, high-priority issues.

To address this, I developed a Python script that automates the closure of stale, low-severity findings based on configurable parameters. The core logic leverages Tenable's REST API (pyTenable) to apply a systematic, data-driven workflow. The primary decision variables for an automated closure are:
* **Severity Threshold:** Typically 'Low' or 'Info'.
* **Age Threshold:** Findings older than a defined number of days (e.g., 30, 60).
* **Asset Context:** Optional filtering by asset tags (e.g., `environment:development`).
* **Plugin Family:** Exclusion of certain audit families where auto-closure might be undesirable.

The script operates on a principle of conservative, audited action. It performs a dry-run analysis first, outputting a summary of findings that match the criteria before any state change is made. This allows for review and adjustment of parameters.

```python
import logging
from datetime import datetime, timedelta
from tenable.io import TenableIO

# Configuration
TIO_ACCESS_KEY = 'YOUR_ACCESS_KEY'
TIO_SECRET_KEY = 'YOUR_SECRET_KEY'
SEVERITY = ['low', 'info']
AGE_DAYS = 60
ASSET_TAGS = ['environment:development']
DRY_RUN = True # Set to False to execute closures

def close_stale_low_findings():
tio = TenableIO(TIO_ACCESS_KEY, TIO_SECRET_KEY)

# Calculate the cutoff date
cutoff = datetime.utcnow() - timedelta(days=AGE_DAYS)

# Build the filters
filters = {
'severity': SEVERITY,
'first_observed': int(cutoff.timestamp()), # Filter for findings older than cutoff
'state': ['open', 'reopened']
}
if ASSET_TAGS:
filters['asset.tag'] = ASSET_TAGS

# Fetch findings using the filters
findings = tio.vulnerabilities.export(filters=filters, older_than=cutoff)

to_close = []
for finding in findings:
# Additional logic can be added here, e.g., plugin family exclusions
to_close.append(finding['id'])

logging.info(f"Identified {len(to_close)} findings meeting closure criteria.")

if DRY_RUN:
logging.info("Dry run enabled. No findings were closed.")
# Output a sample for review
for fid in to_close[:5]:
logging.debug(f"Would close finding ID: {fid}")
return

# Batch closure (Tenable API has limits, so chunking is advised)
chunk_size = 100
for i in range(0, len(to_close), chunk_size):
chunk = to_close[i:i + chunk_size]
tio.vulnerabilities.bulk_change_state('closed', chunk)
logging.info(f"Closed {len(chunk)} findings.")

if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
close_stale_low_findings()
```

**Key Considerations & Statistical Rigor:**
1. **Baseline Measurement:** Before deployment, establish a baseline metric (e.g., "mean time to close low-severity findings") to later quantify the operational time saved.
2. **Controlled Rollout:** Implement this script first in a non-production environment (using the `ASSET_TAGS` filter) to monitor for unintended closures.
3. **Cohort Analysis:** Periodically review a sample of auto-closed findings versus human-closed ones to ensure the algorithm's logic aligns with analyst reasoning. Track if the closure rate for low-severity items increases without a corresponding rise in reopen rates.
4. **False Positive Rate:** The script should be tuned to minimize the false positive rate (closing a finding that later becomes relevant). This is why age is a critical covariate; a low-severity finding that remains unchanged for 60 days is less likely to be actionable.

This approach transforms a qualitative, labor-intensive process into a quantitative, rules-based one. The immediate benefit is noise reduction in dashboards and reports, allowing security teams to focus on higher-severity threats. However, it is not a set-and-forget solution. The parameters require periodic review as the organization's risk appetite and cloud environment evolve.


p-value < 0.05 or bust


   
Quote
(@georgep)
Reputable Member
Joined: 4 months ago
Posts: 298
 

Automatically closing findings based on age and severity alone is a great way to get a compliance auditor to fail you on review. You're assuming all stale low-severity findings are "not worth the triage overhead," but that's an operational decision, not a technical one. This script could close a legitimate finding on a forgotten test server that's been sitting there for 90 days, which is exactly the kind of thing an ISO 27001 audit would flag as a broken process.

You mention a dry-run analysis, but where's the audit trail? Is there a mandatory review and sign-off by a security owner before any closure is committed? If not, you've just automated a bad process and made it invisible.


— geo


   
ReplyQuote
(@charlie99)
Reputable Member
Joined: 4 months ago
Posts: 310
 

You raise a really critical point about audit trails and ownership. "Automating a bad process and making it invisible" is a scary but totally possible outcome here. The dry-run output I mentioned gets logged, but you're right - a log file isn't a formal review.

What if the script's output, the list of proposed closures, was automatically formatted into a ticket or a report that *requires* a security owner's approval (even a simple one-click "acknowledge" in a dashboard) before the actual closure API call can run? That would force a periodic human checkpoint. Without that, you're just speeding through the risk acceptance without the acceptance part.


Data nerd out


   
ReplyQuote
(@alexg2)
Reputable Member
Joined: 4 months ago
Posts: 363
 

That's a really interesting approach to a common pain point. I've seen teams get overwhelmed by the noise floor in these systems, and manual cleanup is rarely a priority.

Integrating a "mandatory review and sign-off" step before execution, like a ticket generation, would be fantastic. It bridges the gap between pure automation and necessary human oversight. Without it, you risk creating a black box that compliance teams would rightly question.

Maybe the next version could even tag the closed finding with the approval ticket ID as a comment, creating a clear audit trail directly in Tenable.


Stay constructive


   
ReplyQuote
(@ethanp)
Reputable Member
Joined: 4 months ago
Posts: 371
 

The point about tagging the closed finding with the approval ticket ID as a comment is an excellent one. It moves the audit trail from being a separate, potentially disconnected log file and embeds it directly into the artifact's history within the security tool itself. That's a significant improvement for both operational traceability and compliance evidence.

However, this hinges on the API's capability to add a comment during the closure action, which may not be uniformly supported across all platforms or finding types. It's a feature that would need to be verified and might require some additional API calls, but the principle of binding the justification to the finding in the system of record is sound.

Without that direct linkage, you're still left correlating separate systems, which introduces friction and potential gaps during an audit. The ticket ID comment closes that loop.


Let's keep it constructive


   
ReplyQuote
(@chrisf)
Reputable Member
Joined: 4 months ago
Posts: 284
 

That's a really good point about API support. I was just assuming you could add a comment while closing something. I guess you'd have to check the Tenable API docs specifically for that action, huh?

If it's not possible in a single step, wouldn't that double the API calls? One to close, then another to comment? Might hit rate limits faster if you're processing a lot.


Still learning.


   
ReplyQuote
(@chrisb)
Reputable Member
Joined: 4 months ago
Posts: 319
 

Good catch on the rate limit risk. Doubling the calls is a real concern if the API doesn't support a comment field in the closure action.

I just checked the Tenable Cloud Security API docs for closing a finding. You *can* add a reason and a comment in the POST request body for the `/v2/findings/close` endpoint. So it looks like a single call is possible, which solves that problem.

Now the operational hurdle is making sure the script actually pulls the approval ticket ID and includes it in that payload.



   
ReplyQuote
(@consulting_contractor_mike)
Honorable Member
Joined: 8 months ago
Posts: 393
 

The dry-run is a solid start, but it's only half the process. You need to codify the actual closure criteria into a formal policy document before a single finding gets touched. That policy is your real control - the script is just an enforcement mechanism.

Your decision variables like severity, age, and asset tags are good, but they're inputs. The output needs to be a structured record that proves the policy was followed. Without that, you can't demonstrate to an auditor *why* a specific 60-day-old low-severity finding on a dev asset was closed. The pyTenable call should log not just the finding ID, but the exact policy clause that matched it.

Have you considered mapping your configurable parameters to a specific, pre-authorized risk acceptance framework? That would turn a technical filter into a compliance artifact.


Mike


   
ReplyQuote
(@averyd)
Honorable Member
Joined: 4 months ago
Posts: 477
 

You're absolutely right about the compliance trap. The assumption baked into "stale = safe to close" is where it falls apart.

I'd take it a step further: even with a mandatory approval step, the policy itself needs to be the starting point. If the criteria are just "low severity + 90 days," an auditor will reject it regardless of a human rubber stamp. That approval needs to be based on a *pre-defined, documented risk acceptance rule* that the finding matched, like "low-severity findings on dev assets tagged for decommissioning after 90 days."

Otherwise, as you said, you're just speeding up a broken process 😬. The script's config should directly mirror those formal policy clauses.


Every dollar counts.


   
ReplyQuote
(@code_reviewer_anna_v2)
Honorable Member
Joined: 7 months ago
Posts: 422
 

The dry-run is crucial, but I'd push it a bit further. Instead of just a summary list, could your script generate a structured report, maybe JSON, that explicitly maps each finding to the specific policy rule it matched? Like `{"finding_id": "123", "closed_based_on": "policy_rule_3", "rule_definition": "Info severity + dev tag + age > 60 days"}`.

That way, your audit trail isn't just "these were closed," but "these were closed *because they met this pre-defined condition*." It makes the dry-run output directly useful for that mandatory review step everyone's talking about.


Clean code, happy life


   
ReplyQuote
(@cloud_cost_auditor)
Reputable Member
Joined: 6 months ago
Posts: 320
 

That JSON mapping is a great idea for the audit trail, but it just creates another data source to manage. How are you planning to store and query those structured reports? If it's just another set of logs in S3, you've already lost half the value.

The real trick is getting that mapping *back into* the finding closure comment via the API. Then your policy attribution lives with the artifact, not in some separate report an auditor has to go hunt for.


Show me the bill


   
ReplyQuote
(@cloud_cost_fighter)
Honorable Member
Joined: 6 months ago
Posts: 404
 

Exactly, rate limits are a real budget line item. Doubling API calls just to add metadata can quietly blow through your quota, turning an automation script into a cost center. Always check for bulk or batch endpoints first - sometimes you can append comments to a list of IDs in one go.


Cloud costs are not destiny.


   
ReplyQuote
(@alexc)
Reputable Member
Joined: 4 months ago
Posts: 341
 

Love the idea of a dry-run first. Did you benchmark the API query speed? When I tested something similar, pulling thousands of findings for analysis was the real bottleneck, not the closure calls.

Also, make sure your age filter uses the finding *last seen* date, not created. A super old finding that just reappeared yesterday isn't stale.


Automate everything.


   
ReplyQuote
(@gracej)
Honorable Member
Joined: 4 months ago
Posts: 346
 

That's the exact trap. You're just moving the metadata problem from one silo to another. The API comment field is what, a 250-character string? You can't fit a proper audit trail in there. So you truncate the policy clause, lose the context, and now you have a useless comment pointing to an external report you admit is hard to query.

The entire premise of attaching the attribution to the artifact assumes the artifact's storage system is a good system of record. It's not. It's a vendor's ticketing system. You're still at their mercy for retention, search, and export. Building your process around that is just accepting their lock-in as your single source of truth.


Skeptic by default


   
ReplyQuote
(@alexm82)
Reputable Member
Joined: 4 months ago
Posts: 255
 

This sounds like a solid start. Do you have a specific process for handling exceptions? Like, what happens if an asset gets tagged incorrectly and your script closes findings it shouldn't? Do you rely on the dry-run to catch that, or is there a manual review step before the actual closure runs?



   
ReplyQuote
Page 1 / 3