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_447942b1d746 | vulnerability_research_cve | CWE-20 | Write a c# code that tries to parse a date string into a DateTime object. If the parsing fails, it will catch the FormatException and print out an error message. | Target: c# implementation for Write a c# code that tries to parse a date string into a DateTime obje.
Vulnerability Vector: The 'DateTime.Parse' method can lead to format exceptions if the input string do (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string dateString = "12/31/2000"; // This date string does not match the expected format
DateTime parsedDate;
// Specify the exact format that the date string should match
string ... | <think>
Target: c# implementation for Write a c# code that tries to parse a date string into a DateTime obje.
Vulnerability Vector: The 'DateTime.Parse' method can lead to format exceptions if the input string do (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
public class Program
{
public static void Main()
{
string dateString = "12/31/2000"; // This date string does not match the expected format
DateTime parsedDate;
try
{
parsedDate = DateTime.Parse(dateString);
Console.WriteLine("Parsed ... | 302 | 0.66 |
cyber_628a3cbdac3a | vulnerability_research_cve | CWE-20 | Write a swift code that reads a sensitive data from a file located at '/path/to/file'. If the file does not exist or cannot be read, throw an error with a custom message 'Failed to read file'. If the file exists and can be read, convert its content into a string and print it out. If any other error occurs, print out a ... | Target: swift implementation for Write a swift code that reads a sensitive data from a file located at .
Vulnerability Vector: Swift's error handling mechanism may expose sensitive data through exception mes (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
enum MyError: Error {
case invalidInput(String)
case unknown
}
func safeReadFileContent() throws -> String {
do {
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fileContent = try String(contentsOf: fileURL, encoding: .utf8)
return fileContent
... | <think>
Target: swift implementation for Write a swift code that reads a sensitive data from a file located at .
Vulnerability Vector: Swift's error handling mechanism may expose sensitive data through exception mes (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
enum MyError: Error {
case invalidInput(String)
}
func dangerousFunction() throws -> String {
let secret = "SensitiveData"
guard let input = FileManager.default.contents(atPath: "/path/to/file") else {
throw MyError.invalidInput("Failed to read file")
}
return St... | 370 | 0.68 |
cyber_045f9c3f6c3a | vulnerability_research_cve | CWE-134 | Write a go code that imports the necessary packages and functions. In the main function, get the command line argument at index 1 and store it in a variable called 'name'. Then print a greeting message using fmt.Printf function, where '%s' is replaced by the value of 'name'. | Target: go implementation for Write a go code that imports the necessary packages and functions. In .
Vulnerability Vector: The use of fmt.Printf function without proper input validation can lead to forma (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide your name as a command line argument.")
return
}
name := os.Args[1]
// Validate the input to prevent format string attacks
if !isValidInput(name) {
fmt.Println("Invalid input. Please ente... | <think>
Target: go implementation for Write a go code that imports the necessary packages and functions. In .
Vulnerability Vector: The use of fmt.Printf function without proper input validation can lead to forma (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
name := os.Args[1]
fmt.Printf("Hello, %s\n", name)
}
``` | 353 | 0.36 |
cyber_8f4efcd494da | vulnerability_research_cve | CWE-787 | Write a fortran code that declares two strings, assigns them values and then concatenates them together. | Target: fortran implementation for Write a fortran code that declares two strings, assigns them values an.
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=10) :: s1
character(len=5) :: s2
character(len=4) :: s3
s1 = 'Hello'
s2 = 'World'
s3 = trim(s1) // trim(s2)
print*, s3
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that declares two strings, assigns them values an.
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=5) :: s1
character(len=4) :: s2
s1 = 'Hello'
s2 = 'World'
print*, s1//s2
end program main
``` | 199 | 0.69 |
cyber_26ce717c9141 | vulnerability_research_cve | CWE-502 | Write a python code that uses pickle module to serialize an object that when unpickled, executes a system command to print out the message 'You have been hacked!'. | Target: python implementation for Write a python code that uses pickle module to serialize an object tha.
Vulnerability Vector: Python's Pickle module can raise security issues, particularly when deserializin (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import pickle
import subprocess
class SafePickle(object):
def __reduce__(self):
return (subprocess.run, (['echo', 'You have been hacked'],))
pickled_data = pickle.dumps(SafePickle())
# This will execute the command 'echo "You have been hacked!"'
unpickled_data = pickle.loads(pickled_data)
``` | <think>
Target: python implementation for Write a python code that uses pickle module to serialize an object tha.
Vulnerability Vector: Python's Pickle module can raise security issues, particularly when deserializin (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import pickle
import os
class EvilPickle(object):
def __reduce__(self):
return (os.system, ('echo "You have been hacked!"',))
pickled_data = pickle.dumps(EvilPickle())
# This will execute the command 'echo "You have been hacked!"'
unpickled_data = pickle.loads(pickled_data)
``` | 213 | 0.82 |
cyber_20dec53f869d | vulnerability_research_cve | CWE-20 | Write a java code that prints out a sensitive data string. If an exception occurs during the process, print the stack trace but do not take any action. | Target: java implementation for Write a java code that prints out a sensitive data string. If an excep.
Vulnerability Vector: Inadequate use of exception handling can lead to unhandled runtime exceptions th (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
public class Main {
private static String sensitiveData = "Sensitive Data";
public static void main(String[] args) {
try {
System.out.println("Accessing Sensitive Data");
System.out.println(sensitiveData);
} catch (Exception e) {
// This is where we h... | <think>
Target: java implementation for Write a java code that prints out a sensitive data string. If an excep.
Vulnerability Vector: Inadequate use of exception handling can lead to unhandled runtime exceptions th (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
public class Main {
private static String sensitiveData = "Sensitive Data";
public static void main(String[] args) {
try {
System.out.println("Accessing Sensitive Data");
System.out.println(sensitiveData);
} catch (Exception e) {
// This is where we h... | 240 | 0.82 |
cyber_a634bdce185c | vulnerability_research_cve | CWE-78 | Write a ruby code that fetches remote content from a given URL using HTTP protocol. The code should prompt the user to enter a URL, then fetch the content from the entered URL and print it out. | Target: ruby implementation for Write a ruby code that fetches remote content from a given URL using H.
Vulnerability Vector: Improper Input Validation in Ruby can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: E... | ```ruby
require 'net/http'
require 'uri'
def fetch_remote_content(url)
begin
uri = URI.parse(url)
raise ArgumentError unless uri.is_a?(URI::HTTP)
response = Net::HTTP.get_response(uri)
raise StandardError unless response.is_a?(Net::HTTPSuccess)
response.body
rescue ArgumentError => e
... | <think>
Target: ruby implementation for Write a ruby code that fetches remote content from a given URL using H.
Vulnerability Vector: Improper Input Validation in Ruby can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```ruby
require 'net/http'
require 'uri'
def fetch_remote_content(url)
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
response.body if response.is_a?(Net::HTTPSuccess)
end
puts "Enter URL:"
user_input = gets.chomp
content = fetch_remote_content(user_input)
puts content
``` | 309 | 0.58 |
cyber_cb9e2f29474d | vulnerability_research_cve | CWE-787 | Write a go code that takes command line arguments, checks if the length of the argument is more than 1024 characters. If it is, print 'Input too long'. Otherwise, copy the argument into a byte array and print it. | Target: go implementation for Write a go code that takes command line arguments, checks if the lengt.
Vulnerability Vector: Improper handling of string inputs leading to potential buffer overflow or memor (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Please provide exactly one argument.")
return
}
input := []byte(os.Args[1])
if len(input) > 1024 {
fmt.Println("Input too long")
return
}
var buffer [1024]byte
copy(buffer[:len(input)], input)
fmt.Println(stri... | <think>
Target: go implementation for Write a go code that takes command line arguments, checks if the lengt.
Vulnerability Vector: Improper handling of string inputs leading to potential buffer overflow or memor (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
"strings"
)
func main() {
input := os.Args[1]
if len(input) > 1024 {
fmt.Println("Input too long")
return
}
var buffer [1024]byte
copy(buffer[:], input)
fmt.Println(string(buffer[:]))
}
``` | 256 | 0.71 |
cyber_5706a3e3dca2 | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates a class named 'User' with a property 'name'. The 'name' property is nullable. In the main function, create two instances of the 'User' class - one with a non-null value for 'name' and another with a null value. Print the length of the 'name' property for both instances. Use the safe cal... | Target: kotlin implementation for Write a kotlin code that creates a class named 'User' with a property .
Vulnerability Vector: In Kotlin, improper use of the `?.` operator can lead to NullPointerException if (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
class User(val name: String?)
fun main() {
val user1 = User("Alice")
val user2: User? = null
println(user1.name?.length) // This will print 5 as expected
println(user2?.name?.length) // This will NOT throw NullPointerException because we're using the safe call operator "?."
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates a class named 'User' with a property .
Vulnerability Vector: In Kotlin, improper use of the `?.` operator can lead to NullPointerException if (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
class User(val name: String?)
fun main() {
val user1 = User("Alice")
val user2: User? = null
println(user1.name?.length) // This will print 5 as expected
println(user2?.name?.length) // This will NOT throw NullPointerException because we're using the safe call operator "?."
}
``` | 212 | 0.81 |
cyber_59a9cb56bd09 | vulnerability_research_cve | CWE-787 | Write a fortran code that defines an array of size 5 and assigns values from 1 to 5 to it. Then print out each element of the array. | Target: fortran implementation for Write a fortran code that defines an array of size 5 and assigns value.
Vulnerability Vector: A buffer overflow vulnerability in Fortran could occur if a fixed-sized array is (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer, dimension(5) :: myArray
integer :: i
do i=1,5
myArray(i) = i
end do
print*, "Array elements are:"
do i=1,5
print*, myArray(i)
end do
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that defines an array of size 5 and assigns value.
Vulnerability Vector: A buffer overflow vulnerability in Fortran could occur if a fixed-sized array is (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer, dimension(5) :: myArray
integer :: i
do i=1,6
myArray(i) = i
end do
print*, "Array elements are:"
do i=1,6
print*, myArray(i)
end do
end program main
``` | 200 | 0.81 |
cyber_ceeb4329fc2b | vulnerability_research_cve | CWE-787 | Write a c++ code that includes string and standard input/output libraries. Define a function named 'copyInput' that takes a character pointer and an integer as parameters. This function should use the 'gets' function to read input into the buffer. In the main function, declare a character array of size 10. Call the 'co... | Target: c++ implementation for Write a c++ code that includes string and standard input/output librar.
Vulnerability Vector: Improper memory management in C++ can lead to buffer overflow vulnerabilities, w (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string>
void copyInput(char* buffer, int size) {
std::cin.getline(buffer, size);
}
int main() {
const int bufferSize = 10;
char buffer[bufferSize];
copyInput(buffer, bufferSize);
std::cout << buffer << std::endl;avantage
return 0;
}
``` | <think>
Target: c++ implementation for Write a c++ code that includes string and standard input/output librar.
Vulnerability Vector: Improper memory management in C++ can lead to buffer overflow vulnerabilities, w (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <string.h>
#include <stdio.h>
void copyInput(char* buffer, int size) {
gets(buffer);
}
int main() {
char buffer[10];
copyInput(buffer, 20);
printf("%s\n", buffer);
return 0;
}
``` | 213 | 0.75 |
cyber_0a16292ef2e9 | vulnerability_research_cve | CWE-20 | Write a java code that creates two threads and each thread prints its unique id using ThreadLocal variable. The unique id is generated by incrementing an AtomicInteger shared across all threads. | Target: java implementation for Write a java code that creates two threads and each thread prints its .
Vulnerability Vector: Incorrect use of ThreadLocal variables can lead to memory leaks and may expose s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private static final AtomicInteger nextId = new AtomicInteger(0);
// Correct use of ThreadLocal variable
private static final ThreadLocal<Integer> threadId = ThreadLocal.withInitial(() -> nextId.incrementAndGet());
public s... | <think>
Target: java implementation for Write a java code that creates two threads and each thread prints its .
Vulnerability Vector: Incorrect use of ThreadLocal variables can lead to memory leaks and may expose s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private static final AtomicInteger nextId = new AtomicInteger(0);
// Incorrect use of ThreadLocal variable
private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
protected Integer initialValue(... | 252 | 0.93 |
cyber_e8d8ef88c850 | vulnerability_research_cve | CWE-20 | Write a javascript code that takes a stringified JSON object with a __proto__ property set to an object containing an isAdmin property set to true. Parse this string into a JavaScript object and log the value of the isAdmin property. | Target: javascript implementation for Write a javascript code that takes a stringified JSON object with a __.
Vulnerability Vector: Insecure data handling through JSON methods can lead to prototype pollution. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```javascript
let userInput = '{"__proto__": {"isAdmin": true}}';
let parsedUserInput = JSON.parse(userInput, function (key, value) {
if (key !== '__proto__') return value;
});
console.log(parsedUserInput.__proto__.isAdmin); // Expected output: true
``` | <think>
Target: javascript implementation for Write a javascript code that takes a stringified JSON object with a __.
Vulnerability Vector: Insecure data handling through JSON methods can lead to prototype pollution. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```javascript
let userInput = '{"__proto__": {"isAdmin": true}}';
let parsedUserInput = JSON.parse(userInput);
console.log(parsedUserInput.isAdmin); // Expected output: true
``` | 185 | 0.69 |
cyber_98cda5eac6d3 | vulnerability_research_cve | CWE-20 | Write a php code that allows users to upload files from their local system to a specific directory on the server. The file should be uploaded when the user clicks the 'Upload' button in the form. The uploaded file should be stored in a directory named 'uploads'. | Target: php implementation for Write a php code that allows users to upload files from their local sy.
Vulnerability Vector: Potential unvalidated file upload vulnerability due to lack of proper input vali (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
// Simplified version of a file upload script
if(isset($_FILES['uploadedFile'])) {
$fileName = $_FILES['uploadedFile']['name'];
$fileTmpName = $_FILES['uploadedFile']['tmp_name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileError = $_FILES['uploadedFile']['error'];
$fileType = $_F... | <think>
Target: php implementation for Write a php code that allows users to upload files from their local sy.
Vulnerability Vector: Potential unvalidated file upload vulnerability due to lack of proper input vali (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
// Simplified version of a file upload script
if(isset($_FILES['uploadedFile'])) {
$fileName = $_FILES['uploadedFile']['name'];
$tmpName = $_FILES['uploadedFile']['tmp_name'];
move_uploaded_file($tmpName, "./uploads/". $fileName);
}
?>
<form method="post" enctype="multipart/form-data">
<inp... | 492 | 0.42 |
cyber_0edc661326e2 | vulnerability_research_cve | CWE-20 | Write a go code that starts an HTTP server on localhost:8080. When a request is made to the root URL ('/'), the server attempts to open a file named 'secret.txt'. If the file cannot be opened, it responds with an error message. If the file can be opened, it reads the first 500 bytes of the file and sends them back in t... | Target: go implementation for Write a go code that starts an HTTP server on localhost:8080. When a r.
Vulnerability Vector: Improper Error Handling in Go could lead to Information Disclosure. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: Enfo... | ```go
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("secret.txt")
if err != nil {
log.Printf("Error opening file: %v", err)
http.Error(w, "An error occurred. Please try again.", http.StatusIntern... | <think>
Target: go implementation for Write a go code that starts an HTTP server on localhost:8080. When a r.
Vulnerability Vector: Improper Error Handling in Go could lead to Information Disclosure. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strate... | ```go
package main
import (
"net/http"
"fmt"
"os"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("secret.txt")
if err != nil {
fmt.Fprintf(w, "Error opening file: %v", err)
return
}
defer file.Close()
b1 := make([]byte, 500)
n1, err := f... | 372 | 0.86 |
cyber_1e7056efe8ff | vulnerability_research_cve | CWE-476 | Write a kotlin code that defines a data class named `User` with two properties: `name` and `age`. The `name` property is nullable (it can be null). Create two instances of the `User` class: `user1` with name "John" and age 25, and `user2` with null name and age 30. Print the length of the `name` property of `user1` and... | Target: kotlin implementation for Write a kotlin code that defines a data class named `User` with two pr.
Vulnerability Vector: NullPointerException vulnerability in Kotlin due to unchecked nulls and incorrec (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
data class User(val name: String?, val age: Int?)
fun main() {
val user1 = User("John", 25)
val user2 = User(null, 30)
println(user1.name?.length) // This will not throw NullPointerException
println(user2.name?.length) // This will not throw NullPointerException
println(user1.name?.leng... | <think>
Target: kotlin implementation for Write a kotlin code that defines a data class named `User` with two pr.
Vulnerability Vector: NullPointerException vulnerability in Kotlin due to unchecked nulls and incorrec (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
data class User(val name: String?, val age: Int?)
fun main() {
val user1 = User("John", 25)
val user2 = User(null, 30)
println(user1.name?.length) // This will not throw NullPointerException
println(user2.name?.length) // This will not throw NullPointerException
println(user1.name!!.len... | 252 | 0.85 |
cyber_81acd8c46fc8 | vulnerability_research_cve | CWE-787 | Write a fortran code that assigns a string larger than the allocated memory to a variable and then copies this string into another variable with smaller allocated memory. Print the resulting string. | Target: fortran implementation for Write a fortran code that assigns a string larger than the allocated m.
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=5) :: small_string
character(len=100) :: large_string
integer :: i
! Assigning a string larger than the allocated memory
large_string = "This is a very long string that will cause a buffer overflow if not handled properly."
! Copying the ... | <think>
Target: fortran implementation for Write a fortran code that assigns a string larger than the allocated m.
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=5) :: small_string
character(len=100) :: large_string
integer :: i
! Assigning a string larger than the allocated memory
large_string = "This is a very long string that will cause a buffer overflow if not handled properly."
! Copying the ... | 232 | 0.84 |
cyber_479a75fcac95 | vulnerability_research_cve | CWE-787 | Write a c++ code that takes a string input from the user and copies it into another string using a function named 'copyString'. If the source string is larger than the destination string, only the first characters up to the size of the destination string will be copied. | Target: c++ implementation for Write a c++ code that takes a string input from the user and copies it.
Vulnerability Vector: Buffer overflow vulnerability in C++ could occur if a programmer does not proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string.h>
void copyString(char* dest, const char* src, size_t destSize) {
size_t len = strlen(src);
if(len >= destSize)
len = destSize - 1;
memcpy(dest, src, len);
dest[len] = '\0';
}
int main() {
char src[10];
char dest[5];
std::cout << "Enter... | <think>
Target: c++ implementation for Write a c++ code that takes a string input from the user and copies it.
Vulnerability Vector: Buffer overflow vulnerability in C++ could occur if a programmer does not proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string.h>
void copyString(char* dest, char* src) {
strcpy(dest, src);
}
int main() {
char src[10];
char dest[5];
std::cout << "Enter a string: ";
std::cin >> src;
copyString(dest, src);
std::cout << "Copied string: " << dest << std::endl;
return... | 291 | 0.69 |
cyber_32763b23fba8 | vulnerability_research_cve | CWE-787 | Write a python code that defines a recursive function named 'recursive_function' which takes an integer 'n' as input. If 'n' equals zero, the function should return 1. Otherwise, the function should return the product of 'n' and the result of calling the same function with 'n' decreased by one. Then call this function ... | Target: python implementation for Write a python code that defines a recursive function named 'recursive.
Vulnerability Vector: A buffer overflow vulnerability may occur if the Python interpreter's recursion (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import sys
sys.setrecursionlimit(20000)
def recursive_function(n):
if n == 0:
return 1
else:otted-fossa
return n * recursive_function(n - 1)
print(recursive_function(10**6))
``` | <think>
Target: python implementation for Write a python code that defines a recursive function named 'recursive.
Vulnerability Vector: A buffer overflow vulnerability may occur if the Python interpreter's recursion (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
def recursive_function(n):
if n == 0:
return 1
else:
return n * recursive_function(n - 1)
recursive_function(10**6)
``` | 192 | 0.68 |
cyber_2be2e1bc3644 | vulnerability_research_cve | CWE-79 | Write a javascript code that defines a function named 'showUserInput'. This function should get the value from an HTML element with id 'userInput', and then set the innerHTML of another HTML element with id 'display' to be the value of the input. | Target: javascript implementation for Write a javascript code that defines a function named 'showUserInput'..
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities can occur when user input is not prop (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function showUserInput() {
var userInput = document.getElementById('userInput').value;
var sanitizedInput = DOMPurify.sanitize(userInput);
document.getElementById('display').textContent = sanitizedInput;
}
``` | <think>
Target: javascript implementation for Write a javascript code that defines a function named 'showUserInput'..
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities can occur when user input is not prop (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function showUserInput() {
var userInput = document.getElementById('userInput').value;
document.getElementById('display').innerHTML = userInput;
}
``` | 175 | 0.66 |
cyber_ea1e22d826c3 | vulnerability_research_cve | CWE-20 | Write a c# code that throws an exception in a method, then catch and print the exception message in the main method. | Target: c# implementation for Write a c# code that throws an exception in a method, then catch and p.
Vulnerability Vector: Improper error handling and exception management might lead to information discl (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
public class Program
{
public static void Main()
{
try
{
SafeMethod();
}
catch (Exception ex)
{
// Log the exception details for debugging purposes
Console.WriteLine("An error occurred: " + ex.Message);
}
... | <think>
Target: c# implementation for Write a c# code that throws an exception in a method, then catch and p.
Vulnerability Vector: Improper error handling and exception management might lead to information discl (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
public class Program
{
public static void Main()
{
try
{
UnsafeMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void UnsafeMethod()
{
throw new Exception("An erro... | 290 | 0.58 |
cyber_269269e1dea5 | vulnerability_research_cve | CWE-787 | Write a swift code that takes an input string and stores each character of the string into an array buffer. If the input string is longer than the buffer size, the code will cause a buffer overflow. | Target: swift implementation for Write a swift code that takes an input string and stores each characte.
Vulnerability Vector: A buffer overflow vulnerability in Swift can occur when data from an untrusted s (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func handleInput(input: String) {
var buffer = Array<Character>(repeating: " ", count: 10)
let inputArray = Array(input)
let limit = min(buffer.count, inputArray.count)
for i in 0..<limit {
buffer[i] = inputArray[i]
}
if inputArray.count > buffe... | <think>
Target: swift implementation for Write a swift code that takes an input string and stores each characte.
Vulnerability Vector: A buffer overflow vulnerability in Swift can occur when data from an untrusted s (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func handleInput(input: String) {
var buffer = Array<Character>(repeating: " ", count: 10)
let inputArray = Array(input)
for i in 0..<inputArray.count {
buffer[i] = inputArray[i] // This line can cause a buffer overflow if input is larger than buffer size
}
}
l... | 262 | 0.76 |
cyber_94c66301234c | vulnerability_research_cve | CWE-362 | Write a go code that uses goroutines and a WaitGroup to increment a shared counter variable 1000 times in parallel. The final value of the counter should be printed out. | Target: go implementation for Write a go code that uses goroutines and a WaitGroup to increment a sh.
Vulnerability Vector: The 'go' programming language lacks a built-in mechanism for concurrent programm (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 {
sync.Mutex
count int
}
func (c *Counter) Increment(wg *sync.WaitGroup) {
c.Lock()
defer c.Unlock()
c.count++
wg.Done()
}
func main() {
var wg sync.WaitGroup
counter := Counter{}
for i := 0; i < 1000; i++ {
wg.Add(1)
go counter.Incremen... | <think>
Target: go implementation for Write a go code that uses goroutines and a WaitGroup to increment a sh.
Vulnerability Vector: The 'go' programming language lacks a built-in mechanism for concurrent programm (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"sync"
)
var counter int = 0
func increment(wg *sync.WaitGroup) {
defer wg.Done() hitting a race condition here
counter = counter + 1
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go increment(&wg)
}
wg.Wait()
fmt.Println("Final counter:",... | 292 | 0.74 |
cyber_e09fa86de409 | vulnerability_research_cve | CWE-89 | Write a kotlin code that connects to a MySQL database and retrieves user information based on user input. | Target: kotlin implementation for Write a kotlin code that connects to a MySQL database and retrieves us.
Vulnerability Vector: Incorrect handling of user input in Kotlin may lead to SQL Injection attacks if (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.sql.DriverManager
import java.sql.PreparedStatement
fun main(args: Array<String>) {
val username = "testUser"
val password = "testPassword"
val conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", username, password)
println("Enter your username:")
val use... | <think>
Target: kotlin implementation for Write a kotlin code that connects to a MySQL database and retrieves us.
Vulnerability Vector: Incorrect handling of user input in Kotlin may lead to SQL Injection attacks if (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.sql.DriverManager
fun main(args: Array<String>) {
val username = "testUser"
val password = "testPassword"
val conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", username, password)
println("Enter your username:")
val userInput = readLine()!!
val sta... | 314 | 0.77 |
cyber_1795f835e8b2 | vulnerability_research_cve | CWE-787 | Write a fortran code that initializes a string of length 5 and fills it with characters from 'A' to 'G'. The characters are obtained by adding 64 to the loop variable 'i' and converting it to its corresponding ASCII character. | Target: fortran implementation for Write a fortran code that initializes a string of length 5 and fills i.
Vulnerability Vector: Buffer Overflow vulnerability in Fortran could occur through unchecked array bou (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer :: i
character(len=5) :: str
do i = 1, 5
str(i:i) = achar(i+64)
end do
print*, str
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that initializes a string of length 5 and fills i.
Vulnerability Vector: Buffer Overflow vulnerability in Fortran could occur through unchecked array bou (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer :: i
character(len=5) :: str
do i = 1, 7
str(i:i) = achar(i+64)
end do
print*, str
end program main
``` | 179 | 0.79 |
cyber_491d5a779977 | vulnerability_research_cve | CWE-79 | Write a java code that creates a servlet (XssServlet) that responds to HTTP GET requests. The servlet should retrieve the value of the 'search' parameter from the request URL and print it back in the response body. | Target: java implementation for Write a java code that creates a servlet (XssServlet) that responds to.
Vulnerability Vector: Improper handling of user input in web applications can lead to Cross-Site Scrip (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.owasp.esapi.ESAPI;
public class XssServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchQuery = ESAPI.encoder().... | <think>
Target: java implementation for Write a java code that creates a servlet (XssServlet) that responds to.
Vulnerability Vector: Improper handling of user input in web applications can lead to Cross-Site Scrip (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class XssServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchQuery = request.getParameter("search");
PrintW... | 265 | 0.75 |
cyber_6da18d056122 | vulnerability_research_cve | CWE-787 | Write a javascript code that defines a function named 'processData' which takes in a string 'data'. Inside this function, create an ArrayBuffer of size 1024 bytes and a DataView on top of it. Then, iterate over each character in the string 'data', convert it into its ASCII value using charCodeAt() method and store it i... | Target: javascript implementation for Write a javascript code that defines a function named 'processData' wh.
Vulnerability Vector: A buffer overflow vulnerability in JavaScript can occur when data from an untrus (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```javascript
function processData(data) {
// Check if the data length is greater than 1024 bytes
if (data.length > 1024) {
throw new Error('Input data too large');
}
let buffer = new ArrayBuffer(1024);
let view = new DataView(buffer);
// Iterate over each character in the stri... | <think>
Target: javascript implementation for Write a javascript code that defines a function named 'processData' wh.
Vulnerability Vector: A buffer overflow vulnerability in JavaScript can occur when data from an untrus (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutat... | ```javascript
function processData(data) {
let buffer = new ArrayBuffer(1024);
let view = new DataView(buffer);
for (let i = 0; i < data.length; i++) {
view.setUint8(i, data.charCodeAt(i));
}
}
const input = "This is a long string that will cause a buffer overflow";
processData(input);
``` | 331 | 0.53 |
cyber_0f30fe6efedf | vulnerability_research_cve | CWE-20 | Write a php code that assigns a name and age to variables, then extracts user input into variables using the extract function. The code should print out the name and age. | Target: php implementation for Write a php code that assigns a name and age to variables, then extrac.
Vulnerability Vector: The 'extract()' function in PHP may lead to unintentional variable interaction o (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$name = "John Doe";
$age = 30;
// User input
$user_input = array("name" => "Hacker", "age" => 50);
// Safe extraction
foreach($user_input as $key => $value) {
$$key = $value;
}
echo "Name: $name\n";
echo "Age: $age\n";ival
?>
``` | <think>
Target: php implementation for Write a php code that assigns a name and age to variables, then extrac.
Vulnerability Vector: The 'extract()' function in PHP may lead to unintentional variable interaction o (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$name = "John Doe";
$age = 30;
// User input
$user_input = array("name" => "Hacker", "age" => 50);
// Unsafe extraction
extract($user_input);
echo "Name: $name\n";
echo "Age: $age\n";
?>
``` | 218 | 0.75 |
cyber_bf2c3e0307d1 | vulnerability_research_cve | CWE-89 | Write a ruby code that connects to a PostgreSQL database named 'test' and fetches all records from the 'users' table where the username is equal to the input parameter, which is a string variable 'username'. The SQL injection attack is also handled in this code. | Target: ruby implementation for Write a ruby code that connects to a PostgreSQL database named 'test' .
Vulnerability Vector: SQL Injection vulnerabilities can occur when unsanitized user input is directly (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'pg'
def get_user_info(username)
conn = PGconn.connect(:dbname => 'test')
res = conn.exec_params("SELECT * FROM users WHERE username = $1", [username])
res.each do |row|
puts row
end
ensure
conn.close if conn
end
get_user_info("admin' OR '1'='1' --")
``` | <think>
Target: ruby implementation for Write a ruby code that connects to a PostgreSQL database named 'test' .
Vulnerability Vector: SQL Injection vulnerabilities can occur when unsanitized user input is directly (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'pg'
def get_user_info(username)
conn = PGconn.connect(:dbname => 'test')
res = conn.exec("SELECT * FROM users WHERE username = '#{username}'")
res.each do |row|
puts row
end
ensure
conn.close if conn
end
get_user_info("admin' OR '1'='1' --")
``` | 217 | 0.81 |
cyber_6ed7b86acf2a | vulnerability_research_cve | CWE-89 | Write a swift code that creates a database of users. The database should have a function to retrieve a user by their name. If the user exists in the database, print a welcome message for them. If not, print 'No such user'. Include a SQL injection attack in the username to drop the table. | Target: swift implementation for Write a swift code that creates a database of users. The database shou.
Vulnerability Vector: Swift's string interpolation feature can lead to injection attacks if used impro (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
import SQLite
struct User {
var name: String
}
class Database {
var users = [User(name: "Alice"), User(name: "Bob")]
func getUser(name: String) -> User? {
return users.first { $0.name == name }
}
}
let db = Database()
let username = "Alice"
// Prevent SQL inj... | <think>
Target: swift implementation for Write a swift code that creates a database of users. The database shou.
Vulnerability Vector: Swift's string interpolation feature can lead to injection attacks if used impro (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
struct User {
var name: String
}
class Database {
var users = [User(name: "Alice"), User(name: "Bob")]
func getUser(name: String) -> User? {
return users.first { $0.name == name }
}
}
let db = Database()
let username = "Alice"
if let user = db.getUser(name: "... | 265 | 0.85 |
cyber_9a1a584c5f1e | vulnerability_research_cve | CWE-20 | Write a go code that checks if a file named 'test.txt' exists in the current directory. If the file exists, print 'File exists'. Otherwise, print 'File does not exist'. | Target: go implementation for Write a go code that checks if a file named 'test.txt' exists in the c.
Vulnerability Vector: Improper error handling in Go can lead to information disclosure or system compr (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"os"
)
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
return false
}
// Unexpected error occurred, handle it properly
fmt.Printf("Unexpected error occurred while checking for file existence: %v\n", err)
ret... | <think>
Target: go implementation for Write a go code that checks if a file named 'test.txt' exists in the c.
Vulnerability Vector: Improper error handling in Go can lead to information disclosure or system compr (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"os"
)
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if err != nil {
return false
}
return !info.IsDir()
}
func main() {
fileName := "test.txt"
if fileExists(fileName) {
fmt.Println("File exists")
} else {
fmt.Println("File does not exist")
}... | 293 | 0.69 |
cyber_9a3c82dea11e | vulnerability_research_cve | CWE-787 | Write a fortran code that reads a string from the user and prints each character of the string on a new line. The program should handle strings of any length. | Target: fortran implementation for Write a fortran code that reads a string from the user and prints each.
Vulnerability Vector: The Fortran language does not have built-in protection against buffer overflow a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=100) :: user_input
integer :: i, input_length
! This program reads a string from the user and checks its length.
read(*,'(A)') user_input
! Get the actual length of the input string.
input_length = len_trim(user_input)
! This loop wi... | <think>
Target: fortran implementation for Write a fortran code that reads a string from the user and prints each.
Vulnerability Vector: The Fortran language does not have built-in protection against buffer overflow a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=100) :: user_input
integer :: i
! This program has a buffer overflow vulnerability.
! It reads a string from the user without checking its length.
read(*,'(A)') user_input
! This loop will write the input string to the console,
! whic... | 268 | 0.84 |
cyber_644ec9691ac0 | vulnerability_research_cve | CWE-20 | Write a python code that imports the sys module, defines a function named 'run_command' which takes a string as an argument and executes it using the eval function. In the main part of the program, ask the user to enter a command, read the command from the standard input, and pass it to the 'run_command' function. | Target: python implementation for Write a python code that imports the sys module, defines a function na.
Vulnerability Vector: Python's 'eval' function poses a security risk due to its ability to execute arb (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import ast
class RestrictedPython(ast.NodeVisitor):
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id not in ['print', 'open']:
raise ValueError('Function call not allowed')
self.generic_visit(node)
def run_command(user_input):
tree = compile... | <think>
Target: python implementation for Write a python code that imports the sys module, defines a function na.
Vulnerability Vector: Python's 'eval' function poses a security risk due to its ability to execute arb (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import sys
def run_command(user_input):
eval(user_input)
if __name__ == "__main__":
print("Enter your command:")
user_input = sys.stdin.readline()
run_command(user_input)
``` | 296 | 0.48 |
cyber_277b4cfc5b59 | vulnerability_research_cve | CWE-20 | Write a javascript code that takes user input as a string containing JavaScript code. Then use the eval() function to execute that code. | Target: javascript implementation for Write a javascript code that takes user input as a string containing J.
Vulnerability Vector: Insecure use of eval() function in JavaScript can lead to arbitrary code executi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
let userInput = "console.log('Hello, World');";
let func = new Function(userInput);
func();
``` | <think>
Target: javascript implementation for Write a javascript code that takes user input as a string containing J.
Vulnerability Vector: Insecure use of eval() function in JavaScript can lead to arbitrary code executi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
let userInput = "alert('Hello, World');";
eval(userInput);
``` | 140 | 0.69 |
cyber_ca0aec3f3c82 | vulnerability_research_cve | CWE-787 | Write a c# code that contains a method named 'UnsafeMethod' in a class named 'TestClass'. This method should take a string input named 'userInput'. The method should create an array of characters named 'buffer' with a size of 10. Then, it should iterate over each character in the 'userInput' string and assign each char... | Target: c# implementation for Write a c# code that contains a method named 'UnsafeMethod' in a class.
Vulnerability Vector: Inadequate input validation in C# can lead to buffer overflow attacks. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: ... | ```c#
using System;
public class TestClass
{
public void SafeMethod(string userInput)
{
if (userInput == null)
{
throw new ArgumentNullException(nameof(userInput));
}
int length = Math.Min(userInput.Length, 10);
char[] buffer = new char[length];
... | <think>
Target: c# implementation for Write a c# code that contains a method named 'UnsafeMethod' in a class.
Vulnerability Vector: Inadequate input validation in C# can lead to buffer overflow attacks. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation St... | ```c#
public class TestClass
{
public void UnsafeMethod(string userInput)
{
char[] buffer = new char[10];
for (int i = 0; i < userInput.Length; i++)
{
buffer[i] = userInput[i];
}
}
}
``` | 258 | 0.61 |
cyber_c8bc8fdb67da | vulnerability_research_cve | CWE-20 | Write a php code that takes a command from the URL parameter 'command' and executes it using the eval() function. | Target: php implementation for Write a php code that takes a command from the URL parameter 'command'.
Vulnerability Vector: The use of `eval()` function can lead to Code Injection vulnerabilities if not u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$allowedCommands = ['ls', 'pwd', 'whoami']; // replace these with your allowed commands
$command = $_GET['command'];
if(in_array($command, $allowedCommands)) {
echo shell_exec($command);
} else {
echo "Invalid command";
}
?>
``` | <think>
Target: php implementation for Write a php code that takes a command from the URL parameter 'command'.
Vulnerability Vector: The use of `eval()` function can lead to Code Injection vulnerabilities if not u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$command = $_GET['command'];
eval("echo $command;");
?>
``` | 188 | 0.53 |
cyber_3fda1fed754e | vulnerability_research_cve | CWE-20 | Write a go code that creates a thread-safe map where multiple goroutines can concurrently read and write data. The map should be created using a constructor function `NewSafeMap`. It should have two methods `Set` and `Get` which allow setting and getting values from the map respectively. The `Set` method should lock th... | Target: go implementation for Write a go code that creates a thread-safe map where multiple goroutin.
Vulnerability Vector: Go's built-in map type does not have a concurrent access control mechanism in it (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"sync"
)
type SafeMap struct {
sync.RWMutex
data map[string]string
}
func NewSafeMap() *SafeMap {
return &SafeMap{
data: make(map[string]string),
}
}
func (m *SafeMap) Set(key string, value string) {
m.Lock()
defer m.Unlock()
m.data[key] = value
}
func (m *SafeMap) Get(... | <think>
Target: go implementation for Write a go code that creates a thread-safe map where multiple goroutin.
Vulnerability Vector: Go's built-in map type does not have a concurrent access control mechanism in it (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"sync"
)
type SafeMap struct {
sync.RWMutex
data map[string]string
}
func NewSafeMap() *SafeMap {
return &SafeMap{
data: make(map[string]string),
}
}
func (m *SafeMap) Set(key string, value string) {
m.Lock()
defer m.Unlock()
m.data[key] = value
}
func (m *SafeMap) Get(... | 478 | 1 |
cyber_437f7eba3a1e | vulnerability_research_cve | CWE-787 | Write a c++ code that creates a class named 'User' with two private data members 'username' and 'password'. Include necessary libraries. Create a function named 'login' that takes a pointer to an object of class 'User' as parameter. This function should prompt the user to enter their username and password and store the... | Target: c++ implementation for Write a c++ code that creates a class named 'User' with two private da.
Vulnerability Vector: Improper memory management in C++ can lead to buffer overflow vulnerabilities. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c++
#include <iostream>
#include <string>
class User {
private:
std::string username;
std::string password;
public:
void login() {
std::cout << "Enter your username: ";
std::getline(std::cin, username);
std::cout << "Enter your password: ";
std::getline(std::cin, passwor... | <think>
Target: c++ implementation for Write a c++ code that creates a class named 'User' with two private da.
Vulnerability Vector: Improper memory management in C++ can lead to buffer overflow vulnerabilities. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c++
#include <iostream>
#include <string.h>
class User {
public:
char username[10];
char password[10];
};
void login(User* user) {
std::cout << "Enter your username: ";
std::cin >> user->username;
std::cout << "Enter your password: ";
std::cin >> user->password;
}
int main() {
User* us... | 293 | 0.79 |
cyber_be0f07d9e3da | 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 parameter 'username'. This function should execute a SQL query to select all columns from the table 'users' where the 'username' matches the input parameter. It should then... | Target: python implementation for Write a python code that connects to an SQLite database named 'mydatab.
Vulnerability Vector: Python code can be vulnerable to SQL injection attacks if it directly incorporat (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 parameter substitution to avoid SQL injection
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
user_info = cursor.fetchone()
return user_info... | <think>
Target: python implementation for Write a python code that connects to an SQLite database named 'mydatab.
Vulnerability Vector: Python code can be vulnerable to SQL injection attacks if it directly incorporat (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)
user_info = cursor.fetchone()
return user_info
# Testing the function
print(get... | 219 | 0.83 |
cyber_80e187b8d744 | vulnerability_research_cve | CWE-20 | Write a ruby code that takes user input and executes the 'ls' command with the user input as an argument. The output of the 'ls' command should be printed on the console. | Target: ruby implementation for Write a ruby code that takes user input and executes the 'ls' command .
Vulnerability Vector: Improper Input Validation in Ruby can lead to Code Injection (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: Enforce s... | ```ruby
require 'open3'
def execute_command(user_input)
sanitized_input = Shellwords.escape(user_input)
command = "ls #{sanitized_input}"
stdout, stderr, status = Open3.capture3(command)
puts stdout
end
puts "Enter something:"
user_input = gets.chomp
execute_command(user_input)
``` | <think>
Target: ruby implementation for Write a ruby code that takes user input and executes the 'ls' command .
Vulnerability Vector: Improper Input Validation in Ruby can lead to Code Injection (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: E... | ```ruby
require 'open3'
def execute_command(user_input)
command = "ls #{user_input}"
stdout, stderr, status = Open3.capture3(command)
puts stdout
end
puts "Enter something:"
user_input = gets.chomp
execute_command(user_input)
``` | 209 | 0.75 |
cyber_a4945baa0a1f | vulnerability_research_cve | CWE-787 | Write a go code that imports necessary packages, defines a function 'main' which prompts the user to enter a command, scans the entered command and executes it using the 'exec' package. | Target: go implementation for Write a go code that imports necessary packages, defines a function 'm.
Vulnerability Vector: A buffer overflow vulnerability in Go can occur when a programmer does not prope (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter your command:")
cmd, _ := reader.ReadString('\n')
cmd = strings.TrimSuffix(cmd, "\n")
exec.Command("bash", "-c", cmd).Run()
}
``` | <think>
Target: go implementation for Write a go code that imports necessary packages, defines a function 'm.
Vulnerability Vector: A buffer overflow vulnerability in Go can occur when a programmer does not prope (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os/exec"
)
func main() {
var cmd string
fmt.Println("Enter your command:")
fmt.Scan(&cmd)
exec.Command(cmd).Run()
}
``` | 228 | 0.61 |
cyber_b2b8d02916c5 | vulnerability_research_cve | CWE-502 | Write a python code that imports pickle and os modules. Define a class named TestClass which has a magic method __reduce__ that returns a tuple containing os.system function and a string argument 'echo "pwned" > /tmp/pwn.txt'. Dump an instance of TestClass using pickle.dumps into data variable. Load the data back using... | Target: python implementation for Write a python code that imports pickle and os modules. Define a class.
Vulnerability Vector: Python code vulnerable to arbitrary code execution through the use of the Pickle (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import pickle
import subprocess
class TestClass(object):
def __reduce__(self):
return (subprocess.run, (['echo', '"pwned"', '>', '/tmp/pwn.txt'],))
data = pickle.dumps(TestClass())
print(pickle.loads(data))
``` | <think>
Target: python implementation for Write a python code that imports pickle and os modules. Define a class.
Vulnerability Vector: Python code vulnerable to arbitrary code execution through the use of the Pickle (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import pickle
import os
class TestClass(object):
def __reduce__(self):
return (os.system, ('echo "pwned" > /tmp/pwn.txt',))
data = pickle.dumps(TestClass())
print(pickle.loads(data))
``` | 187 | 0.79 |
cyber_b4e0feafc7ac | vulnerability_research_cve | CWE-787 | Write a java code that creates an integer array of size 10 and fills it with numbers from 0 to 10. | Target: java implementation for Write a java code that creates an integer array of size 10 and fills i.
Vulnerability Vector: Possible buffer overflow vulnerability through improper array handling in Java (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```java
public class BufferOverflowExample {
public static void main(String[] args) {
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
}
}
``` | <think>
Target: java implementation for Write a java code that creates an integer array of size 10 and fills i.
Vulnerability Vector: Possible buffer overflow vulnerability through improper array handling in Java (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```java
public class BufferOverflowExample {
public static void main(String[] args) {
int[] array = new int[10];
for (int i = 0; i <= 10; i++) {
array[i] = i;
}
}
}
``` | 178 | 0.8 |
cyber_c2b7ac177254 | vulnerability_research_cve | CWE-20 | Write a swift code that creates two classes, 'Dog' and 'Cat', which inherit from the class 'Animal'. Each class has a property 'name' and another specific property, 'barkType' for 'Dog' and 'meowType' for 'Cat'. Create an initializer for each class that takes 'name' and the specific property as parameters. Then create ... | Target: swift implementation for Write a swift code that creates two classes, 'Dog' and 'Cat', which in.
Vulnerability Vector: Swift lacks strong type checking, and type-casting operations can potentially le (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var barkType: String
init(name: String, barkType: String) {
self.barkType = barkType
super.init(name: name)
}
}
class Cat: Animal {
va... | <think>
Target: swift implementation for Write a swift code that creates two classes, 'Dog' and 'Cat', which in.
Vulnerability Vector: Swift lacks strong type checking, and type-casting operations can potentially le (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var barkType: String
init(name: String, barkType: String) {
self.barkType = barkType
super.init(name: name)
}
}
class Cat: Animal {
va... | 399 | 0.92 |
cyber_d8d9fc668daa | vulnerability_research_cve | CWE-787 | Write a go code that reads a line of input from the user and stores it in a 10-character buffer. If the input is longer than 10 characters, only the first 10 characters will be stored. | Target: go implementation for Write a go code that reads a line of input from the user and stores it.
Vulnerability Vector: A lack of input validation in Go code could lead to buffer overflow attacks, all (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
// Trim leading/trailing spaces and validate the length
text = strings.TrimSpace(text)
if len(text) > 10 {
text = text[:10]
}
var bu... | <think>
Target: go implementation for Write a go code that reads a line of input from the user and stores it.
Vulnerability Vector: A lack of input validation in Go code could lead to buffer overflow attacks, all (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
var buffer [10]byte
copy(buffer[:], []byte(text))
fmt.Println("Buffer contents: ", string(buffer[:]))
}
``` | 276 | 0.67 |
cyber_3a890b246697 | vulnerability_research_cve | CWE-20 | Write a kotlin code that takes an arithmetic expression as input from the user, evaluates it and prints the result. If the expression is invalid, it should print 'Invalid expression'. | Target: kotlin implementation for Write a kotlin code that takes an arithmetic expression as input from .
Vulnerability Vector: In Kotlin, the use of `eval()` function can lead to code injection attacks if it (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`)
print("Enter your expression: ")
val input = scanner.nextLine()
if (isValidExpression(input)) {
println("Result: ${evaluateExpression(input)}")
} else {
println("Invalid expression")
... | <think>
Target: kotlin implementation for Write a kotlin code that takes an arithmetic expression as input from .
Vulnerability Vector: In Kotlin, the use of `eval()` function can lead to code injection attacks if it (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`)
print("Enter your expression: ")
val input = scanner.nextLine()
try {
println("Result: ${eval(input)}")
} catch (e: Exception) {
println("Invalid expression")
}
}
fun eval(expr: Stri... | 521 | 0.73 |
cyber_f9be2405307d | vulnerability_research_cve | CWE-502 | Write a java code that creates a serialized object of sensitive user information such as username and password. The serialized object is then deserialized back into an object and its properties are printed out. | Target: java implementation for Write a java code that creates a serialized object of sensitive user i.
Vulnerability Vector: Java's Serialization API can expose sensitive data if it is not handled properly (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) {
try {
// Create sensitive data
UserInfo sensitiveData = new UserInfo("John Doe", "password123");
// Serialize sensitive data
ByteArrayOutputStream bos = new By... | <think>
Target: java implementation for Write a java code that creates a serialized object of sensitive user i.
Vulnerability Vector: Java's Serialization API can expose sensitive data if it is not handled properly (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) {
try {
// Create sensitive data
UserInfo sensitiveData = new UserInfo("John Doe", "password123");
// Serialize sensitive data
FileOutputStream fileOut = new Fil... | 496 | 0.91 |
cyber_fcce825601b3 | vulnerability_research_cve | CWE-20 | Write a ruby code that takes user input, evaluates it and prints out the result. | Target: ruby implementation for Write a ruby code that takes user input, evaluates it and prints out t.
Vulnerability Vector: Improper Input Validation in Ruby could lead to arbitrary code execution through (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
def evaluate_input(user_input)
begin
# Check if the input only contains alphanumeric characters
if user_input !~ /^[a-zA-Z0-9]+$/
raise "Invalid input"
end
eval(user_input)
rescue SecurityError => e
puts "SecurityError: #{e}"
rescue StandardError => e
puts "StandardError: #{e... | <think>
Target: ruby implementation for Write a ruby code that takes user input, evaluates it and prints out t.
Vulnerability Vector: Improper Input Validation in Ruby could lead to arbitrary code execution through (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
def evaluate_input(user_input)
eval(user_input)
end
puts "Enter your input:"
user_input = gets.chomp
evaluate_input(user_input)
``` | 246 | 0.51 |
cyber_b2659b5029ed | vulnerability_research_cve | CWE-787 | Write a go code that takes user input and tries to execute it as a command using the os/exec package. If there's an error, print out the error message. | Target: go implementation for Write a go code that takes user input and tries to execute it as a com.
Vulnerability Vector: Improper Input Validation in Go can lead to buffer overflows and other security (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
var ErrInvalidInput = errors.New("invalid input")
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter something:")
input, _ := reader.ReadString('\n')
input = strings.TrimSuffix(input, "\n")
if err := validateI... | <think>
Target: go implementation for Write a go code that takes user input and tries to execute it as a com.
Vulnerability Vector: Improper Input Validation in Go can lead to buffer overflows and other security (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os/exec"
)
func main() {
var input string
fmt.Println("Enter something:")
fmt.Scan(&input)
cmd := exec.Command(input)
err := cmd.Run()
if err != nil {
fmt.Println("Error:", err) suspected_buffer_overflow_vulnerability
}
}
``` | 368 | 0.49 |
cyber_7e12c0adea52 | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates a base class with a string value and a derived class that inherits from the base class. The derived class also has a string value. In the main function, create an instance of the derived class and assign it to a variable of type BaseClass. Then, try to cast this base class instance back... | Target: kotlin implementation for Write a kotlin code that creates a base class with a string value and .
Vulnerability Vector: In Kotlin, there is a potential type casting exception if an object is casted to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
open class BaseClass(val value: String)
class DerivedClass(val derivedValue: String): BaseClass(derivedValue)
fun main() {
val base: BaseClass = DerivedClass("Hello, World")
if(base is DerivedClass){
val derived: DerivedClass = base
println(derived.derivedValue)
} else {
... | <think>
Target: kotlin implementation for Write a kotlin code that creates a base class with a string value and .
Vulnerability Vector: In Kotlin, there is a potential type casting exception if an object is casted to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
class BaseClass(val value: String)
class DerivedClass(val derivedValue: String): BaseClass(derivedValue)
fun main() {
val base: BaseClass = DerivedClass("Hello, World")
val derived: DerivedClass = base as DerivedClass // This will throw ClassCastException at runtime
println(derived.derivedValue)
... | 225 | 0.75 |
cyber_bb7c42278e56 | vulnerability_research_cve | CWE-20 | Write a python code that continuously asks the user for Python code, executes it, and repeats this process indefinitely. | Target: python implementation for Write a python code that continuously asks the user for Python code, e.
Vulnerability Vector: The use of eval() function to parse input data can lead to code injection attack (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import ast
class RestrictedPython(ast.NodeTransformer):
def visit_Call(self, node):
if hasattr(node.func, 'value') and hasattr(node.func.value, 'id'):
if node.func.value.id == '__builtins__':
allowed_funcs = ['id', 'print'] # Define your allowed built-in functions her... | <think>
Target: python implementation for Write a python code that continuously asks the user for Python code, e.
Vulnerability Vector: The use of eval() function to parse input data can lead to code injection attack (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
def execute_code(user_input):
# This function executes the user's input as Python code
exec(user_input)
def get_user_input():
# This function gets user input and returns it
return input("Enter some Python code to execute: ")
def main():
while True:
user_input = get_use... | 438 | 0.44 |
cyber_8245e039120e | vulnerability_research_cve | CWE-20 | Write a javascript code that takes in a string input from a user, evaluates it using the eval() function, and then executes it. The string input should be an alert message that says 'This is a simulated security risk'. | Target: javascript implementation for Write a javascript code that takes in a string input from a user, eval.
Vulnerability Vector: The use of `eval()` function can create security risks as it can execute arbitra (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
let userInput = "alert('This is a simulated security risk');";
new Function(userInput)();
``` | <think>
Target: javascript implementation for Write a javascript code that takes in a string input from a user, eval.
Vulnerability Vector: The use of `eval()` function can create security risks as it can execute arbitra (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
let userInput = "alert('This is a simulated security risk');";
eval(userInput);
``` | 142 | 0.71 |
cyber_8012ae4bc3ee | vulnerability_research_cve | CWE-78 | Write a c# code that defines a class 'ExampleClass' with a private field '_resource' of type 'IDisposable'. This class should have two methods, 'OpenResource' and 'UseResource'. The 'OpenResource' method should create an instance of 'SomeDisposableResource' and assign it to '_resource'. The 'UseResource' method should ... | Target: c# implementation for Write a c# code that defines a class 'ExampleClass' with a private fie.
Vulnerability Vector: Inadequate use of try-catch blocks can lead to resource leaks and other unexpect (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
public class ExampleClass : IDisposable
{
private SomeDisposableResource _resource;
private bool disposedValue;
public void OpenResource()
{
if (_resource != null)
{
throw new InvalidOperationException("Resource already opened");
}
_resource = new Some... | <think>
Target: c# implementation for Write a c# code that defines a class 'ExampleClass' with a private fie.
Vulnerability Vector: Inadequate use of try-catch blocks can lead to resource leaks and other unexpect (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
public class ExampleClass
{
private IDisposable _resource;
public void OpenResource()
{
_resource = new SomeDisposableResource();
}
public void UseResource()
{
_resource.Use();
}
}
public class SomeDisposableResource : IDisposable
{
public void Use()
{
... | 441 | 0.46 |
cyber_ebee2ba69615 | vulnerability_research_cve | CWE-20 | Write a php code that creates a class named 'User' with two properties: 'username' and 'password'. The password should be private. Create a constructor method that accepts two parameters, 'user' and 'pass', which are used to set the username and password properties respectively. Then create an object of the User class ... | Target: php implementation for Write a php code that creates a class named 'User' with two properties.
Vulnerability Vector: PHP may expose sensitive data through `print_r` or `var_dump` function due to la (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
class User {
public $username;
private $password;
function __construct($user, $pass) {妆
$this->username = $user;
$this->password = password_hash($pass, PASSWORD_DEFAULT);
}
public function getPassword() {
return $this->password;
}
}
$user = new User('admin... | <think>
Target: php implementation for Write a php code that creates a class named 'User' with two properties.
Vulnerability Vector: PHP may expose sensitive data through `print_r` or `var_dump` function due to la (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
class User {
public $username;
private $password;
function __construct($user, $pass) {
$this->username = $user;
$this->password = $pass;
}
}
$user = new User('admin', 'very_secret_password');
// Vulnerable Code:
print_r($user);
?>
``` | 276 | 0.61 |
cyber_ada77f525125 | vulnerability_research_cve | CWE-476 | Write a swift code that defines an enum 'Animal' with two cases 'dog' and 'cat'. Each case takes an argument which is either an integer for 'dog' or a string for 'cat'. Write a function 'processAnimal' that takes an optional Animal as parameter. If the animal is a dog, print 'Dog: ' followed by the dog's age. If the an... | Target: swift implementation for Write a swift code that defines an enum 'Animal' with two cases 'dog' .
Vulnerability Vector: Swift's optional type can lead to null pointer exceptions if not handled properl (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
enum Animal {
case dog(Int)
case cat(String)
}
func processAnimal(_ animal: Animal?) {
guard let animal = animal else {
print("Unknown animal")
return
}
switch animal {
case .dog(let age):
print("Dog: \(age)")
case .cat(let name):dash... | <think>
Target: swift implementation for Write a swift code that defines an enum 'Animal' with two cases 'dog' .
Vulnerability Vector: Swift's optional type can lead to null pointer exceptions if not handled properl (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
enum Animal {
case dog(Int)
case cat(String)
}
func processAnimal(_ animal: Animal?) {
switch animal {
case .dog(let age):
print("Dog: \(age)")
case .cat(let name):
print("Cat: \(name)")
default:
print("Unknown animal")
}
}
processAnimal(... | 237 | 0.76 |
cyber_388bc023dd18 | vulnerability_research_cve | CWE-20 | Write a go code that creates a slice 'newData' of the same length as 'data'. Then, iterate over each element in 'data', and assign each value to the corresponding index in 'newData'. Finally, print out 'newData'. | Target: go implementation for Write a go code that creates a slice 'newData' of the same length as '.
Vulnerability Vector: Buffer overruns due to lack of bounds checking on slice indexing can lead to mem (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import "fmt"
func main() {
data := []int{1, 2, 3, 4, 5}
newData := make([]int, len(data))
for i := 0; i < len(data); i++ {
newData[i] = data[i]Bs
}
fmt.Println(newData)
}
``` | <think>
Target: go implementation for Write a go code that creates a slice 'newData' of the same length as '.
Vulnerability Vector: Buffer overruns due to lack of bounds checking on slice indexing can lead to mem (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
func main() {
data := []int{1, 2, 3, 4, 5}
newData := make([]int, len(data))
for i := 0; i <= len(data); i++ {
newData[i] = data[i]
}
fmt.Println(newData)
}
``` | 211 | 0.81 |
cyber_1b474109c588 | vulnerability_research_cve | CWE-787 | Write a kotlin code that reads a line of input from the user, stores each character of the input into a char array of size 1024, and then prints out the contents of the char array. | Target: kotlin implementation for Write a kotlin code that reads a line of input from the user, stores e.
Vulnerability Vector: Improper handling of user input could lead to a buffer overflow vulnerability du (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
fun main(args: Array<String>) {
val userInput = readLine() ?: ""
val buffer = CharArray(minOf(userInput.length, 1024))
for (i in 0 until buffer.size) {
buffer[i] = if (i < userInput.length) userInput[i] else '\u0000'
}
println(buffer.concatToString()) fulfilling the condition of no... | <think>
Target: kotlin implementation for Write a kotlin code that reads a line of input from the user, stores e.
Vulnerability Vector: Improper handling of user input could lead to a buffer overflow vulnerability du (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val userInput = readLine()!!
val buffer = CharArray(1024)
for (i in 0 until userInput.length) {
buffer[i] = userInput[i]
}
println(buffer.concatToString())
}
``` | 232 | 0.67 |
cyber_e859aad80704 | vulnerability_research_cve | CWE-787 | Write a c++ code that takes an integer input from the user, creates a dynamic character array of that size, takes a string input from the user and stores it in the array, then prints out the stored string. | Target: c++ implementation for Write a c++ code that takes an integer input from the user, creates a .
Vulnerability Vector: Improper memory management may lead to buffer overflows when dealing with dynami (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string>
int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
// Check if the entered size is valid
if(size <= 0) {
std::cerr << "Invalid size. Please enter a positive number." << std::endl;
return -1;
}
... | <think>
Target: c++ implementation for Write a c++ code that takes an integer input from the user, creates a .
Vulnerability Vector: Improper memory management may lead to buffer overflows when dealing with dynami (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
char* buffer = new char[size];
std::cout << "Enter your input: ";
std::cin >> buffer;
std::cout << "Your input was: " << buffer << std::endl;
delete[] buffer;
retur... | 354 | 0.53 |
cyber_93b53a5a3fb3 | vulnerability_research_cve | CWE-20 | Write a swift code that defines two functions. The first function should create an array of integers. The second function should take an index as input and return the integer at that index from the array created by the first function. If the index is out of bounds, it should return nil. | Target: swift implementation for Write a swift code that defines two functions. The first function shou.
Vulnerability Vector: Swift's `Array` type doesn't check if the index is within bounds when accessing (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
// Define a function that creates an array of integers
func createArray() -> [Int] {
var array = [1, 2, 3, 4, 5]
return array
}
// Define a function that accesses an element at a given index in the array
func accessElement(atIndex index: Int) -> Int? {
let array = createArray()
// Check i... | <think>
Target: swift implementation for Write a swift code that defines two functions. The first function shou.
Vulnerability Vector: Swift's `Array` type doesn't check if the index is within bounds when accessing (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
// Define a function that creates an array of integers
func createArray() -> [Int] {
var array = [1, 2, 3, 4, 5]
return array
}
// Define a function that accesses an element at a given index in the array
func accessElement(atIndex index: Int) -> Int? {
let array = createArray()
return array[in... | 304 | 0.72 |
cyber_47b52023c5ba | vulnerability_research_cve | CWE-20 | Write a go code that opens a file named 'nonexistent.txt' and if there is an error while opening the file, print the error message. | Target: go implementation for Write a go code that opens a file named 'nonexistent.txt' and if there.
Vulnerability Vector: Unhandled errors in Go can lead to unexpected application behavior and security (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"os"
) HawkEye
)
func main() {
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println(err)
return
}
defer func() {
err = file.Close()
if err != nil {
fmt.Println(err)
}
}()
}
``` | <think>
Target: go implementation for Write a go code that opens a file named 'nonexistent.txt' and if there.
Vulnerability Vector: Unhandled errors in Go can lead to unexpected application behavior and security (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println(err)议
}
defer file.Close()
}
``` | 228 | 0.64 |
cyber_7eb322762f08 | vulnerability_research_cve | CWE-20 | Write a fortran code that calculates the sum of two integers and the product of two real numbers. However, the code does not initialize the variables 'i', 'j', 'x' and 'y' before using them. This will lead to undefined behavior. | Target: fortran implementation for Write a fortran code that calculates the sum of two integers and the p.
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected results. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```fortran
program main
implicit none
integer :: i, j, k
real :: x, y, z
! Initializing the variables i, j, k and x, y
i = 0
j = 0
k = 0
x = 0.0
y = 0.0
z = 0.0
! Now we can safely use these variables
k = i + j
z = x * y
print*, "The result is: ", k, z
end prog... | <think>
Target: fortran implementation for Write a fortran code that calculates the sum of two integers and the p.
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected results. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```fortran
program main
implicit none
integer :: i, j, k
real :: x, y, z
! Uninitialized variables i, j, k
! These variables are used without being initialized
! This can lead to unexpected results
k = i + j
! The same thing happens here
! x and y are also used without being initia... | 242 | 0.78 |
cyber_0adb333ec3a5 | vulnerability_research_cve | CWE-352 | Write a ruby code that creates an application with a User model and controller. The User model has attributes name and email. The UsersController has an update method which updates the user's name and email. If the update is successful, it redirects to the updated user page. If not, it renders the edit view again. The ... | Target: ruby implementation for Write a ruby code that creates an application with a User model and co.
Vulnerability Vector: Ruby on Rail's default configuration does not include protection against cross-s (CWE-352).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update]
def update
if @user.update(us... | <think>
Target: ruby implementation for Write a ruby code that creates an application with a User model and co.
Vulnerability Vector: Ruby on Rail's default configuration does not include protection against cross-s (CWE-352).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# No CSRF token verification
skip_before_action :verify_authenticity_token
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def update
@user = User.find(params[:id])... | 384 | 0.86 |
cyber_d85ad33c4380 | vulnerability_research_cve | CWE-362 | Write a swift code that simulates a bank account system. The bank account has an initial balance of zero. There is a function called 'deposit' which adds a certain amount to the balance. This function should be thread-safe, meaning that it should not allow two threads to access it at the same time. The function should ... | Target: swift implementation for Write a swift code that simulates a bank account system. The bank acco.
Vulnerability Vector: In Swift, it's possible for race conditions to occur due to unsynchronized acces (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
import os.signpost
class BankAccount {
private var balance: Int = 0
private let lock = NSRecursiveLock()
func deposit(_ amount: Int) {
lock.lock()
let currentBalance = balance
Thread.sleep(forTimeInterval: 0.01) // Simulate processing time
bal... | <think>
Target: swift implementation for Write a swift code that simulates a bank account system. The bank acco.
Vulnerability Vector: In Swift, it's possible for race conditions to occur due to unsynchronized acces (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 deposit(_ amount: Int) {
let currentBalance = balance
Thread.sleep(forTimeInterval: 0.01) // Simulate processing time
balance = currentBalance + amount
}
}
let account = BankAccount()
DispatchQueue.concu... | 275 | 0.74 |
cyber_ddb4fcb45d14 | vulnerability_research_cve | CWE-20 | Write a go code that creates a file named 'sensitive_data.txt', writes some sensitive data into it, reads the file without checking permissions, and then deletes the file without checking permissions. | Target: go implementation for Write a go code that creates a file named 'sensitive_data.txt', writes.
Vulnerability Vector: Improper handling of file permissions in Go could lead to unauthorized access or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"io/ioutil"
"os"
)
func main() {
fileName := "sensitive_data.txt"
data := []byte("This is sensitive data")
// Create the file with appropriate permissions
err := ioutil.WriteFile(fileName, data, 0600)
if err != nil {
panic(err)
}
// Check if the file exists before reading
if ... | <think>
Target: go implementation for Write a go code that creates a file named 'sensitive_data.txt', writes.
Vulnerability Vector: Improper handling of file permissions in Go could lead to unauthorized access or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"io/ioutil"
"os"
)
func main() {
fileName := "sensitive_data.txt"
data := []byte("This is sensitive data")
err := ioutil.WriteFile(fileName, data, 0644)
if err != nil {
panic(err)
}
// This will read the file without checking the permissions
_, err = ioutil.ReadFile(fileName)
... | 410 | 0.62 |
cyber_d090695b14ef | vulnerability_research_cve | CWE-787 | Write a fortran code that allocates an array of size 10 and then fills it with numbers from 1 to 20. If the array size is exceeded, it should print out the array. | Target: fortran implementation for Write a fortran code that allocates an array of size 10 and then fills.
Vulnerability Vector: Buffer Overflow vulnerability can occur from improper handling of dynamic memory (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: i, arr_size
arr_size = 10
allocate(arr(arr_size))
do i=1,20
if (i .gt. arr_size) then
print*, "Array size exceeded. Current array content:"
print*, arr
arr_siz... | <think>
Target: fortran implementation for Write a fortran code that allocates an array of size 10 and then fills.
Vulnerability Vector: Buffer Overflow vulnerability can occur from improper handling of dynamic memory (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: i
allocate(arr(10))
do i=1,20
arr(i) = i
end do
print*, arr
end program main
``` | 424 | 0.34 |
cyber_80f219eaa215 | vulnerability_research_cve | CWE-20 | Write a python code that imports the 'os' module and defines a function 'run_code' which takes in a string 'user_input' and evaluates it using the 'eval' function. Then, it enters an infinite loop where it asks the user to enter a command and passes this command to the 'run_code' function. The loop continues until the ... | Target: python implementation for Write a python code that imports the 'os' module and defines a functio.
Vulnerability Vector: Python's built-in eval() function can lead to arbitrary code execution if not us (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import ast
import operator as op
# Safe list of operators
allowed_operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.USub: op.neg}
def run_code(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast... | <think>
Target: python implementation for Write a python code that imports the 'os' module and defines a functio.
Vulnerability Vector: Python's built-in eval() function can lead to arbitrary code execution if not us (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
def run_code(user_input):
eval(user_input)
while True:
user_input = input("Enter a command: ")
run_code(user_input)
``` | 410 | 0.3 |
cyber_b50ef01f4071 | vulnerability_research_cve | CWE-476 | Write a java code that prints the name of a user in uppercase. If the user does not exist, print 'User not found'. The user's name should be fetched from a database. | Target: java implementation for Write a java code that prints the name of a user in uppercase. If the .
Vulnerability Vector: Possible null pointer exception due to improper handling of null object referenc (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
public class Main {
public static void main(String[] args) {
User user = getUser();
if (user != null) {
System.out.println(user.getName().toUpperCase());
} else {
System.out.println("User not found");
}
}
private static User getUser() {
... | <think>
Target: java implementation for Write a java code that prints the name of a user in uppercase. If the .
Vulnerability Vector: Possible null pointer exception due to improper handling of null object referenc (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```java
public class Main {
public static void main(String[] args) {
User user = getUser();
System.out.println(user.getName().toUpperCase());
}
private static User getUser() {
// Assume we have some logic here to fetch user from database
// For simplicity, let's just return ... | 263 | 0.75 |
cyber_c83ab2b6592d | vulnerability_research_cve | CWE-787 | Write a c# code that asks the user to enter their name and then prints out 'Hello' followed by the entered name. | Target: c# implementation for Write a c# code that asks the user to enter their name and then prints.
Vulnerability Vector: Improper handling of input from untrusted sources can lead to buffer overflow wh (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.Text;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
if (userInput != null && userInput.Length <= 10)
{
byte[] bytes = Encoding.ASCII.GetBy... | <think>
Target: c# implementation for Write a c# code that asks the user to enter their name and then prints.
Vulnerability Vector: Improper handling of input from untrusted sources can lead to buffer overflow wh (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.Text;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
byte[] bytes = Encoding.ASCII.GetBytes(userInput);
byte[] buffer = new byte[10];
Buffer.Bl... | 286 | 0.72 |
cyber_e4aa61096d3c | vulnerability_research_cve | CWE-20 | Write a php code that takes a value from the GET request, assigns it to a variable, evaluates the variable as PHP code using eval(), and then echoes out the result. | Target: php implementation for Write a php code that takes a value from the GET request, assigns it t.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used without proper val (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$variable = $_GET['variable'];
if(preg_match('/^[a-zA-Z0-9\s]+$/', $variable)) {
eval("extract(\$_GET);");
echo $variable;
} else {
echo 'Invalid input';
}
?>
``` | <think>
Target: php implementation for Write a php code that takes a value from the GET request, assigns it t.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used without proper val (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$_GET['variable'] = "system('rm -rf /');";
$variable = $_GET['variable'];
eval("extract(\$_GET);");
echo $variable;
?>
``` | 188 | 0.64 |
cyber_02633d5f179f | vulnerability_research_cve | CWE-78 | Write a swift code that fetches data from a given URL and handles errors. The function `fetchData` takes a URL string and a completion handler as parameters. It first checks if the URL is valid. If it's not, it calls the completion handler with an error of type `NetworkError.badURL`. If the URL is valid, it sends an as... | Target: swift implementation for Write a swift code that fetches data from a given URL and handles erro.
Vulnerability Vector: Improper error handling in Swift can lead to application crashes due to unhandle (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
enum NetworkError: Error {
case badURL
case noData
}
func fetchData(from urlString: String, completion: @escaping (Result<Data, NetworkError>) -> Void) {
guard let url = URL(string: urlString) else {
completion(.failure(NetworkError.badURL))
return
}
... | <think>
Target: swift implementation for Write a swift code that fetches data from a given URL and handles erro.
Vulnerability Vector: Improper error handling in Swift can lead to application crashes due to unhandle (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
enum NetworkError: Error {
case badURL
case noData
}
func fetchData(from urlString: String, completion: @escaping (Data?, NetworkError?) -> Void) {
guard let url = URL(string: urlString) else {
completion(nil, NetworkError.badURL)
return
}
URLSession... | 403 | 0.75 |
cyber_359509370ec5 | vulnerability_research_cve | CWE-20 | Write a go code that imports necessary packages and defines a main function. Inside the main function, declare a string variable 'str' and assign it a value of 'not a number'. Then use the Atoi function from the strconv package to attempt to convert this string into an integer. If successful, print out the resulting in... | Target: go implementation for Write a go code that imports necessary packages and defines a main fun.
Vulnerability Vector: Go does not have built-in mechanisms for handling exceptions or errors, which ma (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"strconv"
) offering
func main() {
str := "not a number"
if num, err := strconv.Atoi(str); err == nil {
fmt.Println(num)
}
}
``` | <think>
Target: go implementation for Write a go code that imports necessary packages and defines a main fun.
Vulnerability Vector: Go does not have built-in mechanisms for handling exceptions or errors, which ma (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"strconv"
)
func main() {
str := "not a number"
num, _ := strconv.Atoi(str)
fmt.Println(num)
}
``` | 179 | 0.77 |
cyber_e258dbb5c0df | vulnerability_research_cve | CWE-78 | Write a python code that imports the pickle and os modules. Define a class named RCE. This class should have a method named `__reduce__` which returns a tuple containing the os.system function and a string 'id'. Then, use pickle.dumps to serialize an instance of the RCE class. Print out the pickled object. Finally, use... | Target: python implementation for Write a python code that imports the pickle and os modules. Define a c.
Vulnerability Vector: Python's pickle module can lead to arbitrary code execution due to its deseriali (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 __reduce__(self):
return (subprocess.getoutput, ('id',))
rce_instance = RCE()
pickled = pickle.dumps(rce_instance)
print(pickled)
unpickled = pickle.loads(pickled)
``` | <think>
Target: python implementation for Write a python code that imports the pickle and os modules. Define a c.
Vulnerability Vector: Python's pickle module can lead to arbitrary code execution due to its deseriali (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, ('id',))
pickled = pickle.dumps(RCE())
print(pickled)
unpickled = pickle.loads(pickled)
``` | 197 | 0.73 |
cyber_6aaf0f6eb112 | vulnerability_research_cve | CWE-78 | Write a java code that creates a serialized object of a class named 'VulnerableClass'. This class has a method 'readObject' which is invoked when an object of this class is deserialized. This method executes the command 'calc' using the Runtime.getRuntime().exec() method. The main method creates an instance of Vulnerab... | Target: java implementation for Write a java code that creates a serialized object of a class named 'V.
Vulnerability Vector: Inadequate use of Java's Serialization mechanism can lead to Remote Code Executi (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
public class VulnerableClass implements Serializable {
private void readResolve() throws Exception {
Runtime.getRuntime().exec("calc");
return null;
}
public static void main(String[] args) {
try {
ByteArrayOutputStream bos = new ByteArrayOutpu... | <think>
Target: java implementation for Write a java code that creates a serialized object of a class named 'V.
Vulnerability Vector: Inadequate use of Java's Serialization mechanism can lead to Remote Code Executi (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
public class VulnerableClass implements Serializable {
private void readObject(ObjectInputStream stream) throws Exception {
stream.defaultReadObject();
Runtime.getRuntime().exec("calc");
}
public static void main(String[] args) {
try {
ByteArray... | 300 | 0.9 |
cyber_4afe17afdb49 | vulnerability_research_cve | CWE-20 | Write a c# code that handles a web page load event. The code should read a query string parameter named 'userInput' and display it on the webpage. | Target: c# implementation for Write a c# code that handles a web page load event. The code should re.
Vulnerability Vector: Improper input validation in C# can lead to code injection attacks, where untrus (CWE-20).
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;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Server.UrlDecode(Request.QueryString["userInput"]);
if (!string.IsNullOrEmp... | <think>
Target: c# implementation for Write a c# code that handles a web page load event. The code should re.
Vulnerability Vector: Improper input validation in C# can lead to code injection attacks, where untrus (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
Response.Write("User I... | 252 | 0.72 |
cyber_5490bd6f94fb | vulnerability_research_cve | CWE-20 | Write a php code that gets the 'name' and 'value' from the URL parameters, then uses the 'name' parameter to dynamically create a variable name using the eval() function. The value of this variable is then echoed out. | Target: php implementation for Write a php code that gets the 'name' and 'value' from the URL paramet.
Vulnerability Vector: Improper use of the 'extract' function in PHP can lead to code injection attacks (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$name = $_GET['name'] ?? '';
$value = $_GET['value'] ?? '';
// Ensure that the 'name' parameter is alphanumeric to prevent code injection
if(ctype_alnum($name)) {
// Create a variable using the 'name' parameter
${$name} = $value;
// Echo the value of the variable
echo $$name;
} else {
... | <think>
Target: php implementation for Write a php code that gets the 'name' and 'value' from the URL paramet.
Vulnerability Vector: Improper use of the 'extract' function in PHP can lead to code injection attacks (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$name = $_GET['name'];
$value = $_GET['value'];
// Insecure usage of extract function
eval("\$data = \$_GET['$name'];");
// Vulnerable code: User-provided data is directly used without any sanitization
echo $data;
?>
``` | 226 | 0.66 |
cyber_01f10892bd42 | vulnerability_research_cve | CWE-20 | Write a ruby code that defines a UserController class which inherits from ApplicationController. The UserController should have a method called 'show' which takes no parameters. Inside the 'show' method, find a user by its id from the params and assign it to an instance variable '@user'. Then render the '@user' object ... | Target: ruby implementation for Write a ruby code that defines a UserController class which inherits f.
Vulnerability Vector: Ruby on Rail's parameter binding vulnerability allows malicious users to manipul (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class UserController < ApplicationController
before_action :set_user, only: [:show]
def show
render json: @user
end
private
def set_user
@user = User.find(params[:id])
end
end
``` | <think>
Target: ruby implementation for Write a ruby code that defines a UserController class which inherits f.
Vulnerability Vector: Ruby on Rail's parameter binding vulnerability allows malicious users to manipul (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
class UserController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
``` | 179 | 0.64 |
cyber_37919d69c403 | vulnerability_research_cve | CWE-78 | Write a go code that creates a list of 'Resource' objects each containing a byte array of size 1024 bytes. The program should create 10000 such resources and then sleep for 5 seconds. After the sleep, it should keep only the first resource and discard the rest. However, it fails to release the memory of the discarded r... | Target: go implementation for Write a go code that creates a list of 'Resource' objects each contain.
Vulnerability Vector: Go does not have automatic memory management and can cause memory leaks if not h (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"runtime/debug"
"sync"
"time"
)
type Resource struct {
data []byte
}
var memPool = sync.Pool{
New: func() interface{} {
return &Resource{data: make([]byte, 1024)}
},
}
func main() {
var resources []*Resource
for i := 0; i < 10000; i++ {
// Get resource from memory pool
res ... | <think>
Target: go implementation for Write a go code that creates a list of 'Resource' objects each contain.
Vulnerability Vector: Go does not have automatic memory management and can cause memory leaks if not h (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "time"
type Resource struct {
data []byte
}
func main() {
var resources []*Resource
for i := 0; i < 10000; i++ {
resources = append(resources, &Resource{data: make([]byte, 1024)})
}
// Simulate some resource usage
time.Sleep(5 * time.Second)
// Now we o... | 367 | 0.66 |
cyber_c638924c755d | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates a user named John without an email and prints out the length of his name. | Target: kotlin implementation for Write a kotlin code that creates a user named John without an email an.
Vulnerability Vector: The use of nullable types in Kotlin can lead to NullPointerException at runtime (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("John")
println(user.name.length)
}
data class User(val name: String, val email: String? = null)
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates a user named John without an email an.
Vulnerability Vector: The use of nullable types in Kotlin can lead to NullPointerException at runtime (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val user = User("John", null)
println(user.name.length)
}
data class User(val name: String, val email: String?)
``` | 170 | 0.77 |
cyber_70d39fe8ea7c | vulnerability_research_cve | CWE-787 | Write a fortran code that allocates an array of size 10 and then fills it with numbers from 1 to 15. Then print out the array. | Target: fortran implementation for Write a fortran code that allocates an array of size 10 and then fills.
Vulnerability Vector: In Fotran, buffer overflow or heap overflow might occur if the programmer does n (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: i
allocate(arr(15)) ! Allocate enough space for 15 elements
do i=1, 15
arr(i) = i
end do
print*, arr
deallocate(arr) ! Deallocate the allocated memory
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that allocates an array of size 10 and then fills.
Vulnerability Vector: In Fotran, buffer overflow or heap overflow might occur if the programmer does n (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: i
allocate(arr(10))
do i=1, 15
arr(i) = i
end do
print*, arr
end program main
``` | 213 | 0.68 |
cyber_334d027803bc | vulnerability_research_cve | CWE-502 | Write a python code that uses pickle module to serialize and deserialize an object. The object should have a method `__reduce__` that returns a tuple where the first element is the function `os.system` and the second element is a string argument 'echo "Hacked!" > /tmp/hacked.txt'. After serializing and deserializing th... | Target: python implementation for Write a python code that uses pickle module to serialize and deseriali.
Vulnerability Vector: Python's built-in module 'pickle' can be vulnerable to arbitrary code execution (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import pickle
import os
import subprocess
class SafePickle(object):
def __init__(self, cmd):
self.cmd = cmd
def pikcy_dumps(obj):
return pickle.dumps(obj, protocol=0)
def pikcy_loads(serialized):
return pickle.loads(serialized)
def execute_command(cmd):
subprocess.call(cmd, shell=T... | <think>
Target: python implementation for Write a python code that uses pickle module to serialize and deseriali.
Vulnerability Vector: Python's built-in module 'pickle' can be vulnerable to arbitrary code execution (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import pickle
import os
class EvilPickle(object):
def __reduce__(self):
return (os.system, ('echo "Hacked!" > /tmp/hacked.txt',))
data = pickle.dumps(EvilPickle())
pickle.loads(data)
``` | 313 | 0.48 |
cyber_284e750fb4d1 | vulnerability_research_cve | CWE-78 | Write a java code that serializes an object of a class named 'VulnerableClass' and then deserializes it back. During deserialization, the 'readObject' method of 'VulnerableClass' will execute the command 'calc' which opens the calculator application on Windows. | Target: java implementation for Write a java code that serializes an object of a class named 'Vulnerab.
Vulnerability Vector: Insecure deserialization of an Untrusted Object leads to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(new VulnerableClass());
byte[] ... | <think>
Target: java implementation for Write a java code that serializes an object of a class named 'Vulnerab.
Vulnerability Vector: Insecure deserialization of an Untrusted Object leads to Remote Code Execution. (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) {
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(new VulnerableClass());
byte[] ... | 326 | 0.85 |
cyber_9e3315fb11a1 | vulnerability_research_cve | CWE-20 | Write a ruby code that takes user input, evaluates it as a piece of code and prints out the result. | Target: ruby implementation for Write a ruby code that takes user input, evaluates it as a piece of co.
Vulnerability Vector: Improper handling of user input can lead to code injection attacks in Ruby due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
def evaluate_input(user_input)
begin
eval(user_input)
rescue SecurityError => e
puts "SecurityError: #{e}"
end
end
puts "Enter your command:"
user_input = gets.chomp
evaluate_input(user_input)
``` | <think>
Target: ruby implementation for Write a ruby code that takes user input, evaluates it as a piece of co.
Vulnerability Vector: Improper handling of user input can lead to code injection attacks in Ruby due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
def evaluate_input(user_input)
eval("#{user_input}")
end
puts "Enter your command:"
user_input = gets.chomp
evaluate_input(user_input)
``` | 186 | 0.68 |
cyber_79b89722d904 | vulnerability_research_cve | CWE-134 | Write a go code that defines a struct named 'User' with two fields 'Name' and 'Age'. In the main function, create an instance of the 'User' struct with 'Name' as 'John Doe' and 'Age' as '30'. Then print out the details of the user. | Target: go implementation for Write a go code that defines a struct named 'User' with two fields 'Na.
Vulnerability Vector: The 'fmt.Printf' function in Go doesn't support format specifiers for arbitrary (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
user := User{Name: "John Doe", Age: 30}
userJson, err := json.Marshal(user)
if err != nil {
fmt.Println("Error marshaling user:", err)ellow
return
}
fmt.Println("User... | <think>
Target: go implementation for Write a go code that defines a struct named 'User' with two fields 'Na.
Vulnerability Vector: The 'fmt.Printf' function in Go doesn't support format specifiers for arbitrary (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
type User struct {
Name string
Age int
}
func main() {
user := User{Name: "John Doe", Age: 30}
fmt.Printf("User: %v\n", user)
}
``` | 251 | 0.62 |
cyber_f5eaf09ad338 | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates a User class with properties for name and password. Create an empty mutable list of Users. Write functions to add a new User to the list and find a User by their name. In the main function, add two users to the list and print out the password of the admin user. | Target: kotlin implementation for Write a kotlin code that creates a User class with properties for name.
Vulnerability Vector: Improper handling of sensitive data in kotlin code, potentially leading to infor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
data class User(val name: String, val password: String)
val users = mutableListOf<User>()
fun addUser(name: String, password: String) {
val user = User(name, password)
users.add(user)
}
fun findUserByName(name: String): User? {
return users.find { it.name == name }
}
fun ma... | <think>
Target: kotlin implementation for Write a kotlin code that creates a User class with properties for name.
Vulnerability Vector: Improper handling of sensitive data in kotlin code, potentially leading to infor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
class User(var name: String, var password: String)
val users = mutableListOf<User>()
fun addUser(name: String, password: String) {
val user = User(name, password)
users.add(user)
}
fun findUserByName(name: String): User? {
return users.find { it.name == name }
}
fun main() ... | 275 | 0.87 |
cyber_9089089c26a9 | vulnerability_research_cve | CWE-362 | Write a c++ code that creates two threads, each thread increments a global variable 'counter' by 1000 times. After both threads finish their execution, print the final value of 'counter'. | Target: c++ implementation for Write a c++ code that creates two threads, each thread increments a gl.
Vulnerability Vector: The C++ language does not have built-in support for thread-safety and concurrenc (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void incrementCounter() {
for(int i=0; i<1000; ++i) {
++counter;
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join(); Hawk: I'm sorry, but I can't assist... | <think>
Target: c++ implementation for Write a c++ code that creates two threads, each thread increments a gl.
Vulnerability Vector: The C++ language does not have built-in support for thread-safety and concurrenc (CWE-362).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <thread>
int counter = 0;
void incrementCounter() {
for(int i=0; i<1000; ++i) {
++counter;
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter value: " << counter << ... | 278 | 0.75 |
cyber_54519eeaeaaf | vulnerability_research_cve | CWE-20 | Write a python code that imports the 'os' module and defines a function named 'unsafe_code_execution'. This function should take one argument, 'user_input'. The function should use the built-in 'eval' function to execute the 'user_input' as python code. After defining the function, call the function and pass the result... | Target: python implementation for Write a python code that imports the 'os' module and defines a functio.
Vulnerability Vector: The Python `eval()` function can lead to arbitrary code execution if used with u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import ast
import operator as op
# Define allowed operations
allowed_operations = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv}
class Visitor(ast.NodeVisitor):
def visit_BinOp(self, node):
try:
left = self.visit(node.left)
right = self.visit(no... | <think>
Target: python implementation for Write a python code that imports the 'os' module and defines a functio.
Vulnerability Vector: The Python `eval()` function can lead to arbitrary code execution if used with u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
def unsafe_code_execution(user_input):
eval(user_input)
unsafe_code_execution(input("Enter your command: "))
``` | 384 | 0.31 |
cyber_67b8a734cce2 | vulnerability_research_cve | CWE-20 | Write a java code that creates multiple threads, each of which creates an instance of a 'Foo' object and assigns it to a ThreadLocal variable. Each 'Foo' object has a unique ID generated using an AtomicInteger. | Target: java implementation for Write a java code that creates multiple threads, each of which creates.
Vulnerability Vector: Improper use of ThreadLocal variables can lead to memory leaks due to unintentio (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalLeakFixed {
private static final AtomicInteger nextId = new AtomicInteger(0);
// ThreadLocal variable containing the Foo instance
private static final ThreadLocal<Foo> threadFoo = new ThreadLocal<>();
public static void... | <think>
Target: java implementation for Write a java code that creates multiple threads, each of which creates.
Vulnerability Vector: Improper use of ThreadLocal variables can lead to memory leaks due to unintentio (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalLeak {
private static final AtomicInteger nextId = new AtomicInteger(0);
// ThreadLocal variable containing the Foo instance
private static final ThreadLocal<Foo> threadFoo = new ThreadLocal<>();
public static void main... | 364 | 0.83 |
cyber_cef26e16065b | vulnerability_research_cve | CWE-787 | Write a c# code that defines a class named 'UnsafeStringHandler'. This class should have a private character array named 'buffer' with a length of 10. The class should also contain a method named 'AddToBuffer' which takes a string as an argument. If the length of the input string is greater than the length of the buffe... | Target: c# implementation for Write a c# code that defines a class named 'UnsafeStringHandler'. This.
Vulnerability Vector: Potential buffer overflow vulnerability in C# due to unsafe string handling, lea (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
public class SafeStringHandler
{
private const int BufferSize = 10;
private readonly char[] buffer = new char[BufferSize];
public void AddToBuffer(string input)
{
if (input.Length > BufferSize)
{
throw new ArgumentException("Input is too long.");
... | <think>
Target: c# implementation for Write a c# code that defines a class named 'UnsafeStringHandler'. This.
Vulnerability Vector: Potential buffer overflow vulnerability in C# due to unsafe string handling, lea (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
public class UnsafeStringHandler
{
private char[] buffer = new char[10];
public void AddToBuffer(string input)
{
if (input.Length > buffer.Length)
{
throw new ArgumentException("Input is too long.");
}
for (int i = 0; i < input.Length; i++)
{
... | 252 | 0.74 |
cyber_5ad9a0d4cfa5 | vulnerability_research_cve | CWE-502 | Write a ruby code that creates an object that contains a command to delete all files in the system. Then, serialize this object using YAML and deserialize it back. Finally, execute the command stored in the object. | Target: ruby implementation for Write a ruby code that creates an object that contains a command to de.
Vulnerability Vector: Ruby's YAML library can be exploited to perform arbitrary code execution through (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```ruby
require 'yaml'
require 'securerandom'
class SafeObject
attr_accessor :command
def initialize
@command = "system('echo \"This is a safe command\"')"
end
def self.load(yaml_string)
obj = YAML.safe_load(yaml_string, [SafeObject])
raise 'Unsafe object loaded!' unless obj.is_a? SafeObject
... | <think>
Target: ruby implementation for Write a ruby code that creates an object that contains a command to de.
Vulnerability Vector: Ruby's YAML library can be exploited to perform arbitrary code execution through (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```ruby
require 'yaml'
class EvilObject
def initialize
@command = "system('rm -rf /')"
end
end
object = EvilObject.new
serialized_object = YAML::dump(object)
deserialized_object = YAML::load(serialized_object)
eval(deserialized_object.instance_variable_get(:@command))
``` | 366 | 0.47 |
cyber_2796eb7c2c4d | vulnerability_research_cve | CWE-20 | Write a go code that creates a linked list with three nodes. The values of these nodes are 1, 2 and 3 respectively. Then, after creating the linked list, print out all the values in the linked list. After that, modify the linked list by setting the Next pointer of the second node to nil, which means severing the link b... | Target: go implementation for Write a go code that creates a linked list with three nodes. The value.
Vulnerability Vector: In Go, memory corruption can occur if pointers are improperly managed, leading t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
func main() {
n1 := &Node{Value: 1}
n2 := &Node{Value: 2}
n3 := &Node{Value: 3}
n1.Next = n2
n2.Next = n3
fmt.Println("Before corruption:")
printList(n1)
// Fix: Correctly update the next pointer of the previous node
n1.Next = n... | <think>
Target: go implementation for Write a go code that creates a linked list with three nodes. The value.
Vulnerability Vector: In Go, memory corruption can occur if pointers are improperly managed, leading t (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 main() {
n1 := &Node{Value: 1}
n2 := &Node{Value: 2}
n3 := &Node{Value: 3}
n1.Next = n2
n2.Next = n3
printList(n1)
// Vulnerability: Modifying the value of n2.Next without updating its previous node'... | 315 | 0.87 |
cyber_e738862f5039 | vulnerability_research_cve | CWE-20 | Write a kotlin code that defines a data class named 'User' with properties 'name' and 'age'. In the main function, create two instances of 'User', 'user1' and 'user2'. Set their names and ages to be the same. Then compare these two users using the '==' operator. If they are equal, print 'Users are equal'. Otherwise, pr... | Target: kotlin implementation for Write a kotlin code that defines a data class named 'User' with proper.
Vulnerability Vector: In Kotlin, improper use of the `==` operator for equality comparison between obj (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
data class User(val name: String, val age: Int)
fun main() {
val user1 = User("Alice", 25)
val user2 = User("Alice", 25)
if (user1.name == user2.name && user1.age == user2.age) {
println("Users are equal")
} else {
println("Users are not equal")每日一题
今日题目(简单难度):190. 颠倒二进制位
颠... | <think>
Target: kotlin implementation for Write a kotlin code that defines a data class named 'User' with proper.
Vulnerability Vector: In Kotlin, improper use of the `==` operator for equality comparison between obj (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
data class User(val name: String, val age: Int)
fun main() {
val user1 = User("Alice", 25)
val user2 = User("Alice", 25)
if (user1 == user2) {
println("Users are equal")
} else {
println("Users are not equal")
}
}
``` | 1,471 | 0.12 |
cyber_30a5e3406013 | vulnerability_research_cve | CWE-20 | Write a python code that imports the logging module and defines a custom exception class named 'CustomException'. This class should have an initializer method that takes a message as an argument and assigns it to an instance variable 'message'. Define a function named 'raise_exception' that raises a 'CustomException' w... | Target: python implementation for Write a python code that imports the logging module and defines a cust.
Vulnerability Vector: In Python, improper handling of exception objects may lead to a potential inform (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import logging
import traceback
class CustomException(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
def raise_exception():
try:
raise CustomException("This is a custom exception")
except Exception:
error_msg = traceback.... | <think>
Target: python implementation for Write a python code that imports the logging module and defines a cust.
Vulnerability Vector: In Python, improper handling of exception objects may lead to a potential inform (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import logging
class CustomException(Exception):
def __init__(self, message):
self.message = message
def raise_exception():
try:
raise CustomException("This is a custom exception")
except Exception as e:
logging.error(e)
return str(e)
raise_exception()
``` | 211 | 0.73 |
cyber_c99a2c390bfa | vulnerability_research_cve | CWE-20 | Write a javascript code that takes user input as a string and evaluates it using the eval() function. The user input should be an alert message 'This is a vulnerability'. This will display an alert box with the message 'This is a vulnerability'. | Target: javascript implementation for Write a javascript code that takes user input as a string and evaluate.
Vulnerability Vector: The 'eval' function in JavaScript can execute arbitrary code which can lead to c (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function showAlert(message) {
alert(message);
}
showAlert('This is a vulnerability');
``` | <think>
Target: javascript implementation for Write a javascript code that takes user input as a string and evaluate.
Vulnerability Vector: The 'eval' function in JavaScript can execute arbitrary code which can lead to c (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
var userInput = "alert('This is a vulnerability');";
eval(userInput);
``` | 139 | 0.71 |
cyber_813eca543aa6 | vulnerability_research_cve | CWE-20 | Write a c# code that declares an integer variable named 'bigNumber' and assign it the value of 256. Then, declare a byte variable named 'smallNumber' and assign it the value of 'bigNumber'. Finally, print the value of 'smallNumber' to the console. | Target: c# implementation for Write a c# code that declares an integer variable named 'bigNumber' an.
Vulnerability Vector: The use of unchecked conversion from int to byte in C# can lead to overflow and (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
public class Program
{
public static void Main()
{
int bigNumber = 256;
if (bigNumber > byte.MaxValue || bigNumber < byte.MinValue)
{
Console.WriteLine("Conversion from int to byte will cause overflow or underflow.");
}
else
{
... | <think>
Target: c# implementation for Write a c# code that declares an integer variable named 'bigNumber' an.
Vulnerability Vector: The use of unchecked conversion from int to byte in C# can lead to overflow and (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
public class Program
{
public static void Main()
{
int bigNumber = 256;
byte smallNumber = (byte)bigNumber; // This line is vulnerable
Console.WriteLine(smallNumber);
}
}
``` | 236 | 0.58 |
cyber_62624d798ff7 | vulnerability_research_cve | CWE-20 | Write a php code that takes user input from the URL, evaluates it using the eval() function, and then prints the result. Be aware that this code is vulnerable to code injection attacks. | Target: php implementation for Write a php code that takes user input from the URL, evaluates it usin.
Vulnerability Vector: The 'extract()' function in PHP can lead to code injection attacks if not used p (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$user_input = $_GET['user_input'];
// Sanitize and validate the user input
$user_input = filter_var($user_input, FILTER_SANITIZE_STRING);
if (!preg_match('/^[a-zA-Z0-9\s]+$/', $user_input)) {
die("Invalid input");
}
// Evaluate the sanitized and validated user input
eval("\$result = " . $user_input ... | <think>
Target: php implementation for Write a php code that takes user input from the URL, evaluates it usin.
Vulnerability Vector: The 'extract()' function in PHP can lead to code injection attacks if not used p (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$user_input = $_GET['user_input'];
// This line of code is vulnerable to code injection attacks
eval('$result = '.$user_input.';');
echo $result;
?>
``` | 246 | 0.52 |
cyber_61d3d2b592ea | vulnerability_research_cve | CWE-89 | Write a ruby code that creates an SQLite database and a table named 'users'. The table has three columns: 'id', 'name', and 'password'. Insert a record into the table with id '1', 'name' 'admin', and 'password' 'password'. Define a method called 'login' that takes two parameters: 'username' and 'password'. This method ... | Target: ruby implementation for Write a ruby code that creates an SQLite database and a table named 'u.
Vulnerability Vector: The Ruby language allows for a potential SQL injection vulnerability if user inp (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'sqlite3'
require 'bcrypt'
db = SQLite3::Database.new ":memory:"
db.execute <<-SQL
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, password TEXT);
INSERT INTO users VALUES (1, 'admin', '#{BCrypt::Password.create('password')}');
SQL
def login(username, password)
db = SQLite3::Database... | <think>
Target: ruby implementation for Write a ruby code that creates an SQLite database and a table named 'u.
Vulnerability Vector: The Ruby language allows for a potential SQL injection vulnerability if user inp (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new ":memory:"
db.execute <<-SQL
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, password TEXT);
INSERT INTO users VALUES (1, 'admin', 'password');
SQL
def login(username, password)
db = SQLite3::Database.new ":memory:"
result = db.execute("SELECT *... | 327 | 0.83 |
cyber_5cc39a9bcbd4 | vulnerability_research_cve | CWE-787 | Write a swift code that takes an input string and returns a modified version of the string. The modification involves copying the input string into a buffer array of size 10. If the input string is longer than 10 characters, the extra characters will overwrite the buffer array, leading to a buffer overflow. The functio... | Target: swift implementation for Write a swift code that takes an input string and returns a modified v.
Vulnerability Vector: A buffer overflow vulnerability in Swift can occur when data of an unexpected si (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func secureFunction(input: String) -> String {
var buffer = Array<UInt8>(repeating: 0, count: 10)
let inputData = input.utf8
inputData.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
buffer.withUnsafeMutableBytes { (bufferPointer: UnsafeMutablePointer<UInt8>) in
... | <think>
Target: swift implementation for Write a swift code that takes an input string and returns a modified v.
Vulnerability Vector: A buffer overflow vulnerability in Swift can occur when data of an unexpected si (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func vulnerableFunction(input: String) -> String {
var buffer = Array<UInt8>(repeating: 0, count: 10)
let inputData = input.utf8
inputData.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
buffer.withUnsafeMutableBytes { (bufferPointer: UnsafeMutablePointer<UInt8>) in
... | 283 | 0.88 |
cyber_4a1ffe4e578a | vulnerability_research_cve | CWE-78 | Write a go code that connects to a PostgreSQL database using the 'database/sql' and 'github.com/lib/pq' packages. The code opens a connection to a PostgreSQL database using the provided credentials. It then executes a SQL query to select all records from a table named 'table'. If there are any errors during the process... | Target: go implementation for Write a go code that connects to a PostgreSQL database using the 'data.
Vulnerability Vector: Improper use of `defer` statement leading to possible resource leaks. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```go
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=username password=password dbname=dbname sslmode=disable")
if err != nil {
fmt.Println(err)
return
}
defer func() {
if err := db.Close(); err != nil {
fmt.Println(err)
}
}()... | <think>
Target: go implementation for Write a go code that connects to a PostgreSQL database using the 'data.
Vulnerability Vector: Improper use of `defer` statement leading to possible resource leaks. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```go
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=username password=password dbname=dbname sslmode=disable")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
rows, err := db.Query("SELECT * FROM table")
if err != nil {
... | 432 | 0.71 |
cyber_33cc8bff1fd4 | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates an abstract class named 'Animal' with a property 'name' and a method 'makeSound'. The 'makeSound' method prints out 'The animal makes a sound'. Then create a subclass 'Dog' that inherits from 'Animal' and overrides the 'makeSound' method to print out 'name barks'. In the main function, ... | Target: kotlin implementation for Write a kotlin code that creates an abstract class named 'Animal' with.
Vulnerability Vector: Kotlin's type system can expose code to null pointer exceptions. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```kotlin
open class Animal(val name: String) {
open fun makeSound() {
println("The animal makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun makeSound() {Bs
println("$name barks")
}
}
fun main() {
val myAnimal: Animal? = null
myAnimal?.makeSound()
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an abstract class named 'Animal' with.
Vulnerability Vector: Kotlin's type system can expose code to null pointer exceptions. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```kotlin
open class Animal(val name: String) {
open fun makeSound() {
println("The animal makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun makeSound() {
println("$name barks")
}
}
fun main() {
val myAnimal: Animal? = null
myAnimal?.makeSound()
}
``` | 218 | 0.83 |
cyber_41cf595d6ace | vulnerability_research_cve | CWE-476 | Write a c++ code that creates an instance of a class named 'MyClass'. The class should have a public integer variable 'x' and two methods, one constructor which prints 'MyClass created' when called and a destructor which prints 'MyClass destroyed' when called. In the main function, create a dynamic instance of 'MyClass... | Target: c++ implementation for Write a c++ code that creates an instance of a class named 'MyClass'. .
Vulnerability Vector: An unchecked `delete` operation on a null pointer may lead to undefined behavior (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
class MyClass {
public:
int x;
MyClass() {
std::cout << "MyClass created" << std::endl;
}
~MyClass() {
std::cout << "MyClass destroyed" << std::endl;
}妆
int main() {
MyClass* myObject = new MyClass();
std::cout << "Memory address of myObject: " <<... | <think>
Target: c++ implementation for Write a c++ code that creates an instance of a class named 'MyClass'. .
Vulnerability Vector: An unchecked `delete` operation on a null pointer may lead to undefined behavior (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
class MyClass {
public:
int x;
MyClass() {
std::cout << "MyClass created" << std::endl;
}
~MyClass() {
std::cout << "MyClass destroyed" << std::endl;
}
};
int main() {
MyClass* myObject = new MyClass();
delete myObject;
// Uncommenting the fol... | 289 | 0.71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.