Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected revert with vector #150

Merged
merged 20 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions .github/workflows/test-detectors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
matrix:
os:
- ubuntu-latest
- macos-latest
- macos-13
runs-on: ${{ matrix.os }}
steps:
- name: Checkout repository
Expand Down Expand Up @@ -97,7 +97,7 @@ jobs:
matrix:
os:
- ubuntu-latest
- macos-latest
- macos-13
detector: ${{fromJson(needs.prepare-detector-matrix.outputs.matrix)}}
runs-on: ${{ matrix.os }}
outputs:
Expand All @@ -121,7 +121,10 @@ jobs:
restore-keys: ${{ runner.os }}-tests-

- name: Run unit and integration tests
run: python scripts/run-tests.py --detector=${{ matrix.detector }}
run: |
rustup toolchain install nightly-2023-12-16-x86_64-apple-darwin
rustup component add rust-src --toolchain nightly-2023-12-16-x86_64-apple-darwin
python scripts/run-tests.py --detector=${{ matrix.detector }}

comment-on-pr:
name: Comment on PR
Expand All @@ -136,11 +139,13 @@ jobs:
id: ubuntu_status
working-directory: build-status-ubuntu-latest
run: echo "status=$(cat status-ubuntu-latest.txt)" >> $GITHUB_OUTPUT
continue-on-error: true

- name: Read macOS build status
id: macos_status
working-directory: build-status-macos-latest
run: echo "status=$(cat status-macos-latest.txt)" >> $GITHUB_OUTPUT
continue-on-error: true

- name: Find comment
id: find_comment
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@ node_modules
.vscode/
.idea/
!/.vscode/

**/__pycache__/
16 changes: 16 additions & 0 deletions detectors/dos-unexpected-revert-with-vector/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "dos-unexpected-revert-with-vector"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
scout-audit-clippy-utils = { workspace = true }
dylint_linting = { workspace = true }
if_chain = { workspace = true }


[package.metadata.rust-analyzer]
rustc_private = true
97 changes: 97 additions & 0 deletions detectors/dos-unexpected-revert-with-vector/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#![feature(rustc_private)]
#![warn(unused_extern_crates)]
#![feature(let_chains)]

extern crate rustc_hir;
extern crate rustc_middle;
extern crate rustc_span;

use rustc_hir::intravisit::walk_expr;
use rustc_hir::intravisit::Visitor;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Ty;
use rustc_span::def_id::DefId;
use rustc_span::Span;
use scout_audit_clippy_utils::diagnostics::span_lint;

const LINT_MESSAGE: &str = "This vector operation is called without access control";

dylint_linting::impl_late_lint! {
pub UNEXPECTED_REVERT_WARN,
Warn,
"",
UnexpectedRevertWarn::default(),
{
name: "Unexpected Revert Inserting to Storage",
long_message: " It occurs by preventing transactions by other users from being successfully executed forcing the blockchain state to revert to its original state.",
severity: "Medium",
help: "https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/dos-unexpected-revert-with-vector",
vulnerability_class: "Denial of Service",
}
}

#[derive(Default)]
pub struct UnexpectedRevertWarn {}
impl UnexpectedRevertWarn {
pub fn new() -> Self {
Self {}
}
}

impl<'tcx> LateLintPass<'tcx> for UnexpectedRevertWarn {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: rustc_hir::intravisit::FnKind<'tcx>,
_: &'tcx rustc_hir::FnDecl<'tcx>,
body: &'tcx rustc_hir::Body<'tcx>,
_: Span,
_localdef: rustc_span::def_id::LocalDefId,
) {
struct UnprotectedVectorFinder<'tcx, 'tcx_ref> {
cx: &'tcx_ref LateContext<'tcx>,
push_def_id: Option<DefId>,
push_span: Option<Span>,
require_auth: bool,
}
impl<'tcx> Visitor<'tcx> for UnprotectedVectorFinder<'tcx, '_> {
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
if let ExprKind::MethodCall(path, _receiver, ..) = expr.kind {
let defid = self.cx.typeck_results().type_dependent_def_id(expr.hir_id);
let ty = Ty::new_foreign(self.cx.tcx, defid.unwrap());
if path.ident.name.to_string() == "require_auth" {
//println!("este es un require auth");
self.require_auth = true;
}
if ty.to_string().contains("soroban_sdk::Vec")
&& (path.ident.name.to_string() == "push_back"
|| path.ident.name.to_string() == "push_front")
{
self.push_def_id = defid;
self.push_span = Some(path.ident.span);
}
}
walk_expr(self, expr);
}
}

let mut uvf_storage = UnprotectedVectorFinder {
cx,
push_def_id: None,
push_span: None,
require_auth: false,
};

walk_expr(&mut uvf_storage, body.value);

if uvf_storage.push_def_id.is_some() && !uvf_storage.require_auth {
span_lint(
uvf_storage.cx,
UNEXPECTED_REVERT_WARN,
uvf_storage.push_span.unwrap(),
LINT_MESSAGE,
);
}
}
}
6 changes: 5 additions & 1 deletion scripts/run-fmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ def run_fmt(directories):
if is_rust_project(root):
start_time = time.time()
returncode, _, stderr = run_subprocess(
["cargo", "fmt", "--all", "--check"],
["cargo", "fmt"],
cwd=root,
)
returncode, _, stderr = run_subprocess(
["cargo", "fmt", "--check"],
cwd=root,
)
print_results(
Expand Down
7 changes: 4 additions & 3 deletions scripts/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def print_results(returncode, error_message, check_type, root, elapsed_time):
)
if returncode != 0:
print(f"\n{RED}{check_type.capitalize()} {issue_type} found in: {root}{ENDC}\n")
for line in error_message.strip().split("\n"):
print(f"| {line}")
print("\n")
if not error_message is None:
for line in error_message.strip().split("\n"):
print(f"| {line}")
print("\n")
22 changes: 22 additions & 0 deletions test-cases/dos-unexpected-revert-with-vector/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[workspace]
exclude = [".cargo", "target"]
members = ["dos-unexpected-revert-with-vector-*/*"]
resolver = "2"

[workspace.dependencies]
soroban-sdk = { version = "=20.0.0" }

[profile.release]
codegen-units = 1
debug = 0
debug-assertions = false
lto = true
opt-level = "z"
overflow-checks = true
panic = "abort"
strip = "symbols"

[profile.release-with-logs]
debug-assertions = true
inherits = "release"

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
edition = "2021"
name = "dos-unexpected-revert-with-vector-remediated-1"
version = "0.1.0"

[lib]
crate-type = ["cdylib"]

[dependencies]
soroban-sdk = { workspace = true }

[dev_dependencies]
soroban-sdk = { workspace = true, features = ["testutils"] }

[features]
testutils = ["soroban-sdk/testutils"]
Loading
Loading