
Implementing Github Advanced Security For Code Scanning
- 1 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Configure GitHub Advanced Security with CodeQL for automated static analysis and vulnerability detection across repositories at enterprise scale.
About
Configures GitHub Advanced Security with CodeQL to run automated static analysis and vulnerability detection across repositories. A security or DevSecOps team uses it to shift left and scan code for supply-chain and injection vulnerabilities at scale.
- CodeQL-based SAST across enterprise repositories
- Shift-left supply-chain and code-scanning integration
Implementing Github Advanced Security For Code Scanning by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,834 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill implementing-github-advanced-security-for-code-scanningAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Configure GitHub Advanced Security with CodeQL for automated static analysis and vulnerability detection across repositories at enterprise scale.
Files
Implementing GitHub Advanced Security for Code Scanning
Overview
GitHub Advanced Security (GHAS) integrates CodeQL-powered static application security testing directly into the GitHub development workflow. CodeQL treats code as data, enabling semantic analysis that identifies security vulnerabilities such as SQL injection, cross-site scripting, buffer overflows, and authentication flaws with significantly fewer false positives than traditional pattern-matching scanners. GHAS encompasses code scanning, secret scanning, dependency review, and Dependabot alerts to provide a comprehensive security posture for repositories.
When to Use
- When deploying or configuring implementing github advanced security for code scanning capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- GitHub Enterprise Cloud or GitHub Enterprise Server 3.0+ with GHAS license
- Repository admin or organization owner permissions
- Familiarity with GitHub Actions workflow syntax (YAML)
- Supported languages: C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, Swift
Core Concepts
CodeQL Analysis Engine
CodeQL compiles source code into a queryable database, then executes security-focused queries against that database. The query suites ship with hundreds of checks mapped to CWE identifiers and cover OWASP Top 10, SANS Top 25, and language-specific vulnerability patterns. Custom queries can be authored using the CodeQL query language (QL) to detect organization-specific anti-patterns.
Default Setup vs. Advanced Setup
Default Setup enables code scanning with a single click from the repository's Code Security settings. GitHub automatically determines the languages present, selects appropriate query suites, and configures scanning triggers. This approach requires no workflow file and is ideal for rapid onboarding.
Advanced Setup generates a .github/workflows/codeql.yml workflow file that can be customized. Teams control scheduling, language matrices, build commands for compiled languages, additional query packs, and integration with third-party SARIF producers. Advanced setup is required when custom build steps, monorepo configurations, or private query packs are needed.
Organization-Wide Rollout
For enterprises managing hundreds of repositories, GHAS supports configuring code scanning at scale using the organization-level security overview. Administrators can enable default setup across all eligible repositories, define custom security configurations, and monitor adoption through the security coverage dashboard.
Workflow
Step 1 --- Enable GHAS on the Organization
1. Navigate to Organization Settings > Code security and analysis 2. Enable GitHub Advanced Security for all repositories or selected repositories 3. Confirm license seat allocation (GHAS is billed per active committer)
Step 2 --- Configure Default Setup for Quick Wins
1. Go to Repository Settings > Code security > Code scanning 2. Click "Set up" in the CodeQL analysis row and select "Default" 3. Review the auto-detected languages and query suite (default or extended) 4. Click "Enable CodeQL" to activate scanning on push and pull request events
Step 3 --- Advanced Setup with Custom Workflow
Create .github/workflows/codeql-analysis.yml:
name: "CodeQL Analysis"
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
schedule:
- cron: '30 2 * * 1' # Weekly Monday 2:30 AM UTC
jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
security-events: write
contents: read
actions: read
strategy:
fail-fast: false
matrix:
language: ['javascript-typescript', 'python', 'java-kotlin']
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: +security-extended,security-and-quality
# For compiled languages, add build commands below
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"Step 4 --- Custom Query Packs
Install organization-specific query packs by referencing them in the workflow:
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: java-kotlin
packs: |
my-org/java-custom-queries@1.0.0
codeql/java-queries:cwe/cwe-089Step 5 --- Configure Branch Protection Rules
1. Navigate to Repository Settings > Branches > Branch protection rules 2. Enable "Require status checks to pass" and add the CodeQL analysis check 3. Enable "Require code scanning results" and set severity thresholds (e.g., block on High/Critical)
Step 6 --- Secret Scanning and Push Protection
1. Enable secret scanning from Code security settings 2. Activate push protection to block commits containing detected secrets 3. Configure custom patterns for organization-specific secrets (API keys, internal tokens)
Step 7 --- Dependency Review and Dependabot
1. Enable Dependabot alerts and security updates 2. Configure .github/dependabot.yml for automated dependency version updates 3. Enable dependency review enforcement on pull requests to block PRs that introduce known vulnerable dependencies
Query Suite Reference
| Suite | Description | Use Case |
|---|---|---|
default | High-confidence security queries | Production scanning with minimal false positives |
security-extended | Broader security queries including lower-severity findings | Comprehensive security coverage |
security-and-quality | Security plus code quality queries | Teams wanting both security and maintainability checks |
| Custom packs | Organization-authored queries | Detecting internal anti-patterns and compliance violations |
Integration with Security Workflows
SARIF Upload from Third-Party Tools
GHAS accepts SARIF (Static Analysis Results Interchange Format) uploads from external tools:
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
category: "semgrep"Security Overview Dashboard
The organization-level security overview provides:
- Risk view showing repositories with open alerts by severity
- Coverage view showing GHAS feature enablement across repositories
- Alert trends over time for tracking remediation progress
- Filter by team, language, and alert type for targeted review
Monitoring and Metrics
- Track mean time to remediate (MTTR) for code scanning alerts
- Monitor false positive rates and tune query configurations accordingly
- Review alert dismissal reasons to identify areas for developer training
- Use the API (
/repos/{owner}/{repo}/code-scanning/alerts) for custom reporting dashboards
Common Pitfalls
1. Compiled language build failures --- CodeQL requires successful compilation for C/C++, Java, C#, Go, and Swift; ensure build dependencies are available in the Actions runner 2. Ignoring scheduled scans --- Push/PR scanning misses vulnerabilities in dependencies; weekly scheduled scans catch newly disclosed CVEs in existing code 3. Over-alerting with security-and-quality --- Start with default suite and expand gradually to avoid developer alert fatigue 4. Missing GHAS license seats --- Only active committers to GHAS-enabled repositories consume license seats; plan capacity accordingly
References
GHAS Code Scanning Implementation Template
Organization Security Configuration
| Setting | Value | Notes |
|---|---|---|
| Organization | _______________ | |
| GHAS License Seats | _______________ | Active committers |
| Default Query Suite | [ ] default [ ] security-extended [ ] security-and-quality | |
| Branch Protection Enabled | [ ] Yes [ ] No | |
| Secret Scanning Enabled | [ ] Yes [ ] No | |
| Push Protection Enabled | [ ] Yes [ ] No | |
| Dependabot Enabled | [ ] Yes [ ] No |
Repository Enablement Tracker
| Repository | Languages | Setup Type | Scanning Active | Open Alerts | Date Enabled |
|---|---|---|---|---|---|
| [ ] Default [ ] Advanced | [ ] Yes [ ] No | ||||
| [ ] Default [ ] Advanced | [ ] Yes [ ] No | ||||
| [ ] Default [ ] Advanced | [ ] Yes [ ] No |
Custom Query Pack Registry
| Pack Name | Version | Description | Target Languages |
|---|---|---|---|
Alert Severity Gate Configuration
| Environment | Block on Critical | Block on High | Block on Medium | Block on Low |
|---|---|---|---|---|
| Production (main) | [x] Yes | [x] Yes | [ ] Yes | [ ] No |
| Staging (develop) | [x] Yes | [ ] Yes | [ ] No | [ ] No |
| Feature branches | [x] Yes | [ ] Yes | [ ] No | [ ] No |
Secret Scanning Custom Patterns
| Pattern Name | Regex | Description | Alert Enabled | Push Protection |
|---|---|---|---|---|
| [ ] Yes [ ] No | [ ] Yes [ ] No |
Weekly Security Review Checklist
- [ ] Review new critical and high severity alerts
- [ ] Check alert dismissal reasons for quality
- [ ] Verify new repositories have scanning enabled
- [ ] Review Dependabot alerts and merge security updates
- [ ] Check secret scanning alerts for exposed credentials
- [ ] Update security overview dashboard metrics
- [ ] Review MTTR trends and identify bottlenecks
Escalation Matrix
| Alert Severity | Response SLA | Escalation Contact | Action Required |
|---|---|---|---|
| Critical | 24 hours | Security Lead | Immediate remediation, potential incident |
| High | 72 hours | Team Lead | Prioritize in current sprint |
| Medium | 2 weeks | Developer | Schedule for next sprint |
| Low | 30 days | Developer | Add to backlog |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Implementing GitHub Advanced Security for Code Scanning
GitHub Code Scanning API
# List code scanning alerts
gh api /repos/OWNER/REPO/code-scanning/alerts?state=open
# Get specific alert
gh api /repos/OWNER/REPO/code-scanning/alerts/ALERT_NUMBER
# List analyses
gh api /repos/OWNER/REPO/code-scanning/analyses
# Upload SARIF
gh api /repos/OWNER/REPO/code-scanning/sarifs -X POST \
-f commit_sha=SHA -f ref=refs/heads/main -f sarif=@results.sarif.gzSecret Scanning API
# List secret alerts
gh api /repos/OWNER/REPO/secret-scanning/alerts?state=open
# Update alert state
gh api /repos/OWNER/REPO/secret-scanning/alerts/ALERT_NUMBER -X PATCH \
-f state=resolved -f resolution=revokedCodeQL Query Suites
| Suite | Description | False Positive Rate |
|---|---|---|
default | High-confidence security | Low |
security-extended | Broader security coverage | Medium |
security-and-quality | Security + code quality | Higher |
CodeQL Workflow (GitHub Actions)
- uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: +security-extended
- uses: github/codeql-action/autobuild@v3
- uses: github/codeql-action/analyze@v3Supported Languages
| Language | Build Required | Query Pack |
|---|---|---|
| Python | No | codeql/python-queries |
| JavaScript/TypeScript | No | codeql/javascript-queries |
| Java/Kotlin | Yes | codeql/java-queries |
| C/C++ | Yes | codeql/cpp-queries |
| C# | Yes | codeql/csharp-queries |
| Go | Yes | codeql/go-queries |
| Ruby | No | codeql/ruby-queries |
| Swift | Yes | codeql/swift-queries |
References
- GHAS Docs: https://docs.github.com/en/code-security/code-scanning
- CodeQL: https://codeql.github.com/docs/
- CodeQL Queries: https://github.com/github/codeql
- SARIF Spec: https://sarifweb.azurewebsites.net/
Standards and Frameworks Reference
OWASP Top 10 (2021) Coverage by CodeQL
| OWASP Category | CodeQL CWE Coverage | Query Suite |
|---|---|---|
| A01 Broken Access Control | CWE-22, CWE-284, CWE-639 | security-extended |
| A02 Cryptographic Failures | CWE-259, CWE-327, CWE-328 | security-extended |
| A03 Injection | CWE-77, CWE-78, CWE-79, CWE-89 | default |
| A04 Insecure Design | CWE-209, CWE-256, CWE-501 | security-and-quality |
| A05 Security Misconfiguration | CWE-16, CWE-611 | security-extended |
| A06 Vulnerable Components | Dependency Review / Dependabot | N/A (separate feature) |
| A07 Auth Failures | CWE-287, CWE-798 | default |
| A08 Data Integrity Failures | CWE-502, CWE-829 | security-extended |
| A09 Logging Failures | CWE-117, CWE-778 | security-and-quality |
| A10 SSRF | CWE-918 | default |
NIST SP 800-218 (SSDF) Alignment
- PO.3: Define security requirements --- CodeQL enforces security policies through query suites
- PW.4: Reuse existing, well-secured software --- Dependabot ensures dependencies are patched
- PW.7: Review and test code for vulnerabilities --- Automated code scanning on every PR
- PW.8: Test executable code --- SARIF integration enables combining SAST with DAST results
- RV.1: Identify and confirm vulnerabilities --- Security overview tracks alerts across the organization
CIS Software Supply Chain Security Guide
- SCS-1: Source code management security --- Branch protection rules, required reviewers
- SCS-2: Build pipelines --- CodeQL runs in GitHub Actions with pinned action versions
- SCS-5: Artifact management --- Dependency review prevents vulnerable packages from merging
ISO 27001 Control Mapping
| ISO 27001 Control | GHAS Feature |
|---|---|
| A.8.25 Secure development lifecycle | CodeQL in CI/CD pipeline |
| A.8.26 Application security requirements | Custom query packs for org standards |
| A.8.28 Secure coding | Real-time scanning on pull requests |
| A.8.29 Security testing in dev and acceptance | Required status checks with severity gates |
| A.8.31 Separation of environments | Branch protection and deployment rules |
GHAS Implementation Workflows
Workflow 1: Organization-Wide Enablement
1. Audit current repository inventory
- List all repositories in the organization
- Identify languages and build systems in use
- Estimate active committer count for licensing
|
2. Pilot phase (2-4 weeks)
- Enable GHAS on 5-10 representative repositories
- Use default setup for initial scanning
- Collect baseline alert counts and false positive rates
|
3. Triage pilot results
- Review alerts by severity (Critical, High, Medium, Low)
- Dismiss confirmed false positives with documented reasons
- Create remediation issues for confirmed vulnerabilities
|
4. Tune configuration
- Adjust query suites based on false positive feedback
- Write custom queries for organization-specific patterns
- Configure alert dismissal policies
|
5. Broad rollout
- Enable default setup across remaining repositories
- Configure organization-level security configurations
- Set branch protection rules requiring code scanning checks
|
6. Continuous monitoring
- Review security overview dashboard weekly
- Track MTTR for code scanning alerts
- Report metrics to security leadership monthlyWorkflow 2: Pull Request Security Gate
Developer pushes code to feature branch
|
PR is created targeting main
|
CodeQL analysis triggers automatically
|
Dependency review checks for vulnerable dependencies
|
Secret scanning checks for hardcoded credentials
|
Results posted as PR check and inline annotations
|
[Pass] All checks pass --> PR is eligible for merge
[Fail] Critical/High findings --> PR is blocked
|
Developer reviews findings and applies fixes
|
Re-push triggers re-analysis
|
Merge after all checks pass and reviewer approvalWorkflow 3: Custom CodeQL Query Development
1. Identify recurring vulnerability pattern not caught by default queries
|
2. Set up CodeQL development environment
- Install CodeQL CLI
- Clone CodeQL standard library repository
- Create workspace with target codebase database
|
3. Author the query in QL language
- Define source, sink, and taint-tracking configuration
- Add metadata (@name, @description, @kind, @problem.severity, @security-severity, @precision, @id, @tags)
|
4. Test the query
- Create test cases with expected results
- Run `codeql test run` against test database
- Validate precision and recall
|
5. Package the query
- Create qlpack.yml with version and dependencies
- Publish to GitHub Container Registry or internal package registry
|
6. Deploy to scanning workflow
- Reference the query pack in codeql-action/init step
- Monitor results for the new query across repositoriesWorkflow 4: SARIF Integration with External Tools
External SAST/DAST tool runs scan
|
Tool outputs results in SARIF 2.1.0 format
|
GitHub Actions uploads SARIF via codeql-action/upload-sarif
|
Results appear in Security tab alongside CodeQL findings
|
Unified triage workflow across all scanning tools
|
Alert deduplication based on location and rule ID#!/usr/bin/env python3
"""Agent for managing GitHub Advanced Security code scanning with CodeQL."""
import json
import argparse
import subprocess
from datetime import datetime
from collections import Counter
def gh_api(endpoint, method="GET"):
"""Call GitHub API via gh CLI."""
cmd = ["gh", "api", endpoint, "--method", method]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return {"error": result.stderr.strip()}
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
return {"raw": result.stdout.strip()}
def get_code_scanning_alerts(owner, repo, state="open"):
"""Get code scanning alerts for a repository."""
alerts = gh_api(f"/repos/{owner}/{repo}/code-scanning/alerts?state={state}&per_page=100")
if isinstance(alerts, dict) and "error" in alerts:
return alerts
return alerts if isinstance(alerts, list) else []
def get_secret_scanning_alerts(owner, repo, state="open"):
"""Get secret scanning alerts for a repository."""
alerts = gh_api(f"/repos/{owner}/{repo}/secret-scanning/alerts?state={state}&per_page=100")
if isinstance(alerts, dict) and "error" in alerts:
return alerts
return alerts if isinstance(alerts, list) else []
def get_dependabot_alerts(owner, repo, state="open"):
"""Get Dependabot alerts for a repository."""
alerts = gh_api(f"/repos/{owner}/{repo}/dependabot/alerts?state={state}&per_page=100")
if isinstance(alerts, dict) and "error" in alerts:
return alerts
return alerts if isinstance(alerts, list) else []
def analyze_code_scanning_alerts(alerts):
"""Analyze code scanning alerts and produce summary."""
if not isinstance(alerts, list):
return {"error": "No alerts data"}
by_severity = Counter()
by_rule = Counter()
by_tool = Counter()
critical_alerts = []
for alert in alerts:
rule = alert.get("rule", {})
severity = rule.get("security_severity_level", rule.get("severity", "unknown"))
by_severity[severity] += 1
by_rule[rule.get("id", "unknown")] += 1
tool = alert.get("tool", {}).get("name", "unknown")
by_tool[tool] += 1
if severity in ("critical", "high"):
critical_alerts.append({
"number": alert.get("number"),
"rule": rule.get("id", ""),
"description": rule.get("description", "")[:120],
"severity": severity,
"state": alert.get("state", ""),
"created_at": alert.get("created_at", ""),
"html_url": alert.get("html_url", ""),
})
return {
"total_alerts": len(alerts),
"by_severity": dict(by_severity),
"by_rule": dict(by_rule.most_common(10)),
"by_tool": dict(by_tool),
"critical_and_high": critical_alerts[:20],
}
def analyze_secret_alerts(alerts):
"""Analyze secret scanning alerts."""
if not isinstance(alerts, list):
return {"error": "No alerts data"}
by_type = Counter()
for alert in alerts:
by_type[alert.get("secret_type_display_name", alert.get("secret_type", "unknown"))] += 1
return {
"total_secrets": len(alerts),
"by_type": dict(by_type),
"alerts": [
{"number": a.get("number"), "type": a.get("secret_type_display_name", ""),
"state": a.get("state", ""), "created_at": a.get("created_at", "")}
for a in alerts[:20]
],
}
def analyze_dependabot_alerts(alerts):
"""Analyze Dependabot vulnerability alerts."""
if not isinstance(alerts, list):
return {"error": "No alerts data"}
by_severity = Counter()
by_ecosystem = Counter()
for alert in alerts:
vuln = alert.get("security_vulnerability", alert.get("security_advisory", {}))
severity = vuln.get("severity", alert.get("severity", "unknown"))
by_severity[severity] += 1
dep = alert.get("dependency", {})
pkg = dep.get("package", {})
by_ecosystem[pkg.get("ecosystem", "unknown")] += 1
return {
"total_alerts": len(alerts),
"by_severity": dict(by_severity),
"by_ecosystem": dict(by_ecosystem),
}
def generate_codeql_workflow(languages, query_suite="security-extended"):
"""Generate a CodeQL analysis GitHub Actions workflow."""
lang_list = ", ".join(f"'{l}'" for l in languages)
return f"""name: CodeQL Analysis
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
schedule:
- cron: '30 2 * * 1'
jobs:
analyze:
name: Analyze (${{{{ matrix.language }}}})
runs-on: ubuntu-latest
permissions:
security-events: write
contents: read
actions: read
strategy:
fail-fast: false
matrix:
language: [{lang_list}]
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with:
languages: ${{{{ matrix.language }}}}
queries: +{query_suite}
- uses: github/codeql-action/autobuild@v3
- uses: github/codeql-action/analyze@v3
with:
category: "/language:${{{{ matrix.language }}}}"
"""
def full_security_audit(owner, repo):
"""Run full GHAS security audit for a repository."""
code_alerts = get_code_scanning_alerts(owner, repo)
secret_alerts = get_secret_scanning_alerts(owner, repo)
dependabot_alerts = get_dependabot_alerts(owner, repo)
return {
"code_scanning": analyze_code_scanning_alerts(code_alerts),
"secret_scanning": analyze_secret_alerts(secret_alerts),
"dependabot": analyze_dependabot_alerts(dependabot_alerts),
}
def main():
parser = argparse.ArgumentParser(description="GitHub Advanced Security Agent")
parser.add_argument("--owner", help="Repository owner")
parser.add_argument("--repo", help="Repository name")
parser.add_argument("--action", choices=["audit", "code-alerts", "secrets",
"dependabot", "gen-workflow"],
default="audit")
parser.add_argument("--languages", nargs="+", default=["python", "javascript-typescript"])
parser.add_argument("--output", default="ghas_report.json")
args = parser.parse_args()
report = {"generated_at": datetime.utcnow().isoformat(), "results": {}}
if args.action == "audit" and args.owner and args.repo:
results = full_security_audit(args.owner, args.repo)
report["results"] = results
cs = results["code_scanning"]
print(f"[+] Code scanning: {cs.get('total_alerts', 0)} alerts")
print(f"[+] Secrets: {results['secret_scanning'].get('total_secrets', 0)}")
print(f"[+] Dependabot: {results['dependabot'].get('total_alerts', 0)}")
elif args.action == "code-alerts" and args.owner and args.repo:
alerts = get_code_scanning_alerts(args.owner, args.repo)
analysis = analyze_code_scanning_alerts(alerts)
report["results"]["code_scanning"] = analysis
print(f"[+] {analysis.get('total_alerts', 0)} code scanning alerts")
elif args.action == "secrets" and args.owner and args.repo:
alerts = get_secret_scanning_alerts(args.owner, args.repo)
analysis = analyze_secret_alerts(alerts)
report["results"]["secret_scanning"] = analysis
print(f"[+] {analysis.get('total_secrets', 0)} secret alerts")
elif args.action == "gen-workflow":
workflow = generate_codeql_workflow(args.languages)
report["results"]["workflow"] = workflow
print("[+] CodeQL workflow generated")
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
GitHub Advanced Security Code Scanning Alert Management
Uses the GitHub REST API to query, triage, and report on CodeQL
code scanning alerts across an organization's repositories.
"""
import json
import os
import sys
import urllib.request
import urllib.error
from datetime import datetime, timedelta
from collections import defaultdict
def get_github_headers(token: str) -> dict:
return {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
def github_api_get(url: str, token: str) -> list | dict:
headers = get_github_headers(token)
results = []
page = 1
while True:
paginated_url = f"{url}{'&' if '?' in url else '?'}per_page=100&page={page}"
req = urllib.request.Request(paginated_url, headers=headers)
try:
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read().decode())
if isinstance(data, list):
if not data:
break
results.extend(data)
page += 1
else:
return data
except urllib.error.HTTPError as e:
print(f"HTTP {e.code} for {paginated_url}: {e.read().decode()}")
break
return results
def list_org_repos(org: str, token: str) -> list:
url = f"https://api.github.com/orgs/{org}/repos?type=all"
repos = github_api_get(url, token)
return [r["full_name"] for r in repos if isinstance(r, dict)]
def get_code_scanning_alerts(repo: str, token: str, state: str = "open") -> list:
url = f"https://api.github.com/repos/{repo}/code-scanning/alerts?state={state}"
return github_api_get(url, token)
def categorize_alerts(alerts: list) -> dict:
categories = defaultdict(lambda: defaultdict(int))
for alert in alerts:
rule = alert.get("rule", {})
severity = rule.get("security_severity_level", "unknown")
cwe_tags = [t for t in rule.get("tags", []) if t.startswith("cwe-")]
tool_name = alert.get("tool", {}).get("name", "unknown")
categories["by_severity"][severity] += 1
categories["by_tool"][tool_name] += 1
for cwe in cwe_tags:
categories["by_cwe"][cwe] += 1
return dict(categories)
def calculate_mttr(alerts: list) -> dict:
resolved = [a for a in alerts if a.get("state") == "fixed"]
if not resolved:
return {"total_resolved": 0, "avg_mttr_hours": None}
durations = []
for alert in resolved:
created = datetime.fromisoformat(alert["created_at"].replace("Z", "+00:00"))
fixed = datetime.fromisoformat(
alert.get("fixed_at", alert.get("dismissed_at", "")).replace("Z", "+00:00")
)
durations.append((fixed - created).total_seconds() / 3600)
return {
"total_resolved": len(resolved),
"avg_mttr_hours": round(sum(durations) / len(durations), 1),
"min_mttr_hours": round(min(durations), 1),
"max_mttr_hours": round(max(durations), 1),
}
def generate_org_report(org: str, token: str) -> dict:
repos = list_org_repos(org, token)
report = {
"organization": org,
"generated_at": datetime.utcnow().isoformat() + "Z",
"total_repositories": len(repos),
"repositories_with_scanning": 0,
"total_open_alerts": 0,
"severity_summary": defaultdict(int),
"top_cwes": defaultdict(int),
"repo_details": [],
}
for repo in repos:
alerts = get_code_scanning_alerts(repo, token, state="open")
if not alerts:
continue
report["repositories_with_scanning"] += 1
report["total_open_alerts"] += len(alerts)
categories = categorize_alerts(alerts)
for sev, count in categories.get("by_severity", {}).items():
report["severity_summary"][sev] += count
for cwe, count in categories.get("by_cwe", {}).items():
report["top_cwes"][cwe] += count
closed_alerts = get_code_scanning_alerts(repo, token, state="fixed")
mttr = calculate_mttr(closed_alerts)
report["repo_details"].append(
{
"repository": repo,
"open_alerts": len(alerts),
"severity_breakdown": dict(categories.get("by_severity", {})),
"mttr": mttr,
}
)
report["severity_summary"] = dict(report["severity_summary"])
top_cwes_sorted = sorted(report["top_cwes"].items(), key=lambda x: x[1], reverse=True)[:10]
report["top_cwes"] = dict(top_cwes_sorted)
return report
def print_report(report: dict) -> None:
print(f"\n{'='*60}")
print(f"GHAS Code Scanning Report: {report['organization']}")
print(f"Generated: {report['generated_at']}")
print(f"{'='*60}")
print(f"Total repositories: {report['total_repositories']}")
print(f"Repositories with scanning enabled: {report['repositories_with_scanning']}")
coverage = (
report["repositories_with_scanning"] / report["total_repositories"] * 100
if report["total_repositories"] > 0
else 0
)
print(f"Coverage: {coverage:.1f}%")
print(f"Total open alerts: {report['total_open_alerts']}")
print(f"\nSeverity Summary:")
for sev in ["critical", "high", "medium", "low", "unknown"]:
count = report["severity_summary"].get(sev, 0)
if count > 0:
print(f" {sev.upper():12s}: {count}")
print(f"\nTop CWEs:")
for cwe, count in report.get("top_cwes", {}).items():
print(f" {cwe:15s}: {count}")
print(f"\nRepository Details:")
for repo in sorted(report["repo_details"], key=lambda r: r["open_alerts"], reverse=True):
mttr_str = (
f"{repo['mttr']['avg_mttr_hours']}h" if repo["mttr"]["avg_mttr_hours"] else "N/A"
)
print(f" {repo['repository']:40s} | Open: {repo['open_alerts']:4d} | Avg MTTR: {mttr_str}")
def main():
token = os.environ.get("GITHUB_TOKEN")
if not token:
print("Error: GITHUB_TOKEN environment variable is required")
sys.exit(1)
org = os.environ.get("GITHUB_ORG")
if not org:
print("Error: GITHUB_ORG environment variable is required")
sys.exit(1)
print(f"Fetching code scanning data for organization: {org}")
report = generate_org_report(org, token)
print_report(report)
output_file = f"ghas_report_{org}_{datetime.utcnow().strftime('%Y%m%d')}.json"
with open(output_file, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\nDetailed report saved to: {output_file}")
if __name__ == "__main__":
main()