Skip to content

Commit

Permalink
Merge pull request #4 from VulnPlanet/scale-1
Browse files Browse the repository at this point in the history
Scale 1
  • Loading branch information
kajojify authored Mar 15, 2024
2 parents 3887ee5 + f23c475 commit fbe2b02
Show file tree
Hide file tree
Showing 5 changed files with 186 additions and 289 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ cargo build
cargo run
```
3. Run

Note: By default, only critical and high severity findings are validated. To validate all findings, use the `--all-severities` flag.

```bash
l3x smart-contracts-folder-to-analyse
```
Expand Down
33 changes: 12 additions & 21 deletions etc/patterns-rust.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
| ID | Title | Severity | Description | Fix |
|----------|-----------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| RUST001 | Undefined Behavior | Critical | Operations that could lead to undefined behavior, such as dereferencing a raw pointer or accessing arrays out-of-bounds without proper checks. | Ensure all accesses within unsafe blocks are checked and validated to prevent undefined behavior. Use safe abstractions where possible. |
| RUST002 | Data Races | High | Concurrent data access without proper synchronization can lead to data races. | Use synchronization primitives like Mutex or RwLock to safeguard against data races in concurrent operations. |
| RUST003 | Dangling Pointers | Critical | Use of pointers that may no longer be valid, leading to dangling pointers. | Ensure that any pointer or reference is valid for the duration of its use. Consider using smart pointers for safer memory management. |
| RUST004 | Buffer Overflows | High | Accessing arrays or vectors with unchecked indices, potentially leading to buffer overflows. | Use the `.get()` or `.get_mut()` methods for accessing elements by index safely. |
| RUST005 | Aliasing Rules Violation | Medium | Mutable aliasing that could lead to data races or undefined behavior. | Ensure that mutable references do not alias by using exclusive access patterns. |
| RUST006 | Memory Leaks | Medium | Improper use of memory allocation that could result in memory leaks. | Ensure proper deallocation of resources and consider using smart pointers correctly to prevent leaks. |
| RUST007 | Uninitialized Memory | High | Use of uninitialized memory, which can lead to undefined behavior. | Use `MaybeUninit<T>` for safer initialization of memory. |
| RUST009 | Type Punning and Transmutation | High | Unsafe type conversions that can break type safety. | Avoid using `transmute` where possible. Prefer safe conversion methods or carefully validate transmutations. |
| RUST010 | Manual Memory Management Errors | High | Manual allocation, deallocation, or manipulation of memory, risking errors like double frees or use-after-free. | Use Rust's ownership and borrowing system as much as possible, and ensure manual memory management is error-free when necessary. |
| RUST011 | Use After Free | Critical | Accessing memory after it has been freed, leading to potentially exploitable vulnerabilities. | Ensure that pointers or references to memory are not used after the memory has been deallocated. Use lifetime tracking features in Rust to manage memory safely. |
| RUST012 | Integer Overflow | High | Arithmetic operations that may overflow, leading to incorrect calculations or vulnerabilities. | Use checked arithmetic functions like `checked_add` to prevent overflows. |
| RUST013 | Improper Access Control | Medium | Exposing unsafe blocks or functions publicly without proper encapsulation or safety checks. | Minimize the visibility of unsafe code. Encapsulate unsafe operations within safe abstractions whenever possible. |
| RUST014 | Race Condition in Unsafe Code | High | Concurrency issues within unsafe blocks that could lead to race conditions. | Employ proper synchronization mechanisms even within unsafe blocks to prevent race conditions. |
| RUST015 | Unsafe Trait Implementation | Medium | Implementing traits unsafely, which might lead to undefined behavior if the trait's contract is not properly upheld. | Ensure that unsafe trait implementations strictly adhere to their expected contracts and behaviors. |
| RUST016 | Insecure Randomness | Medium | Use of insecure or non-cryptographically secure random number generators. | Use a cryptographically secure random number generator like `rand::thread_rng()` for security-critical applications.|
| RUST017 | Panics in Unsafe Code | Medium | Using `.unwrap()` or `.expect()` within unsafe blocks, which may lead to panics in scenarios where error handling is critical. | Handle errors gracefully in unsafe code to avoid panicking, using `Result` and error handling patterns instead of `.unwrap()` or `.expect()`. |
| RUST018 | Misuse of Sync and Send Traits | High | Incorrectly implementing `Sync` or `Send` traits, potentially leading to data races in concurrent contexts. | Carefully audit and ensure correctness when manually implementing `Sync` or `Send` to uphold Rust's safety guarantees. |
| RUST019 | Unsafe Block in Public Interface | Medium | Exposing unsafe blocks through a public interface, increasing the risk of misuse by external callers. | Avoid exposing unsafe operations in public APIs. Provide safe wrappers to encapsulate unsafe operations internally. |
| RUST020 | Unsafe Dereferencing | High | Dereferencing pointers without ensuring they point to valid memory, leading to potential segmentation faults or undefined behavior. | Verify the validity of pointers before dereferencing, especially in unsafe contexts. Consider using references or smart pointers when possible. |
| ID | Language | Title | Severity | Description | Suggested Fix | Context |
|--------|----------|------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------|
| RUST001| Rust | [Rust] Unsafe code block | High | Unsafe code blocks can lead to undefined behavior if not used properly. | Ensure that unsafe code is necessary and properly reviewed. Use safe abstractions when possible. | Whenever using unsafe blocks in Rust code |
| RUST002| Rust | [Rust] Unhandled error | Medium | Unwrapping a Result or Option without proper error handling can lead to panic. | Use match or if let to handle the Result or Option properly, or use ? to propagate the error. | When using unwrap() on Result or Option types |
| RUST003| Rust | [Rust] Unchecked arithmetic | Medium | Arithmetic operations that can overflow or underflow without being checked. | Use checked arithmetic methods like checked_add, checked_sub, checked_mul, and checked_div. | When performing arithmetic operations that may overflow or underflow |
| RUST004| Rust | [Rust] Insecure random number generator| High | Using an insecure random number generator for security-sensitive operations. | Use a cryptographically secure random number generator like rand::ThreadRng or ring::rand::SystemRandom. | When generating random numbers for security-sensitive purposes |
| RUST005| Rust | [Rust] Uninitialized memory | High | Using uninitialized memory can lead to undefined behavior. | Initialize memory properly or use mem::MaybeUninit for delayed initialization. | When working with uninitialized memory |
| RUST006| Rust | [Rust] Use of mem::transmute | High | Using mem::transmute can lead to undefined behavior and violate type safety. | Avoid using mem::transmute and use safe type conversions or as keyword for primitive types. | When using mem::transmute to reinterpret memory |
| RUST007| Rust | [Rust] Use of std::process::Command | Medium | Using std::process::Command without properly sanitizing user input can lead to command injection vulnerabilities. | Properly sanitize and validate user input before passing it to std::process::Command. Consider using safe wrappers or libraries. | When executing external commands or processes |
| RUST008| Rust | [Rust] Use of std::fs::File with unwrap() | Medium | Using unwrap() with std::fs::File can lead to panics if the file operation fails. | Use ? operator to propagate the error or handle it explicitly with match or if let. | When opening files using std::fs::File |
| RUST009| Rust | [Rust] Deserialization of untrusted data | High | Deserializing untrusted data without proper validation can lead to security vulnerabilities. | Implement custom deserialization logic with proper validation and sanitization of untrusted data. Consider using safe deserialization libraries. | When deserializing data from untrusted sources using serde or other libraries |
| RUST010| Rust | [Rust] Use of std::net::TcpListener with unwrap() | Medium | Using unwrap() with std::net::TcpListener can lead to panics if the binding operation fails. | Use ? operator to propagate the error or handle it explicitly with match or if let. | When binding to a network address using std::net::TcpListener'. From the beginning to end! |
26 changes: 15 additions & 11 deletions l3x/src/gpt_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,30 @@ struct MessageContent {
content: String,
}

pub async fn validate_vulnerability_with_gpt(
pub async fn validate_vulnerabilities_with_gpt(
api_key: &str,
title: &str,
severity: &str,
line_number: usize,
line_of_code: &str,
findings_by_file: &[(usize, String, String, String)],
file_content: &str,
language: &str,
validate_all_severities: bool,
) -> Result<(String, String), Box<dyn Error>> {
let client = Client::new();

let mut findings_list = String::new();
for (line_number, vulnerability_id, severity, _) in findings_by_file {
if validate_all_severities || severity == "Critical" || severity == "High" {
findings_list.push_str(&format!("line {}: {}\n", line_number, vulnerability_id));
}
}

let prompt = match language {
"Rust" => format!(
"A SAST tool detects a potential Rust vulnerability titled '{title}' with severity '{severity}' at line number {line_number}. The line of code flagged is:\n\n{line_of_code}\n\nFull code for context:\n\n{file_content}\n\nIs this a valid vulnerability or a false positive? If valid, suggest a fix.",
title = title, severity = severity, line_number = line_number, line_of_code = line_of_code, file_content = file_content
"A SAST tool detects potential Rust vulnerabilities in the following file:\n\nSource code:\n{}\n\nFindings list:\n{}\n\nAre these valid vulnerabilities or false positives? Provide an explanation.",
file_content, findings_list
),
"Solidity-Ethereum" => format!(
"A SAST tool detects a potential Solidity vulnerability titled '{title}' with severity '{severity}' at line number {line_number}. The line of code flagged is:\n\n{line_of_code}\n\nFull code for context:\n\n{file_content}\n\nIs this a valid vulnerability or a false positive? If valid, suggest a fix.",
title = title, severity = severity, line_number = line_number, line_of_code = line_of_code, file_content = file_content
"A SAST tool detects potential Solidity vulnerabilities in the following file:\n\nSource code:\n{}\n\nFindings list:\n{}\n\nAre these valid vulnerabilities or false positives? Provide an explanation.",
file_content, findings_list
),
_ => return Err(Box::new(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Unsupported language"))),
};
Expand All @@ -73,15 +78,14 @@ pub async fn validate_vulnerability_with_gpt(

let status = analyze_response_text(&text);

Ok((status.to_string(), text.to_string()))
Ok((status.to_string(), "".to_string()))
} else {
Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, "Failed to get a valid response from OpenAI")))
}
}

fn analyze_response_text(text: &str) -> &str {
if text.contains("not a vulnerability")
|| text.contains("is not a valid vulnerability")
|| text.contains("is not a valid vulnerability")
|| text.to_lowercase().contains("appears to be a false positive")
|| text.to_lowercase().contains("is no vulnerability present")
Expand Down
Loading

0 comments on commit fbe2b02

Please sign in to comment.