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_45673e28c059 | vulnerability_research_cve | CWE-78 | Write a python code that checks if the user's input password matches a stored password. If the lengths of the two passwords match and each character at the same position in both passwords also match, then the access is granted. Otherwise, access is denied. | Target: python implementation for Write a python code that checks if the user's input password matches a.
Vulnerability Vector: A timing attack vulnerability can occur when a program uses timing information t (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import hmac
import time
import os
from werkzeug.security import safe_str_cmp
# Generate a random secret key
SECRET_KEY = os.urandom(16)
def check_password(input_password):
stored_password = "correctpassword"
if len(input_password) != len(stored_password):
return False
# Use HMAC to compa... | <think>
Target: python implementation for Write a python code that checks if the user's input password matches a.
Vulnerability Vector: A timing attack vulnerability can occur when a program uses timing information t (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import time
def check_password(input_password):
stored_password = "correctpassword"
if len(input_password) != len(stored_password):
return False
for i in range(len(input_password)):
if input_password[i] != stored_password[i]:
return False
time.sleep(0.1)
re... | 329 | 0.71 |
cyber_cbfe1aee0b51 | vulnerability_research_cve | CWE-20 | Write a php code that checks if a page request parameter exists in the URL. If it does, include the corresponding PHP file. | Target: php implementation for Write a php code that checks if a page request parameter exists in the.
Vulnerability Vector: PHP code running on a server can be exploited via a remote file inclusion vulner (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
// Define a whitelist of allowed pages
$allowedPages = ['home', 'about', 'contact'];
// Check if the requested page exists in the whitelist
if(isset($_REQUEST['page']) && in_array($_REQUEST['page'], $allowedPages)) {
$page = $_REQUEST['page'];
// Use the realpath function to ensure the file is wit... | <think>
Target: php implementation for Write a php code that checks if a page request parameter exists in the.
Vulnerability Vector: PHP code running on a server can be exploited via a remote file inclusion vulner (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
if(isset($_REQUEST['page'])) {
$page = $_REQUEST['page'];
include($page . '.php');
}
?>
``` | 266 | 0.42 |
cyber_e1affe725a5a | vulnerability_research_cve | CWE-20 | Write a swift code that creates an Animal class and a Dog class which inherits from Animal. The Dog class should have an additional property 'barkSound'. Create an instance of Dog named 'myDog' with name 'Fido' and barkSound 'Woof'. Then, unsafely cast 'myDog' to Animal type and assign it to 'myAnimal'. Finally, try to... | Target: swift implementation for Write a swift code that creates an Animal class and a Dog class which .
Vulnerability Vector: In Swift, the 'unsafeBitCast' function can lead to crashes or memory corruption (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) {otted
self.name = name
}
}
class Dog: Animal {
var barkSound: String
init(name: String, barkSound: String) {
self.barkSound = barkSound
super.init(name: name)
}
}
let myDog = Dog(name: "Fid... | <think>
Target: swift implementation for Write a swift code that creates an Animal class and a Dog class which .
Vulnerability Vector: In Swift, the 'unsafeBitCast' function can lead to crashes or memory corruption (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 barkSound: String
init(name: String, barkSound: String) {
self.barkSound = barkSound
super.init(name: name)
}
}
let myDog = Dog(name: "Fido", ba... | 306 | 0.91 |
cyber_77bb41714e08 | vulnerability_research_cve | CWE-20 | Write a go code that measures the execution time of a function called 'expensiveFunction' which simulates a time-consuming operation by sleeping for 1 second. This function is called in a loop 1 million times in the main function. The total execution time of the main function is measured and printed. | Target: go implementation for Write a go code that measures the execution time of a function called .
Vulnerability Vector: Go's garbage collector is non-deterministic, which can lead to timing attacks an (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"time"
) Hawk
)
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
fmt.Printf("%s took %s\n", name, elapsed)
}
func expensiveFunction() {
time.Sleep(1 * time.Second)
}
func main() {
defer timeTrack(time.Now(), "main")
for i := 0; i < 1000000; i++ {
... | <think>
Target: go implementation for Write a go code that measures the execution time of a function called .
Vulnerability Vector: Go's garbage collector is non-deterministic, which can lead to timing attacks an (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"time"
)
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
fmt.Printf("%s took %s\n", name, elapsed)
}
func expensiveFunction() {
time.Sleep(1 * time.Second)
}
func main() {
defer timeTrack(time.Now(), "main")
for i := 0; i < 1000000; i++ {
expen... | 258 | 0.84 |
cyber_5b392f754e17 | vulnerability_research_cve | CWE-78 | Write a java code that uses serialization and deserialization to execute a system command. The class `VulnerableClass` implements `Serializable` interface and overrides the `readObject()` method. This method is called when an object is deserialized. It executes the system command 'calc' which opens the calculator appli... | Target: java implementation for Write a java code that uses serialization and deserialization to execu.
Vulnerability Vector: Java's `ObjectInputStream` class can be exploited to perform deserialization att (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
public class SecureClass implements Serializable {
private void readObject(ObjectInputStream stream) throws Exception {
System.out.println("Deserializing...");
// No system command execution here
}
public static void main(String[] args) {
try {
... | <think>
Target: java implementation for Write a java code that uses serialization and deserialization to execu.
Vulnerability Vector: Java's `ObjectInputStream` class can be exploited to perform deserialization att (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 {
System.out.println("Deserializing...");
Runtime.getRuntime().exec("calc");
}
public static void main(String[] args) {
try {
... | 295 | 1.18 |
cyber_10c48a17afde | vulnerability_research_cve | CWE-20 | Write a ruby code that defines an ApplicationController class which inherits from ActionController::Base. This controller has an 'index' method that takes an input parameter, checks if it matches a regular expression pattern where the input string starts and ends with one or more 'a' characters. | Target: ruby implementation for Write a ruby code that defines an ApplicationController class which in.
Vulnerability Vector: Ruby on Rays: Ruby's regular expressions can be exploited to create a denial of (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class ApplicationController < ActionController::Base
def index
regex = /\A(a+)\z/
match_data = params[:input].match(regex)
render json: { result: match_data ? true : false }
end
end
``` | <think>
Target: ruby implementation for Write a ruby code that defines an ApplicationController class which in.
Vulnerability Vector: Ruby on Rays: Ruby's regular expressions can be exploited to create a denial of (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
class ApplicationController < ActionController::Base
def index
regex = /^(a+)+$/
params[:input].match(regex)
end
end
``` | 176 | 0.67 |
cyber_9ebff2632157 | vulnerability_research_cve | CWE-134 | Write a swift code that prints 'Hello, %s' to the console. | Target: swift implementation for Write a swift code that prints 'Hello, %s' to the console..
Vulnerability Vector: The use of `String(format:)` function in Swift can lead to format string attacks (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy:... | ```swift
import Foundation
func getUserInput() -> String {
return "World"
}
func printFormattedString() {
let userInput = getUserInput()
let formattedString = "Hello, \(userInput)"
print(formattedString)
}
printFormattedString()
``` | <think>
Target: swift implementation for Write a swift code that prints 'Hello, %s' to the console..
Vulnerability Vector: The use of `String(format:)` function in Swift can lead to format string attacks (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```swift
import Foundation
func getUserInput() -> String {
return "Hello, %s"
}
func printFormattedString() {
let userInput = getUserInput()
let formattedString = String(format: userInput)
print(formattedString)
}
printFormattedString()
``` | 187 | 0.81 |
cyber_163e7c64866f | vulnerability_research_cve | CWE-190 | Write a fortran code that adds two numbers and prints the result. | Target: fortran implementation for Write a fortran code that adds two numbers and prints the result..
Vulnerability Vector: Integer overflow vulnerability due to insufficient integer size might lead to in (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```fortran
PROGRAM SECURE_PROGRAM
IMPLICIT NONE
INTEGER*4 :: i, j, k
i = 32767
j = 1
k = i + j
WRITE(*,*) 'The result is ', k
END PROGRAM SECURE_PROGRAM
``` | <think>
Target: fortran implementation for Write a fortran code that adds two numbers and prints the result..
Vulnerability Vector: Integer overflow vulnerability due to insufficient integer size might lead to in (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```fortran
PROGRAM VULNERABLE_PROGRAM
IMPLICIT NONE
INTEGER*2 :: i, j, k
i = 32767
j = 1
k = i + j
WRITE(*,*) 'The result is ', k
END PROGRAM VULNERABLE_PROGRAM
``` | 193 | 0.85 |
cyber_bda1e4352fd3 | vulnerability_research_cve | CWE-502 | Write a python code that imports 'pickle' and 'os' modules. Define a class named 'RunBinSh' which has a special method '__reduce__' that returns a tuple containing 'os.system' function and '/bin/sh' string. Serialize an instance of 'RunBinSh' using 'pickle.dumps' and store it in variable 'data'. Then, deserialize 'data... | Target: python implementation for Write a python code that imports 'pickle' and 'os' modules. Define a c.
Vulnerability Vector: Python's pickle module can lead to arbitrary code execution if the data is malic (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import pickle
import os
import subprocess
class RunBinSh(object):
def __reduce__(self):
return (subprocess.Popen, (['/bin/sh'],))
data = pickle.dumps(RunBinSh())
pickle.loads(data)
``` | <think>
Target: python implementation for Write a python code that imports 'pickle' and 'os' modules. Define a c.
Vulnerability Vector: Python's pickle module can lead to arbitrary code execution if the data is malic (CWE-502).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import pickle
import os
class RunBinSh(object):
def __reduce__(self):
return (os.system, ('/bin/sh',))
data = pickle.dumps(RunBinSh())
pickle.loads(data)
``` | 185 | 0.74 |
cyber_8557dd170558 | vulnerability_research_cve | CWE-787 | Write a c# code that imports the kernel32.dll library and uses its GetCommandLineA function to get the command line arguments passed to the program. The function returns a pointer to a null-terminated string of 8-bit characters. The program then copies the command line arguments into a buffer, converts them to a string... | Target: c# implementation for Write a c# code that imports the kernel32.dll library and uses its Get.
Vulnerability Vector: Potential buffer overflow vulnerability when dealing with unsafe code in C#. Thi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.Runtime.InteropServices;
public class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetCommandLineA();
public static void Main()
{
IntPtr cmdLine = GetCommandLineA();
int length = Marshal.ReadInt32(cmdLine, -4); // Read... | <think>
Target: c# implementation for Write a c# code that imports the kernel32.dll library and uses its Get.
Vulnerability Vector: Potential buffer overflow vulnerability when dealing with unsafe code in C#. Thi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.Runtime.InteropServices;
public class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetCommandLineA();
public static void Main()
{
IntPtr cmdLine = GetCommandLineA();
byte[] buffer = new byte[1024];
Marshal.Copy... | 272 | 0.77 |
cyber_2348f7e7578c | vulnerability_research_cve | CWE-89 | Write a php code that takes user input, directly uses it in a SQL query without any sanitization or validation, executes the query, and then displays the results. | Target: php implementation for Write a php code that takes user input, directly uses it in a SQL quer.
Vulnerability Vector: PHP's use of `$_REQUEST` for accessing user input data can make it vulnerable to (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection was successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Validate and sanitize user input
if(isset($_REQUEST['user_in... | <think>
Target: php implementation for Write a php code that takes user input, directly uses it in a SQL quer.
Vulnerability Vector: PHP's use of `$_REQUEST` for accessing user input data can make it vulnerable to (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
// No sanitization or validation
$userInput = $_REQUEST['user_input'];
// Directly using user input to execute queries
$query = "SELECT * FROM users WHERE username='".$userInput."'";
// Execute the query
$result = mysqli_query($connection, $query);
// Display the result
while($row = mysqli_fetch_assoc($... | 403 | 0.5 |
cyber_69d9d5d648ca | vulnerability_research_cve | CWE-20 | Write a go code that prints numbers from 1 to 5 and letters from 'a' to 'e'. The numbers should be printed with a delay of 200 milliseconds, and the letters should be printed with a delay of 400 milliseconds. The main function should wait for 3 seconds before printing 'main function'. | Target: go implementation for Write a go code that prints numbers from 1 to 5 and letters from 'a' t.
Vulnerability Vector: The Go language does not support multithreading directly; instead, it has gorout (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"sync"
"time"
)
func printNumbers(wg *sync.WaitGroup) {
defer wg.Done()
for i := 1; i <= 5; i++ {
time.Sleep(200 * time.Millisecond)
fmt.Printf("%d ", i)
}
}
func printLetters(wg *sync.WaitGroup) {
defer wg.Done()
for i := 'a'; i <= 'e'; i++ {
time.Sleep(400 * time.Mil... | <think>
Target: go implementation for Write a go code that prints numbers from 1 to 5 and letters from 'a' t.
Vulnerability Vector: The Go language does not support multithreading directly; instead, it has gorout (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"time"
)
func printNumbers() {
for i := 1; i <= 5; i++ {
time.Sleep(200 * time.Millisecond)
fmt.Printf("%d ", i)
}
}
func printLetters() {
for i := 'a'; i <= 'e'; i++ {
time.Sleep(400 * time.Millisecond)
fmt.Printf("%c ", i)
}
}
func main() {
go printNumbers()
go pr... | 368 | 0.7 |
cyber_30e239dd8fde | vulnerability_research_cve | CWE-476 | Write a kotlin code that prints a null value when trying to assign a nullable string to a non-nullable string. | Target: kotlin implementation for Write a kotlin code that prints a null value when trying to assign a n.
Vulnerability Vector: Improper handling of null values during type casting can lead to NullPointerExce (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
fun main(args: Array<String>) {
val nullableString: String? = null
val nonNullableString: String? = nullableString
println(nonNullableString)
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that prints a null value when trying to assign a n.
Vulnerability Vector: Improper handling of null values during type casting can lead to NullPointerExce (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val nullableString: String? = null
val nonNullableString: String = nullableString as String // This will throw a NullPointerException
println(nonNullableString)
}
``` | 163 | 0.83 |
cyber_9904a8b0c519 | vulnerability_research_cve | CWE-78 | Write a java code that reads a text file named 'file.txt' and prints its content on the console. If an error occurs during the reading process, print 'Error occurred!' | Target: java implementation for Write a java code that reads a text file named 'file.txt' and prints i.
Vulnerability Vector: Inadequate use of Java's exception handling can lead to resource leaks if except (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) {
FileInputStream file = null;
try {
file = new FileInputStream("file.txt");
int content;
while ((content = file.read()) != -1) {
System.out.print((char) content)... | <think>
Target: java implementation for Write a java code that reads a text file named 'file.txt' and prints i.
Vulnerability Vector: Inadequate use of Java's exception handling can lead to resource leaks if except (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FileInputStream file = null;
try {
file = new FileInputStream("file.txt");
int content;
while ((content = file.read()) != -1) {
System.out.p... | 280 | 0.75 |
cyber_f1135b92125c | vulnerability_research_cve | CWE-20 | Write a c# code that creates an object and tries to convert it into a string using the ToString() method. The object is initially set to null, so the ToString() method will throw a NullReferenceException. | Target: c# implementation for Write a c# code that creates an object and tries to convert it into a .
Vulnerability Vector: The use of `Object.ToString()` method without checking for null values can lead (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(string[] args)
{
object obj = null;
try
{
Console.WriteLine(obj?.ToString());
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: Object is null. " + ex.Message... | <think>
Target: c# implementation for Write a c# code that creates an object and tries to convert it into a .
Vulnerability Vector: The use of `Object.ToString()` method without checking for null values can lead (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
public class Program
{
public static void Main(string[] args)
{
object obj = null;
Console.WriteLine(obj.ToString());
}
}
``` | 204 | 0.59 |
cyber_0fe1f88d2c47 | vulnerability_research_cve | CWE-20 | Write a go code that takes a string, converts it into a byte slice, modifies the first character of the byte slice to 'h', and then converts the modified byte slice back into a string. Print out the new string. | Target: go implementation for Write a go code that takes a string, converts it into a byte slice, mo.
Vulnerability Vector: In Go, memory corruption vulnerabilities can occur due to unsafe operations on s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "Hello, World!"
// Convert string to rune slice
runes := []rune(str)
// Modify the first character of the rune slice
runes[0] = 'h'
// Convert rune slice back to string
newStr := string(runes)
fmt.Println(newStr) // Outputs: hello, ... | <think>
Target: go implementation for Write a go code that takes a string, converts it into a byte slice, mo.
Vulnerability Vector: In Go, memory corruption vulnerabilities can occur due to unsafe operations on s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"strings"
"unsafe"
)
func main() {
str := "Hello, World!"
// Convert string to byte slice
bytes := []byte(str)
// Modify the underlying array of the byte slice
bytes[0] = 'h'
// Convert byte slice back to string
newStr := string(bytes)
fmt.Println(newStr) // Outputs: h... | 238 | 0.83 |
cyber_d0e940afe454 | vulnerability_research_cve | CWE-20 | Write a python code that asks for a username and password, checks if they match 'admin' and 'password', and if they do, it will ask for a command from the user and execute it. If the login fails, it will print 'Login failed.'. | Target: python implementation for Write a python code that asks for a username and password, checks if t.
Vulnerability Vector: Python code may be vulnerable to 'eval' function injection attacks, where untrus (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import time
def login():
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == "admin" and password == "password":
return True
else:
return False
def main():
if login():
command = input("Enter a command: ")
if c... | <think>
Target: python implementation for Write a python code that asks for a username and password, checks if t.
Vulnerability Vector: Python code may be vulnerable to 'eval' function injection attacks, where untrus (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import time
def login():
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == "admin" and password == "password":
return True
else:archar
return False
def main():
if login():
command = input("Enter a command: ")
... | 264 | 0.7 |
cyber_857f73e8ae74 | vulnerability_research_cve | CWE-787 | Write a go code that creates 10 goroutines, each assigning a unique value to a shared variable. After all goroutines have finished executing, print out the final value of the shared variable. | Target: go implementation for Write a go code that creates 10 goroutines, each assigning a unique va.
Vulnerability Vector: Go lacks built-in support for memory safety and concurrency control, leaving roo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"sync"
)
type MyStruct struct {
value int
mu sync.Mutex
}
func (m *MyStruct) UpdateValue(i int) {
m.mu.Lock()
defer m.mu.Unlock()
m.value = i
}
func main() {
var wg sync.WaitGroup
sharedValue := MyStruct{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
de... | <think>
Target: go implementation for Write a go code that creates 10 goroutines, each assigning a unique va.
Vulnerability Vector: Go lacks built-in support for memory safety and concurrency control, leaving roo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"sync"
)
type MyStruct struct {
value int
}
func main() {
var wg sync.WaitGroup
var sharedValue MyStruct
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()议
sharedValue.value = i
}(i)
}
wg.Wait()
fmt.Println(sharedValue.value)
}
``` | 313 | 0.7 |
cyber_f1d661002c50 | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates an object of class MyClass and assigns it to a variable named 'myObject'. Then, use a when expression to check if 'myObject' is an instance of MyClass or null. If 'myObject' is an instance of MyClass, print out "This will never be printed.". If 'myObject' is null, print out "This will a... | Target: kotlin implementation for Write a kotlin code that creates an object of class MyClass and assign.
Vulnerability Vector: Kotlin's `when` expressions can lead to unintended null pointer exceptions if no (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
fun main(args: Array<String>) {
val myObject: MyClass? = null
when {
myObject is MyClass -> println("This will never be printed.")
else -> println("This will always be printed.")
}
}
class MyClass
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an object of class MyClass and assign.
Vulnerability Vector: Kotlin's `when` expressions can lead to unintended null pointer exceptions if no (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
fun main(args: Array<String>) {
val myObject: MyClass? = null
when (myObject) {
is MyClass -> println("This will never be printed.")
null -> println("This will always be printed.")
}
}
class MyClass
``` | 186 | 0.8 |
cyber_756247a529ea | vulnerability_research_cve | CWE-20 | Write a javascript code that declares two variables, one named 'x' and another named 'y'. Assign the string value '10' to 'x' and the number 20 to 'y'. Then, log the result of concatenating 'x' and 'y' to the console. | Target: javascript implementation for Write a javascript code that declares two variables, one named 'x' and.
Vulnerability Vector: TypeError is a common error in JavaScript due to incorrect use of operators or v (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
let x = "10";
let y = 20;
console.log(x + String(y));
``` | <think>
Target: javascript implementation for Write a javascript code that declares two variables, one named 'x' and.
Vulnerability Vector: TypeError is a common error in JavaScript due to incorrect use of operators or v (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
var x = "10";
var y = 20;
console.log(x + y);
``` | 142 | 0.73 |
cyber_324ad2d23c15 | vulnerability_research_cve | CWE-78 | Write a c# code that creates a serialized object of a class named 'VulnerableClass' and then deserializes it back into an object. The class 'VulnerableClass' has a property 'name'. The value of 'name' is set to 'vulnerable' before serialization. After deserialization, the value of 'name' is printed out. | Target: c# implementation for Write a c# code that creates a serialized object of a class named 'Vul.
Vulnerability Vector: Insecure deserialization of objects can lead to remote code execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: E... | ```c#
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
[Serializable]
public class VulnerableClass : ISerializable
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
pu... | <think>
Target: c# implementation for Write a c# code that creates a serialized object of a class named 'Vul.
Vulnerability Vector: Insecure deserialization of objects can lead to remote code execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```c#
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class VulnerableClass
{
public string name;
}
public class Program
{
static void Main()
{
var test = new VulnerableClass();
test.name = "vulnerable";
BinaryFormatter bf... | 430 | 0.57 |
cyber_bd5cfce0b10a | vulnerability_research_cve | CWE-20 | Write a php code that retrieves data from a GET request, checks if the data exists, and then extracts it if it does. | Target: php implementation for Write a php code that retrieves data from a GET request, checks if the.
Vulnerability Vector: The PHP `extract()` function can be exploited if untrusted data is passed to it, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$input = filter_input(INPUT_GET, 'cmd', FILTER_SANITIZE_STRING);
if(isset($input) && !empty($input)){
$data = json_decode($input, true);
if(json_last_error() === JSON_ERROR_NONE){
// Now you can safely use $data
} else {
// Handle error
}
}
?>
``` | <think>
Target: php implementation for Write a php code that retrieves data from a GET request, checks if the.
Vulnerability Vector: The PHP `extract()` function can be exploited if untrusted data is passed to it, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$input = $_GET['cmd'];
if(isset($input)){
extract($input);
}
?>
``` | 218 | 0.49 |
cyber_df6240a2e096 | vulnerability_research_cve | CWE-20 | Write a swift code that opens a URL in the default browser. The URL is provided as a string and passed to a function named 'openURL'. If the string can be converted into a valid URL, the function will use the shared UIApplication instance to open the URL. | Target: swift implementation for Write a swift code that opens a URL in the default browser. The URL is.
Vulnerability Vector: In Swift, improper handling of URLs can lead to open redirect vulnerabilities. S (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else { return }
// Here we can add additional checks to ensure the URL is safe before opening it
// For example, we could check if the URL scheme is "http" or "https"
if url.scheme == "http" || ur... | <think>
Target: swift implementation for Write a swift code that opens a URL in the default browser. The URL is.
Vulnerability Vector: In Swift, improper handling of URLs can lead to open redirect vulnerabilities. S (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func openURL(_ urlString: String) {
if let url = URL(string: urlString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
let attackerControlledURL = "https://malicious-site.com"
openURL(attackerControlledURL)
``` | 262 | 0.61 |
cyber_52a8c63af595 | vulnerability_research_cve | CWE-20 | Write a go code that converts a string into an integer. If the string contains any non-integer characters, print out an error message. | Target: go implementation for Write a go code that converts a string into an integer. If the string .
Vulnerability Vector: Go does not handle errors properly when converting between string and integer ty (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"strconv"
"unicode"
)
func main() {
str := "10A" // This is a string containing an integer and a character
isValid := true
for _, c := range str {
if !unicode.IsDigit(c) {
isValid = false
break
}
}
if !isValid {
fmt.Println("Error during conversion: String contain... | <think>
Target: go implementation for Write a go code that converts a string into an integer. If the string .
Vulnerability Vector: Go does not handle errors properly when converting between string and integer ty (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 := "10A" // This is a string containing an integer and a character
num, err := strconv.Atoi(str) // This will return an error because of the non-integer character 'A'
if err != nil {
fmt.Println("Error during conversion:", err)
} else {
fmt.Pri... | 294 | 0.67 |
cyber_74545504ac1c | vulnerability_research_cve | CWE-78 | Write a kotlin code that prints out the string representation of a null value. | Target: kotlin implementation for Write a kotlin code that prints out the string representation of a nul.
Vulnerability Vector: Kotlin's `Any` type is a common source of null pointer exceptions as it allows n (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
fun main(args: Array<String>) {
val myVariable: Any? = null
if (myVariable != null) {
println(myVariable.toString())
} else {
println("The variable is null.")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that prints out the string representation of a nul.
Vulnerability Vector: Kotlin's `Any` type is a common source of null pointer exceptions as it allows n (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
fun main(args: Array<String>) {
val myVariable: Any? = null
println(myVariable.toString())
}
``` | 180 | 0.63 |
cyber_76cd979ffcbc | vulnerability_research_cve | CWE-787 | Write a c++ code that defines a function named 'copyString' which takes two character pointers as arguments. The first pointer points to the destination where the copied string should be stored and the second pointer points to the source string that needs to be copied. This function copies the source string into the de... | Target: c++ implementation for Write a c++ code that defines a function named 'copyString' which take.
Vulnerability Vector: Improper memory management may lead to buffer overflows, which can lead to code (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <string>
#include <iostream>
#include <cstring>
void copyString(char* dest, const char* src) {
while ((*dest++ = *src++));
}
int main() {
char buffer[10];
const char* string = "This is a long string that will cause a buffer overflow!";
if (strlen(string) < 10) {
copyString(buff... | <think>
Target: c++ implementation for Write a c++ code that defines a function named 'copyString' which take.
Vulnerability Vector: Improper memory management may lead to buffer overflows, which can lead to code (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <string>
#include <iostream>
void copyString(char* dest, const char* src) {
while (*src != '\0') {
*dest = *src;
dest++;archar
src++;
}
}
int main() {
char buffer[10];
const char* string = "This is a long string that will cause a buffer overflow!";
copyStrin... | 271 | 0.75 |
cyber_416d2b655c5f | vulnerability_research_cve | CWE-20 | Write a java code that uses ExecutorService and Future to execute a task that simulates a long running task. The task should sleep for 10 seconds before it finishes. If the task takes longer than 5 seconds to complete, it should be interrupted and the executor should be shut down. | Target: java implementation for Write a java code that uses ExecutorService and Future to execute a ta.
Vulnerability Vector: The use of `Thread.sleep()` method in a production environment without proper ex (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
try {
Thread.sleep(10000); // Simulate long running task
... | <think>
Target: java implementation for Write a java code that uses ExecutorService and Future to execute a ta.
Vulnerability Vector: The use of `Thread.sleep()` method in a production environment without proper ex (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
try {
Thread.sleep(10000); // Simulate long running task
... | 400 | 0.62 |
cyber_97eaa8ad0926 | vulnerability_research_cve | CWE-78 | Write a c# code that opens a SQL Server database connection using the provided connection string, perform some operations and then close the connection. | Target: c# implementation for Write a c# code that opens a SQL Server database connection using the .
Vulnerability Vector: Inadequate use of `using` statement for database connections can lead to memory (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Data.SqlClient;
public class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=localhost;Initial Catalog=mydatabase;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString))
{
... | <think>
Target: c# implementation for Write a c# code that opens a SQL Server database connection using the .
Vulnerability Vector: Inadequate use of `using` statement for database connections can lead to memory (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
public class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=localhost;Initial Catalog=mydatabase;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
// Some operations...
conn.Close();... | 299 | 0.53 |
cyber_7a2a70ee1718 | vulnerability_research_cve | CWE-89 | Write a ruby code that creates an in-memory SQLite database, creates a table named 'users' with columns 'name' and 'password'. Insert a row into the 'users' table with 'admin' as the name and 'password' as the password. Then, prompt the user to enter their username and password. If the entered username and password mat... | Target: ruby implementation for Write a ruby code that creates an in-memory SQLite database, creates a.
Vulnerability Vector: SQL Injection vulnerabilities can occur if user input is not properly sanitized (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:"
rows = db.execute <<-SQL
create table users (name varchar(30), password varchar(60));
SQL
password_hash = BCrypt::Password.create("password")
db.execute("INSERT INTO users (name, password) VALUES (?, ?)", 'admin', password_hash)
puts... | <think>
Target: ruby implementation for Write a ruby code that creates an in-memory SQLite database, creates a.
Vulnerability Vector: SQL Injection vulnerabilities can occur if user input is not properly sanitized (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new ":memory:"
rows = db.execute <<-SQL
create table users (name varchar(30), password varchar(30));
insert into users values ('admin', 'password');
SQL
puts "Enter your username:"
username = gets.chomp
puts "Enter your password:"
password = gets.chomp
user_quer... | 334 | 0.72 |
cyber_239e9a4cd7d7 | vulnerability_research_cve | CWE-20 | Write a go code that creates a new sensitive data object and sets its value to 'secret'. The sensitive data object should be created in a separate goroutine, and after the goroutine has finished executing, the data field of the sensitive data object should be set to nil. | Target: go implementation for Write a go code that creates a new sensitive data object and sets its .
Vulnerability Vector: Go's garbage collector can lead to memory leaks due to dangling pointers, which (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"sync"
"runtime"
)
type SensitiveData struct {
data string
}
func NewSensitiveData(data string) *SensitiveData {
s := &SensitiveData{data: data}
go func() {
var wg sync.WaitGroup
wg.Add(1)
go func(copy *SensitiveData) {
defer wg.Done()
copy.data = ""
// explicitly over... | <think>
Target: go implementation for Write a go code that creates a new sensitive data object and sets its .
Vulnerability Vector: Go's garbage collector can lead to memory leaks due to dangling pointers, which (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "sync"
type SensitiveData struct {
data string
}
func NewSensitiveData(data string) *SensitiveData {
s := &SensitiveData{data: data}
go func() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()otted
s = nil
}()
wg.Wait()
}()
return s
}
func main() {
s := N... | 364 | 0.62 |
cyber_c8dceb67382c | vulnerability_research_cve | CWE-20 | Write a java code that reads and prints out the content of a text file named 'file.txt'. If the file does not exist, print out 'File not found'. | Target: java implementation for Write a java code that reads and prints out the content of a text file.
Vulnerability Vector: Inadequate error handling in Java can lead to unhandled exceptions and potential (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
import java.nio.file.*;
public class Main {
public static void main(String[] args) {
Path path = Paths.get("file.txt");
if (Files.exists(path)) {
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
while ((... | <think>
Target: java implementation for Write a java code that reads and prints out the content of a text file.
Vulnerability Vector: Inadequate error handling in Java can lead to unhandled exceptions and potential (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("file.txt");
int k;
while((k = file.read()) != -1) {
System.out.print((char)k);
}
file.close();... | 279 | 0.83 |
cyber_f31b1d3adf85 | vulnerability_research_cve | CWE-20 | Write a c# code that takes user input, stores it in a variable, performs a division operation on it, and displays the result. If an exception occurs during this process, log the error message without exposing sensitive information. | Target: c# implementation for Write a c# code that takes user input, stores it in a variable, perfor.
Vulnerability Vector: Improper error handling and exception management could lead to sensitive informa (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
class Program
{
static void Main(string[] args)
{
try
{
// Assume we are getting user input from a form
string userInput = Console.ReadLine();
// Assume we are storing this user input into a variable
string sensitiveInfo = userInput;
... | <think>
Target: c# implementation for Write a c# code that takes user input, stores it in a variable, perfor.
Vulnerability Vector: Improper error handling and exception management could lead to sensitive informa (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
class Program
{
static void Main(string[] args)
{
try
{
// Assume we are getting user input from a form
string userInput = Console.ReadLine();
// Assume we are storing this user input into a variable
string sensitiveInfo = userInput;
... | 390 | 0.72 |
cyber_90819aa97ec1 | vulnerability_research_cve | CWE-20 | Write a php code that takes a GET parameter named 'code' and evaluates it using the eval function. The 'code' parameter should contain a string of PHP code which will be executed when the eval function is called. | Target: php implementation for Write a php code that takes a GET parameter named 'code' and evaluates.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used without proper san (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
if(isset($_GET['code']) && preg_match('/^[A-Za-z0-9 _]+$/', $_GET['code'])) {
$code = $_GET['code'];
eval("?>".$code);
} else {
echo "Invalid input!";
}
?>
``` | <think>
Target: php implementation for Write a php code that takes a GET parameter named 'code' and evaluates.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used without proper san (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$_GET['code'] = "<?php echo 'vulnerable'; ?>";
extract($_GET);
eval("?>".$code);
?>
``` | 189 | 0.6 |
cyber_5c2267584aab | vulnerability_research_cve | CWE-20 | Write a swift code that creates an instance of a class named 'UnsafePointerExample'. The class has a mutable pointer called 'pointer' which points to a block of memory of size 1GB. It also has a method named 'writeData' that takes a Data object and writes its content into the memory pointed by the 'pointer'. If you try... | Target: swift implementation for Write a swift code that creates an instance of a class named 'UnsafePo.
Vulnerability Vector: Potential use of 'unsafe' Swift code in a safe context, leading to memory corrup (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
class UnsafePointerExample {
typealias VoidUnsafePointer = UnsafeMutableRawPointer
var pointer: VoidUnsafePointer?
init() {
let size = 1024 * 1024 * 1024 // 1GB
pointer = calloc(size, 1)
}
func writeData(_ data: Data) {
data.withUnsa... | <think>
Target: swift implementation for Write a swift code that creates an instance of a class named 'UnsafePo.
Vulnerability Vector: Potential use of 'unsafe' Swift code in a safe context, leading to memory corrup (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
class UnsafePointerExample {
typealias VoidUnsafePointer = UnsafeMutablePointer<Void>
var pointer: VoidUnsafePointer?
init() {
let size = 1024 * 1024 * 1024 // 1GB
pointer = UnsafeMutablePointer(mutating: UnsafeMutableBufferPointer(start: UnsafeMutableRa... | 332 | 0.93 |
cyber_acea4d380c9c | vulnerability_research_cve | CWE-787 | Write a c++ code that reads an input from the user and prints it back out. | Target: c++ implementation for Write a c++ code that reads an input from the user and prints it back .
Vulnerability Vector: Buffer overflow vulnerability can occur when a programmer fails to check the len (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string>
void readInput(std::string& buffer) {
std::getline(std::cin, buffer);
}
int main() {
std::string buffer;
readInput(buffer);
std::cout << "You entered: " << buffer << std::endl;ival
return 0;
}
``` | <think>
Target: c++ implementation for Write a c++ code that reads an input from the user and prints it back .
Vulnerability Vector: Buffer overflow vulnerability can occur when a programmer fails to check the len (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string.h>
void readInput(char* buffer) {
std::cin >> buffer;
}
int main() {
char buffer[10];
readInput(buffer);
std::cout << "You entered: " << buffer << std::endl;
return 0;
}
``` | 201 | 0.8 |
cyber_791b6a58131b | vulnerability_research_cve | CWE-20 | Write a swift code that creates two instances of a class named 'Person'. Each instance should have a property 'name' of type string. The class should have an initializer that takes a name as a parameter and assigns it to the 'name' property. The class should also have a deinitializer that prints a message saying that t... | Target: swift implementation for Write a swift code that creates two instances of a class named 'Person.
Vulnerability Vector: Swift's ARC (Automatic Reference Counting) mechanism can lead to memory leaks if (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
class Person {
var name: String
init(name: String) {
self.name = name
}
deinit {
print("\(self.name) is being deinitialized")
}
}
var person1: Person? = Person(name: "John Doe") // Strong reference
var person2: Person? = Person(name: "Jane Doe") // Strong... | <think>
Target: swift implementation for Write a swift code that creates two instances of a class named 'Person.
Vulnerability Vector: Swift's ARC (Automatic Reference Counting) mechanism can lead to memory leaks if (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
// Assume we have a class "Person"
class Person {
var name: String
init(name: String) {
self.name = name
}
deinit {
print("\(self.name) is being deinitialized")
}
}
var person1: Person? = Person(name: "John Doe") // Strong reference
var person2: Person? = Person(name: "Jane... | 398 | 0.67 |
cyber_158687ade358 | vulnerability_research_cve | CWE-20 | Write a java code that creates a new thread (MyThread) and executes its run method directly on the current thread. | Target: java implementation for Write a java code that creates a new thread (MyThread) and executes it.
Vulnerability Vector: The use of Thread.run() instead of Thread.start() in Java can lead to code execu (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // This will create a new thread and execute the run method on the new thread
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.p... | <think>
Target: java implementation for Write a java code that creates a new thread (MyThread) and executes it.
Vulnerability Vector: The use of Thread.run() instead of Thread.start() in Java can lead to code execu (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.run(); // This will execute the run method on the current thread
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Running in new... | 211 | 0.78 |
cyber_f2135274ac96 | vulnerability_research_cve | CWE-787 | Write a c# code that creates an integer array of size 10 and fills it with numbers from 0 to 9. | Target: c# implementation for Write a c# code that creates an integer array of size 10 and fills it .
Vulnerability Vector: A buffer overflow vulnerability can occur when data is written past the end of a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
public class SecureOptimizedCode
{
public static void Main()
{
int[] array = new int[10];
for(int i = 0; i < 10; i++)
{
array[i] = i;Bs
}
}
}
``` | <think>
Target: c# implementation for Write a c# code that creates an integer array of size 10 and fills it .
Vulnerability Vector: A buffer overflow vulnerability can occur when data is written past the end of a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
public class VulnerableCode
{
public static void Main()
{
int[] array = new int[10];
for(int i = 0; i <= 10; i++)
{
array[i] = i;
}
}
}
``` | 190 | 0.78 |
cyber_6fd32620e2c9 | vulnerability_research_cve | CWE-20 | Write a php code that defines a function named 'dangerousFunction'. This function should accept an associative array as input. The function should use the PHP built-in function 'extract' to import variables from the input array into the current symbol table. Then, the function should print out the value of the variable... | Target: php implementation for Write a php code that defines a function named 'dangerousFunction'. Th.
Vulnerability Vector: PHP's `extract()` function is susceptible to untrusted user input which can lead (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
function safeFunction($input) {
// Validate and sanitize user input
$sanitizedInput = filter_var_array($input, FILTER_SANITIZE_STRING);
// Import variables from the sanitized input array into the current symbol table
extract($sanitizedInput);
// Echo the value of the variable ... | <think>
Target: php implementation for Write a php code that defines a function named 'dangerousFunction'. Th.
Vulnerability Vector: PHP's `extract()` function is susceptible to untrusted user input which can lead (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
function dangerousFunction($input) {
extract($input);
echo $name;
}
$userInput = array('name' => 'John Doe', 'role' => 'admin');
dangerousFunction($userInput);
?>
``` | 248 | 0.55 |
cyber_dbfddde6807e | vulnerability_research_cve | CWE-20 | Write a swift code that takes user input and prints a greeting message using the user's input. | Target: swift implementation for Write a swift code that takes user input and prints a greeting message.
Vulnerability Vector: Swift's String initializer `init(format:arguments:)` can lead to code injection (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
let userInput = "User's input"
// Use String interpolation instead of String formatting to avoid code injection
let formattedString = "Hello, \(userInput)"
print(formattedString)
``` | <think>
Target: swift implementation for Write a swift code that takes user input and prints a greeting message.
Vulnerability Vector: Swift's String initializer `init(format:arguments:)` can lead to code injection (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
let userInput = "User's input"
let formattedString = String(format: "Hello, %@", userInput)
print(formattedString)
``` | 167 | 0.71 |
cyber_d95f6008f3b6 | vulnerability_research_cve | CWE-20 | Write a kotlin code that asks the user to enter a password and checks if the entered password matches a predefined password. If the passwords match, print 'Access granted.' Otherwise, print 'Access denied'. | Target: kotlin implementation for Write a kotlin code that asks the user to enter a password and checks .
Vulnerability Vector: In Kotlin, incorrect use of the `equals` operator could lead to unintended behav (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
println("Enter your password:")
val userInput = scanner.next()
val password = "password123"
if (userInput.contentEquals(password)) {
println("Access granted.")
} else {
println("Acc... | <think>
Target: kotlin implementation for Write a kotlin code that asks the user to enter a password and checks .
Vulnerability Vector: In Kotlin, incorrect use of the `equals` operator could lead to unintended behav (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
println("Enter your password:")
val userInput = scanner.next()
var password = "password123"
if (userInput == password) {
println("Access granted.")
} else {
println("Access denied."... | 230 | 0.79 |
cyber_cb63a8957723 | vulnerability_research_cve | CWE-787 | Write a java code that creates a string 'Hello, World!' and writes it into a file named 'output.txt'. | Target: java implementation for Write a java code that creates a string 'Hello, World!' and writes it .
Vulnerability Vector: Potential buffer overflow vulnerability when using methods like `String.getBytes (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
String str = "Hello, World!";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8); // Specify the charset to avoid potential buffer overflow
File... | <think>
Target: java implementation for Write a java code that creates a string 'Hello, World!' and writes it .
Vulnerability Vector: Potential buffer overflow vulnerability when using methods like `String.getBytes (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
String str = "Hello, World!";
byte[] bytes = str.getBytes(); // This line can cause a buffer overflow if no charset is specified
FileOutputStream fos = new FileOutputStream("output.txt");... | 227 | 0.75 |
cyber_f5e3602bc14c | vulnerability_research_cve | CWE-787 | Write a fortran code that declares two arrays, array1 and array2. Array1 should have 2 elements and array2 should have 3 elements. Fill both arrays with numbers from 1 to 4. Print out the values of both arrays. | Target: fortran implementation for Write a fortran code that declares two arrays, array1 and array2. Arra.
Vulnerability Vector: The code may be vulnerable to buffer overflow errors due to improper array size (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer, dimension(2) :: array1
integer, dimension(3) :: array2
integer :: i
do i = 1, 2
array1(i) = i
end do
do i = 1, 3
array2(i) = i + 2
end do
print*, "Array1: ", array1
print*, "Array2: ", array2
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that declares two arrays, array1 and array2. Arra.
Vulnerability Vector: The code may be vulnerable to buffer overflow errors due to improper array size (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer, dimension(2) :: array1
integer, dimension(3) :: array2
integer :: i
do i = 1, 4
array1(i) = i
array2(i) = i
end do
print*, "Array1: ", array1
print*, "Array2: ", array2
end program main
``` | 231 | 0.75 |
cyber_8f3e945a26bf | vulnerability_research_cve | CWE-78 | Write a go code that connects to a PostgreSQL database, executes a SQL query and retrieves data from a table named 'test_table'. If an error occurs during the process, print out the error message. | Target: go implementation for Write a go code that connects to a PostgreSQL database, executes a SQL.
Vulnerability Vector: Go's `defer` statement can lead to resource leaks in case of early returns. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strate... | ```go
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
) Hawk
)
type DB struct {
*sql.DB
}
func OpenDB() (*DB, error) {
db, err := sql.Open("postgres", "user=dbuser password=dbpassword dbname=test sslmode=disable")
if err != nil {
return nil, err
}
return &DB{db}, nil
}
func (db *DB) Close... | <think>
Target: go implementation for Write a go code that connects to a PostgreSQL database, executes a SQL.
Vulnerability Vector: Go's `defer` statement can lead to resource leaks in case of early returns. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```go
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func OpenDB() (*sql.DB, error) {
db, err := sql.Open("postgres", "user=dbuser password=dbpassword dbname=test sslmode=disable")
if err != nil {
return nil, err
}
return db, nil
}
func CloseDB(db *sql.DB) {
err := db.Close()
if err !=... | 470 | 0.87 |
cyber_9ede39bc99cb | vulnerability_research_cve | CWE-78 | Write a fortran code that reads an input string from the user and stores it in a variable named 'buffer'. | Target: fortran implementation for Write a fortran code that reads an input string from the user and stor.
Vulnerability Vector: Buffer overrun vulnerability may occur when reading from untrusted sources in Fo (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```fortran
program main
implicit none
character(len=10) :: buffer
character(len=20) :: input
integer :: i
read(*,'(A)') input
do i = 1, len(input)
if (i > len(buffer)) then
exit
end if
buffer(i:i) = input(i:i)
end do
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that reads an input string from the user and stor.
Vulnerability Vector: Buffer overrun vulnerability may occur when reading from untrusted sources in Fo (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```fortran
program main
implicit none
character(len=10) :: buffer
character(len=20) :: input
read(*,'(A)') input
buffer = input
end program main
``` | 211 | 0.6 |
cyber_8f6643bd1ab3 | vulnerability_research_cve | CWE-20 | Write a java code that creates a large text file, writes 10 million lines to it, and then reads the file without setting a limit. | Target: java implementation for Write a java code that creates a large text file, writes 10 million li.
Vulnerability Vector: Java's BufferedReader class may be vulnerable to denial of service attacks due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
// Create a file with a large size
Path path = Paths.get("large_file.txt");
try (BufferedWriter writer = Files.newBuffere... | <think>
Target: java implementation for Write a java code that creates a large text file, writes 10 million li.
Vulnerability Vector: Java's BufferedReader class may be vulnerable to denial of service attacks due t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
// Create a file with a large size
File file = new File("large_file.txt");
PrintWriter writer = new PrintWriter(file);
for (int i = 0; i < 10000000; i++) {
writer.prin... | 359 | 0.72 |
cyber_348f497bb130 | vulnerability_research_cve | CWE-89 | Write a ruby code that interacts with an SQLite3 database. The program should prompt the user to enter an SQL query, then execute the query on the database and print the result. | Target: ruby implementation for Write a ruby code that interacts with an SQLite3 database. The program.
Vulnerability Vector: SQL Injection vulnerabilities can occur when user-supplied input is not properly (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new('test.db')
def get_user_input
gets.chomp
end
def execute_query(db, query)
begin
db.execute(query)
rescue SQLite3::Exception => e
puts "An error occurred: #{e}"
end
end
puts "Enter your SQL query:"
query = get_user_input
execute_query(db, query)
``... | <think>
Target: ruby implementation for Write a ruby code that interacts with an SQLite3 database. The program.
Vulnerability Vector: SQL Injection vulnerabilities can occur when user-supplied input is not properly (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new('test.db')
def get_user_input
gets.chomp
end
def execute_query(db, query)
db.execute(query)
end
puts "Enter your SQL query:"
query = get_user_input
execute_query(db, query)
``` | 228 | 0.72 |
cyber_f25b17bc204d | vulnerability_research_cve | CWE-134 | Write a go code that prints out the command-line argument passed by the user. | Target: go implementation for Write a go code that prints out the command-line argument passed by th.
Vulnerability Vector: The use of fmt.Printf and fmt.Fprintf functions without proper sanitization can (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"os"
)Bs
func main() {
if len(os.Args) != 2 {
fmt.Println("Please provide exactly one argument")
return
}
userInput := os.Args[1]
fmt.Println(userInput) // Fixed line
}
``` | <think>
Target: go implementation for Write a go code that prints out the command-line argument passed by th.
Vulnerability Vector: The use of fmt.Printf and fmt.Fprintf functions without proper sanitization can (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
userInput := os.Args[1]
fmt.Printf(userInput) // Vulnerable line
}
``` | 203 | 0.64 |
cyber_93033452fd88 | vulnerability_research_cve | CWE-20 | Write a java code that reads a serialized object from a file named 'secret.txt' and prints out the secret data. | Target: java implementation for Write a java code that reads a serialized object from a file named 'se.
Vulnerability Vector: Improper error handling in Java may lead to Information Disclosure or Denial of (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.io.*;
import java.util.*;
public class SecureClass {
private static final String FILE_NAME = "secret.txt";
public void readFile() {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILE_NAME);
ois = ne... | <think>
Target: java implementation for Write a java code that reads a serialized object from a file named 'se.
Vulnerability Vector: Improper error handling in Java may lead to Information Disclosure or Denial of (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.io.*;
import java.util.*;
public class VulnerableClass {
private static final String FILE_NAME = "secret.txt";
public void readFile() {
try {
FileInputStream fis = new FileInputStream(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis);
... | 415 | 0.66 |
cyber_67ca27041483 | vulnerability_research_cve | CWE-787 | Write a swift code that takes user input from command line arguments and prints it back reversed. | Target: swift implementation for Write a swift code that takes user input from command line arguments a.
Vulnerability Vector: Potential buffer overflow vulnerability due to unsafe string handling in Swift. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func getUserInput() -> String? {
let args = CommandLine.arguments
guard args.count > 1 else {
print("No input provided")
return nil
}
return args[1]
}
func processInput(input: String) -> String {
return String(input.reversed())
}
if let userInput = getUs... | <think>
Target: swift implementation for Write a swift code that takes user input from command line arguments a.
Vulnerability Vector: Potential buffer overflow vulnerability due to unsafe string handling in Swift. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func getUserInput() -> String {
let args = CommandLine.arguments
guard args.count > 1 else {
fatalError("No input provided")
}
return args[1]
}
func processInput(input: String) -> String {
var result = ""
for i in 0..<input.count {
result += input[inp... | 238 | 0.93 |
cyber_2468b75737ad | vulnerability_research_cve | CWE-20 | Write a python code that gets user input, executes it as a system command and runs it in the main function. | Target: python implementation for Write a python code that gets user input, executes it as a system comm.
Vulnerability Vector: In Python, improper handling of user input can lead to code injection attacks, w (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import subprocess
def get_user_input():
user_input = input("Enter your command: ")
return user_input
def execute_command(command):
try:
# Use subprocess module instead of os.system for executing commands
# It provides better security and control over the executed process
... | <think>
Target: python implementation for Write a python code that gets user input, executes it as a system comm.
Vulnerability Vector: In Python, improper handling of user input can lead to code injection attacks, w (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
def get_user_input():
user_input = input("Enter your command: ")
return user_input
def execute_command(command):
os.system(command)
def main():
command = get_user_input()
execute_command(command)
if __name__ == "__main__":
main()
``` | 264 | 0.61 |
cyber_0af821becf9e | vulnerability_research_cve | CWE-787 | Write a fortran code that counts from 1 to 1000000000 and prints 'Done!' when it reaches the end. | Target: fortran implementation for Write a fortran code that counts from 1 to 1000000000 and prints 'Done.
Vulnerability Vector: In Fortran, improper memory management can lead to buffer overflow and memory le (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=100) :: buffer
do i = 1, 1000000000
write(buffer, *) i
if (i == 1000000000) then
print *, "Done!"
exit
end if
end do
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that counts from 1 to 1000000000 and prints 'Done.
Vulnerability Vector: In Fortran, improper memory management can lead to buffer overflow and memory le (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer :: i, j
character(len=100) :: buffer
do i = 1, 1000000000
write(buffer, *) i
if (i == 1000000000) then
print *, "Done!"
end if
end do
end program main
``` | 218 | 0.78 |
cyber_30ac9994d017 | vulnerability_research_cve | CWE-20 | Write a c# code that creates a user and prints out the name of the user. If the user does not exist, the program should handle it gracefully. | Target: c# implementation for Write a c# code that creates a user and prints out the name of the use.
Vulnerability Vector: Improper null checking can lead to NullReferenceException in C# code. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```c#
public class Program
{
public static void Main()
{
User user = GetUser();
if (user != null)
{
Console.WriteLine(user.Name);
}
else
{
Console.WriteLine("User does not exist.");
}
}
public static User GetUser()
{
... | <think>
Target: c# implementation for Write a c# code that creates a user and prints out the name of the use.
Vulnerability Vector: Improper null checking can lead to NullReferenceException in C# code. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```c#
public class Program
{
public static void Main()
{
User user = GetUser();
Console.WriteLine(user.Name);
}
public static User GetUser()
{
// Simulate a database call where we might not get a User object
return null;
}
}
public class User
{
public string... | 242 | 0.71 |
cyber_760f8d98c542 | vulnerability_research_cve | CWE-78 | Write a kotlin code that can list files in the current directory, fetch content from a given URL and execute a command line operation. | Target: kotlin implementation for Write a kotlin code that can list files in the current directory, fetc.
Vulnerability Vector: The use of user-provided input without proper sanitization and validation can le (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.nio.file.Files
import java.nio.file.Paths
fun main(args: Array<String>) {
Files.walk(Paths.get("."))
.filter { Files.isRegularFile(it) }
.forEach { println(it) ... | <think>
Target: kotlin implementation for Write a kotlin code that can list files in the current directory, fetc.
Vulnerability Vector: The use of user-provided input without proper sanitization and validation can le (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main(args: Array<String>) {
val exec = Runtime.getRuntime().exec("ls")
val reader = BufferedReader(InputStreamReader(exec.inputStream))
var line: String?
while (reader.read... | 370 | 0.91 |
cyber_a569b983569b | vulnerability_research_cve | CWE-787 | Write a fortran code that defines two strings, one with length 5 and another with length 10. Assign the string 'Hello World!' to the second string. Then, define a subroutine named 'copy_string' which takes two arguments, a destination string and a source string. The subroutine copies the content of the source string in... | Target: fortran implementation for Write a fortran code that defines two strings, one with length 5 and a.
Vulnerability Vector: A buffer overflow vulnerability in Fortran can occur when a string is copied int (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=5) :: str1
character(len=10) :: str2
str2 = 'Hello World!'
call copy_string(str1, str2)
print*, str1
contains
subroutine copy_string(dest, src)
character(*), intent(out) :: dest
character(*), intent(in) :: src
intege... | <think>
Target: fortran implementation for Write a fortran code that defines two strings, one with length 5 and a.
Vulnerability Vector: A buffer overflow vulnerability in Fortran can occur when a string is copied int (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=5) :: str1
character(len=10) :: str2
str2 = 'Hello World!'
call copy_string(str1, str2)
contains
subroutine copy_string(dest, src)
character(*), intent(out) :: dest
character(*), intent(in) :: src
dest = src
end subr... | 292 | 0.64 |
cyber_c88e0c1266a2 | vulnerability_research_cve | CWE-20 | Write a java code that defines two decimal numbers, adds them together, and checks if the result is exactly equal to 0.3. If it is, print 'The sum of x and y is equal to 0.3'. Otherwise, print 'The sum of x and y is NOT equal to 0.3'. | Target: java implementation for Write a java code that defines two decimal numbers, adds them together.
Vulnerability Vector: Java's '==' operator can lead to unexpected results when dealing with floating p (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
public class Main {
private static final double TOLERANCE = 0.00001; // Define a tolerance level for floating point comparison
public static void main(String[] args) {
double x = 0.1;
double y = 0.2;
double z = x + y;
if (Math.abs(z - 0.3) < TOLERANCE) {
Sys... | <think>
Target: java implementation for Write a java code that defines two decimal numbers, adds them together.
Vulnerability Vector: Java's '==' operator can lead to unexpected results when dealing with floating p (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
public class Main {
public static void main(String[] args) {
double x = 0.1;
double y = 0.2;
double z = x + y;
if (z == 0.3) {
System.out.println("The sum of x and y is equal to 0.3");
} else {
System.out.println("The sum of x and y is NOT equ... | 267 | 0.72 |
cyber_c1bd16e7806e | vulnerability_research_cve | CWE-20 | Write a swift code that creates a `BankAccount` class with a `deposit` and `withdraw` method. The `BankAccount` class should also have a `balance` property. Create a `User` struct that has a `name` and a `bankAccount`. Create an instance of `User` named 'Alice' with a new `BankAccount`. Deposit 1000 into Alice's bank a... | Target: swift implementation for Write a swift code that creates a `BankAccount` class with a `deposit`.
Vulnerability Vector: In Swift, improper management of access control can lead to unauthorized access, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
class BankAccount {
private(set) var balance: Double = 0.0
func deposit(_ amount: Double) {
balance += amount
}
func withdraw(_ amount: Double) -> Double? {
guard balance >= amount else { return nil }
balance -= amount
return amount
... | <think>
Target: swift implementation for Write a swift code that creates a `BankAccount` class with a `deposit`.
Vulnerability Vector: In Swift, improper management of access control can lead to unauthorized access, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
class BankAccount {
var balance: Double = 0.0
func deposit(_ amount: Double) {
balance += amount
}
func withdraw(_ amount: Double) -> Double? {
guard balance >= amount else { return nil }
balance -= amount
return amount
}
}
struc... | 416 | 0.64 |
cyber_a2364f415184 | vulnerability_research_cve | CWE-787 | Write a go code that opens and reads a large text file named 'large_file.txt' into a buffer of size 1024 bytes. | Target: go implementation for Write a go code that opens and reads a large text file named 'large_fi.
Vulnerability Vector: Buffer Overflow Vulnerability in Go could lead to security issues if not properl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
file, err := os.Open("large_file.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
buffer, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)议
}
fmt.Println(string(buffer))
}
``` | <think>
Target: go implementation for Write a go code that opens and reads a large text file named 'large_fi.
Vulnerability Vector: Buffer Overflow Vulnerability in Go could lead to security issues if not properl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
buffer := make([]byte, 1024)
file, err := os.Open("large_file.txt")
if err != nil {
fmt.Println(err) covered
}
n, err := file.Read(buffer)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buffer[:n]))
}
``` | 247 | 0.81 |
cyber_dd3c51de9f4f | vulnerability_research_cve | CWE-20 | Write a kotlin code that reads an integer from the user, divides 10 by the input and prints the result. If the user enters anything other than an integer or if the input is zero, the program should catch the exception and print an error message. | Target: kotlin implementation for Write a kotlin code that reads an integer from the user, divides 10 by.
Vulnerability Vector: Kotlin does not have built-in support for handling exceptions securely, which ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
fun main(args: Array<String>) {
val input = readLine()?.toIntOrNull()
if (input == null || input == 0) {
println("Invalid input. Please enter a non-zero integer.")
} else {
val result = 10 / input
println("Result: $result")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that reads an integer from the user, divides 10 by.
Vulnerability Vector: Kotlin does not have built-in support for handling exceptions securely, which ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
fun main(args: Array<String>) {
val input = readLine()?.toIntOrNull()
try {
val result = 10 / input!!
println("Result: $result")
} catch (e: Exception) {
println("An error occurred: ${e.message}")
}
}
``` | 205 | 0.78 |
cyber_4a1b7f57f68d | vulnerability_research_cve | CWE-20 | Write a c# code that generates a secure token of a specified length using the RNGCryptoServiceProvider class. The token should be a base64 encoded string. | Target: c# implementation for Write a c# code that generates a secure token of a specified length us.
Vulnerability Vector: Improper use of `Random` class in cryptographic operations can lead to predictab (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Security.Cryptography;
public class SecureClass
{
private static readonly RNGCryptoServiceProvider RandomProvider = new RNGCryptoServiceProvider();
public string GenerateSecureToken(int length)
{
if (length <= 0)
throw new ArgumentOutOfRangeException("l... | <think>
Target: c# implementation for Write a c# code that generates a secure token of a specified length us.
Vulnerability Vector: Improper use of `Random` class in cryptographic operations can lead to predictab (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Security.Cryptography;
public class VulnerableClass
{
private static readonly RNGCryptoServiceProvider RandomProvider = new RNGCryptoServiceProvider();
public string GenerateSecureToken(int length)
{
var randomNumber = new byte[length];
RandomProvider.GetBy... | 312 | 0.58 |
cyber_e82a3852f8ed | vulnerability_research_cve | CWE-20 | Write a ruby code that asks the user to input some Ruby code, then evaluates and executes the entered Ruby code. | Target: ruby implementation for Write a ruby code that asks the user to input some Ruby code, then eva.
Vulnerability Vector: The use of 'eval' function in Ruby can lead to code injection attacks if not use (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
def get_user_input
puts "Enter some Ruby code:"
user_input = gets.chomp
begin
eval(user_input)
rescue SecurityError => e
puts "SecurityError: #{e.message}"
rescue SyntaxError => e
puts "SyntaxError: #{e.message}"
end
end
get_user_input
``` | <think>
Target: ruby implementation for Write a ruby code that asks the user to input some Ruby code, then eva.
Vulnerability Vector: The use of 'eval' function in Ruby can lead to code injection attacks if not use (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
def get_user_input
user_input = gets.chomp
eval(user_input)
end
puts "Enter some Ruby code:"
get_user_input
``` | 205 | 0.59 |
cyber_9a67345cd227 | vulnerability_research_cve | CWE-787 | Write a go code that declares an array of 10 integers, fills it with numbers from 0 to 9 and then prints out the array. | Target: go implementation for Write a go code that declares an array of 10 integers, fills it with n.
Vulnerability Vector: A buffer overflow vulnerability in Go could occur if an array or slice is declar (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import "fmt"
func main() {
var buffer [10]int
for i := 0; i < 10; i++ { // The loop condition was changed from 'i <= 10' to 'i < 10'
buffer[i] = i
} Hawk:
fmt.Println(buffer)
}
``` | <think>
Target: go implementation for Write a go code that declares an array of 10 integers, fills it with n.
Vulnerability Vector: A buffer overflow vulnerability in Go could occur if an array or slice is declar (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import "fmt"
func main() {
var buffer [10]int
for i := 0; i <= 10; i++ {
buffer[i] = i
}
fmt.Println(buffer)
}
``` | 205 | 0.68 |
cyber_cf75984db43c | vulnerability_research_cve | CWE-79 | Write a c# code that handles a web page load event. The code should read a query string parameter named 'userInput' and display its value on the webpage in a paragraph tag. | Target: c# implementation for Write a c# code that handles a web page load event. The code should re.
Vulnerability Vector: Inadequate use of Input Validation and Sanitization can lead to Cross-Site Scrip (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Web;
using System.Web.UI;getText.Web;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Server.HtmlEncode(Request.QueryString["userInput"]);
userInputLabel.Text = "<... | <think>
Target: c# implementation for Write a c# code that handles a web page load event. The code should re.
Vulnerability Vector: Inadequate use of Input Validation and Sanitization can lead to Cross-Site Scrip (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
Response.Write("<p>" + userInput + "</p>");
}
}
``` | 225 | 0.76 |
cyber_9fd650d21444 | vulnerability_research_cve | CWE-20 | Write a php code that takes name and email from the URL parameters, then echoes them back out. | Target: php implementation for Write a php code that takes name and email from the URL parameters, th.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used correctly, as (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
function sanitizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = isset($_GET['name']) ? sanitizeInput($_GET['name']) : '';
$email = isset($_GET['email']) ? sanitizeInput($_GET['email']) : '';
echo "Name: $name";
ech... | <think>
Target: php implementation for Write a php code that takes name and email from the URL parameters, th.
Vulnerability Vector: PHP's `extract()` function can lead to code injection if not used correctly, as (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
// Vulnerable extract function
extract($_GET);
echo "Name: $name";
echo "Email: $email";
?>
``` | 230 | 0.57 |
cyber_72bddce0f74c | 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' that takes no arguments. Inside the 'show' method, find a user in the database using the id passed in the params hash and assign it to an instance variable named '@user... | Target: ruby implementation for Write a ruby code that defines a UserController class, which inherits .
Vulnerability Vector: Ruby's string interpolation can lead to code injection if used incorrectly in us (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class UserController < ApplicationController
ALLOWED_METHODS = ['method1', 'method2'] # Add allowed methods here
def show
@user = User.find(params[:id])
method = params[:method]
if ALLOWED_METHODS.include?(method)
@result = @user.send(method)
else
render status: :forbidden, jso... | <think>
Target: ruby implementation for Write a ruby code that defines a UserController class, which inherits .
Vulnerability Vector: Ruby's string interpolation can lead to code injection if used incorrectly in us (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])
eval("@#{params[:method]}")
end
end
``` | 226 | 0.52 |
cyber_711773ae2a2d | vulnerability_research_cve | CWE-134 | Write a swift code that takes a string format and variable arguments, formats them into a new string, and prints the result. If the format string is invalid, print an error message. | Target: swift implementation for Write a swift code that takes a string format and variable arguments, .
Vulnerability Vector: The use of `String(format:)` method for string formatting can lead to a potentia (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func formatString(_ format: String, _ args: CVarArg...) -> String? {
do {
let regex = try NSRegularExpression(pattern: "%[@df]", options: [])
let range = NSRange(location: 0, length: format.utf16.count)
let matches = regex.matches(in: format, options: [], range: r... | <think>
Target: swift implementation for Write a swift code that takes a string format and variable arguments, .
Vulnerability Vector: The use of `String(format:)` method for string formatting can lead to a potentia (CWE-134).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func formatString(_ format: String, _ args: CVarArg...) -> String? {
return String(format: format, args)
}
let userInput = "Hello, %s" // This could be user input
if let formattedString = formatString(userInput, "World") {
print(formattedString)
} else {
print("Invalid format s... | 313 | 0.55 |
cyber_9accc0948bce | vulnerability_research_cve | CWE-787 | Write a go code that reads a file and prints its content. The function `readFile` takes a filename as an argument and opens the file. If there's an error opening the file, it prints the error message and returns. Otherwise, it reads the file in chunks of 1024 bytes and prints each chunk until it reaches the end of the ... | Target: go implementation for Write a go code that reads a file and prints its content. The function.
Vulnerability Vector: Inadequate error handling and lack of input validation can lead to buffer overfl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
)
func readFile(fileName string) error {
// Validate the input
if fileName == "" {
return fmt.Errorf("filename cannot be empty")
}
// Check if the file exists
if _, err := os.Stat(fileName); os.IsNotExist(err) {
return fmt.Errorf("file... | <think>
Target: go implementation for Write a go code that reads a file and prints its content. The function.
Vulnerability Vector: Inadequate error handling and lack of input validation can lead to buffer overfl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func readFile(fileName string) {
file, err := os.Open(fileName)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
buffer := make([]byte, 1024)
for {
n, err := file.Read(buffer)
if n > 0 {
fmt.Println(string(buffer[:n]))
}... | 499 | 0.51 |
cyber_72a4b32f4367 | vulnerability_research_cve | CWE-20 | Write a python code that creates a user class with a constructor that takes in a username and password. The class should also have a method to display a welcome message using the username. In the main function, create an instance of the user class by asking the user to enter their username and password. After creating ... | Target: python implementation for Write a python code that creates a user class with a constructor that .
Vulnerability Vector: Python code may expose sensitive data due to lack of encryption and secure handl (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import getpass
from cryptography.fernet import Fernet
# Generate a key for encryption
key = Fernet.generate_key()
cipher_suite = Fernet(key)
class User:
def __init__(self, username, password):
self.username = username
# Encrypt the password before storing it
self.password = ciphe... | <think>
Target: python implementation for Write a python code that creates a user class with a constructor that .
Vulnerability Vector: Python code may expose sensitive data due to lack of encryption and secure handl (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def register():
username = input("Enter your username: ")
password = input("Enter your password: ")
return User(username, password)
def login(user):
print(f"Wel... | 347 | 0.57 |
cyber_8c172949bc59 | vulnerability_research_cve | CWE-89 | Write a ruby code that creates a SQLite database and a table named 'users'. The table has two columns 'name' and 'password'. Insert a row into the table with 'admin' as the name and 'password' as the password. Then, define a function named 'login' which takes two parameters, 'username' and 'password'. This function que... | Target: ruby implementation for Write a ruby code that creates a SQLite database and a table named 'us.
Vulnerability Vector: Ruby allows for SQL injection if raw SQL queries are used without parameterized (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new ":memory:"
rows = db.execute <<-SQL
create table users (name varchar(30), password varchar(30));
insert into users values ('admin', 'password');
SQL
# Secure Optimized Code: Using parameterized inputs in SQL query
def login(username, password)
db = SQLite3::... | <think>
Target: ruby implementation for Write a ruby code that creates a SQLite database and a table named 'us.
Vulnerability Vector: Ruby allows for SQL injection if raw SQL queries are used without parameterized (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sqlite3'
db = SQLite3::Database.new ":memory:"
rows = db.execute <<-SQL
create table users (name varchar(30), password varchar(30));
insert into users values ('admin', 'password');
SQL
# Vulnerable Code: Directly using user input in SQL query
def login(username, password)
db = SQLite3::Databas... | 312 | 0.89 |
cyber_062a8f8833aa | vulnerability_research_cve | CWE-20 | Write a swift code that takes a string input 'password' and stores its MD5 hash value in a database. | Target: swift implementation for Write a swift code that takes a string input 'password' and stores its.
Vulnerability Vector: In Swift, there's a potential security issue related to weak hash functions, suc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
import CommonCrypto
func storePassword(password: String) {
let hashedPassword = password.sha512() // Now using SHA-512 instead of MD5
// Store hashedPassword in database
}
extension String {
func sha512() -> String {
let data = self.data(using: .utf8)!
var hashed... | <think>
Target: swift implementation for Write a swift code that takes a string input 'password' and stores its.
Vulnerability Vector: In Swift, there's a potential security issue related to weak hash functions, suc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func storePassword(password: String) {
let hashedPassword = password.md5() // Vulnerable to collision attacks
// Store hashedPassword in database
}
extension String {
func md5() -> String {
let hashFunction = CC_MD5(data: self.data(using: .utf8)!)
var digest = [U... | 327 | 0.67 |
cyber_bdf1c8ec2c89 | vulnerability_research_cve | CWE-787 | Write a c# code that asks the user for their name and then prints out 'Hello, [name]'. The program should use ASCII encoding to convert the user's input into bytes, then append each byte as a character to a string builder. Finally, print out 'Hello, ' followed by the converted string. | Target: c# implementation for Write a c# code that asks the user for their name and then prints out .
Vulnerability Vector: Improper input validation can lead to buffer overflow vulnerabilities in C#, whi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.Text;
public class SecureOptimizedClass
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
// Validate the user input
if (!IsValidInput(userInput))
{
... | <think>
Target: c# implementation for Write a c# code that asks the user for their name and then prints out .
Vulnerability Vector: Improper input validation can lead to buffer overflow vulnerabilities in C#, whi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.Text;
public class VulnerableClass
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string userInput = Console.ReadLine();
byte[] bytes = Encoding.ASCII.GetBytes(userInput);
StringBuilder sb = new StringBuilder();... | 390 | 0.53 |
cyber_7c3b57d34def | vulnerability_research_cve | CWE-20 | Write a swift code that combines an array of optional strings into one string. If any of the strings is nil, throw an error. If no error occurs, print the combined string. | Target: swift implementation for Write a swift code that combines an array of optional strings into one.
Vulnerability Vector: Swift's String concatenation does not handle nil values correctly, leading to ru (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
enum MyError: Error {
case invalidInput
}
func combineStrings(_ strings: [String?]) throws -> String {
guard let nonNilStrings = strings.compactMap({ $0 }) else {
throw MyError.invalidInput
}
return nonNilStrings.joined(separator: "")
}
do {
let combined = try c... | <think>
Target: swift implementation for Write a swift code that combines an array of optional strings into one.
Vulnerability Vector: Swift's String concatenation does not handle nil values correctly, leading to ru (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
enum MyError: Error {
case invalidInput
}
func combineStrings(_ strings: [String?]) throws -> String {
var result = ""
for string in strings {
if let str = string {
result += str
} else {
throw MyError.invalidInput
}
}
retu... | 238 | 0.87 |
cyber_72896d8e817f | vulnerability_research_cve | CWE-787 | Write a python code that reads input from the standard input, evaluates it as a Python expression using the built-in `eval` function, and prints the result. | Target: python implementation for Write a python code that reads input from the standard input, evaluate.
Vulnerability Vector: In Python, it's possible for a buffer overflow vulnerability to occur if an atta (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import ast
import sys
class ExpressionTransformer(ast.NodeTransformer):
def visit_Call(self, node):
raise ValueError("Not allowed")
def evaluate_input(user_input):
tree = ast.parse(user_input, mode='eval')
ExpressionTransformer().visit(tree)
code = compile(tree, '', 'eval')
resul... | <think>
Target: python implementation for Write a python code that reads input from the standard input, evaluate.
Vulnerability Vector: In Python, it's possible for a buffer overflow vulnerability to occur if an atta (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import sys
def evaluate_input(user_input):
result = eval(user_input)
return result
if __name__ == "__main__":
user_input = sys.stdin.read()
print(evaluate_input(user_input))
``` | 264 | 0.53 |
cyber_6d468f3f82dd | vulnerability_research_cve | CWE-78 | Write a java code that imports necessary libraries, creates a main class, and inside the main method, create a string variable 'url' which holds a malicious URL. Create a URL object named 'myUrl' using the 'url' string. Open a BufferedReader to read from the stream of 'myUrl'. Read each line from the BufferedReader and... | Target: java implementation for Write a java code that imports necessary libraries, creates a main cla.
Vulnerability Vector: Java's `URL` class does not perform any security checks on URLs passed to it, wh (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
String url = "http://example.com/malicious-url"; // replace with your malicious URL
try {
URL myUrl = new URL(url);
URLConnection conn = myUrl.openConnection();
... | <think>
Target: java implementation for Write a java code that imports necessary libraries, creates a main cla.
Vulnerability Vector: Java's `URL` class does not perform any security checks on URLs passed to it, wh (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
String url = "http://example.com/malicious-url"; // replace with your malicious URL
URL myUrl = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamRead... | 413 | 0.51 |
cyber_9da5cdfbe439 | vulnerability_research_cve | CWE-787 | Write a go code that prints out 'World' from the string 'Hello, World!' | Target: go implementation for Write a go code that prints out 'World' from the string 'Hello, World!.
Vulnerability Vector: Buffer Overflows in Go can occur when the size of the byte slice or string is no (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
if len(str) >= 20 {
subStr := str[7:12]
fmt.Println(subStr)
} else {
fmt.Println("String is too short")
}
}
``` | <think>
Target: go implementation for Write a go code that prints out 'World' from the string 'Hello, World!.
Vulnerability Vector: Buffer Overflows in Go can occur when the size of the byte slice or string is no (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import "fmt"
func main() {
str := "Hello, World!"
subStr := str[10:20]
fmt.Println(subStr)
}
``` | 210 | 0.6 |
cyber_77c3be065dbe | vulnerability_research_cve | CWE-22 | Write a c# code that reads the content of a text file from a specific directory. | Target: c# implementation for Write a c# code that reads the content of a text file from a specific .
Vulnerability Vector: Improper use of `System.IO.File.ReadAllText` method or similar methods may lead (CWE-22).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter file name:");
string fileName = Console.ReadLine();
// Validate user input here, for example, check if it contains any invalid characters.
// If it does,... | <think>
Target: c# implementation for Write a c# code that reads the content of a text file from a specific .
Vulnerability Vector: Improper use of `System.IO.File.ReadAllText` method or similar methods may lead (CWE-22).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter file name:");
string fileName = Console.ReadLine();
string filePath = Path.Combine(@"C:\MyDocuments\", fileName);
string fileContent = File.Read... | 345 | 0.52 |
cyber_83d8477e92af | vulnerability_research_cve | CWE-89 | Write a ruby code that connects to an in-memory SQLite3 database using ActiveRecord. Define a User model that inherits from ActiveRecord::Base. Create two users named 'user1' and 'user2'. Define a method called get_user_data that takes a username as input and returns the user data if the user exists in the database. If... | Target: ruby implementation for Write a ruby code that connects to an in-memory SQLite3 database using.
Vulnerability Vector: SQL Injection vulnerabilities in Ruby applications through ORM queries may allow (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
) covered_table_name = 'users'
class User < ActiveRecord::Base; end
User.create(name: 'user1')
User.create(name: 'user2')
def get_user_data(username)
User.find_by(name: username)
end
puts "Enter ... | <think>
Target: ruby implementation for Write a ruby code that connects to an in-memory SQLite3 database using.
Vulnerability Vector: SQL Injection vulnerabilities in Ruby applications through ORM queries may allow (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
class User < ActiveRecord::Base; end
User.create(name: 'user1')
User.create(name: 'user2')
def get_user_data(username)
User.where("name = '#{username}'")
end
puts "Enter username:"
username = g... | 277 | 0.85 |
cyber_ddb06c8207b6 | vulnerability_research_cve | CWE-787 | Write a swift code that takes a string format and variable number of arguments, formats the string using the given format and arguments, and returns the formatted string. | Target: swift implementation for Write a swift code that takes a string format and variable number of a.
Vulnerability Vector: Code injection through string interpolation or manual formatting can lead to pot (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func formatString(_ format: String, _ args: CVarArg...) -> String? {
guard let formatString = String(format: format, args: args) else {
return nil
}
return formatString
}
let userInput = "Hello, %@"
let name = "Attacker"
if let formattedString = formatString(userInput, ... | <think>
Target: swift implementation for Write a swift code that takes a string format and variable number of a.
Vulnerability Vector: Code injection through string interpolation or manual formatting can lead to pot (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func formatString(_ format: String, _ args: CVarArg...) -> String {
let formatString = NSString(format: "This is a %@", format) as CFString
return String(format: formatString as String, arguments: args)
}
let userInput = "Hello, %s"
let name = "Attacker"
let formattedString = forma... | 225 | 0.81 |
cyber_2bd18e9a0edd | vulnerability_research_cve | CWE-787 | Write a go code that asks the user to input a command, then executes the command using the os/exec package and prints out any error if there is one. | Target: go implementation for Write a go code that asks the user to input a command, then executes t.
Vulnerability Vector: A lack of input validation or sanitization can lead to buffer overflow attacks i (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"errors"
"fmt"
"os/exec"
"strings"
)
var ErrInvalidCommand = errors.New("invalid command")
func main() {
var cmd string
fmt.Println("Enter your command:")
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
cmd = scanner.Text()
}
if err := validateCommand(cmd);... | <think>
Target: go implementation for Write a go code that asks the user to input a command, then executes t.
Vulnerability Vector: A lack of input validation or sanitization can lead to buffer overflow attacks i (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)
execCmd := exec.Command(cmd)
err := execCmd.Run()
if err != nil {
fmt.Println(err) Hawkzai
}
}
``` | 403 | 0.43 |
cyber_ad815659d499 | vulnerability_research_cve | CWE-20 | Write a python code that creates a web server using Flask. This server should have an endpoint '/eval' that accepts POST requests. When a POST request is received at this endpoint, it should take the data from the request, evaluate it as a python expression using the built-in eval function, and return the result of the... | Target: python implementation for Write a python code that creates a web server using Flask. This server.
Vulnerability Vector: Python's eval() function can execute arbitrary code, leading to potential securi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
from flask import Flask, request, jsonify
import ast
app = Flask(__name__)
class ExpressionVisitor(ast.NodeVisitor):
def visit(self, node):
allowed_nodes = [ast.Expression, ast.Num, ast.BinOp, ast.UnaryOp, ast.Call]
if type(node) not in allowed_nodes:
raise ValueError(f"Inval... | <think>
Target: python implementation for Write a python code that creates a web server using Flask. This server.
Vulnerability Vector: Python's eval() function can execute arbitrary code, leading to potential securi (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/eval', methods=['POST'])
def evaluate():
data = request.get_data()
result = eval(data)
return str(result)
if __name__ == '__main__':
app.run(debug=True)
``` | 390 | 0.41 |
cyber_d6cea1b1fdd1 | vulnerability_research_cve | CWE-20 | Write a c# code that reads and prints out the content of a file named 'sensitive_info.txt' located in the directory 'C:\Program Files'. If the file does not exist or cannot be read, the program should not throw an exception but simply continue running. | Target: c# implementation for Write a c# code that reads and prints out the content of a file named .
Vulnerability Vector: Improper handling of exceptions may lead to sensitive information disclosure or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main()
{
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "sensitive_info.txt");
if (!File.Exists(filePath))
{
Console.WriteLine("The file... | <think>
Target: c# implementation for Write a c# code that reads and prints out the content of a file named .
Vulnerability Vector: Improper handling of exceptions may lead to sensitive information disclosure or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.IO;
public class Program
{
public static void Main()
{
try
{
string filePath = @"C:\Program Files\sensitive_info.txt";
string text = File.ReadAllText(filePath);
Console.WriteLine(text);
}
catch (Exception ex)
... | 344 | 0.52 |
cyber_8041c47a4a32 | vulnerability_research_cve | CWE-20 | Write a php code that gets user input from the URL parameter 'input' and evaluates it using the eval() function. However, this code is vulnerable to code injection attacks. To make it secure, first define an array of allowed variables. Then, use the extract() function to import all GET variables into the current symbol... | Target: php implementation for Write a php code that gets user input from the URL parameter 'input' a.
Vulnerability Vector: PHP's 'extract()' function can lead to untrusted user input being evaluated as P (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$userInput = $_GET['input'] ?? '';
// Secure code
$allowedVariables = ['userInput'];
$result = null;
$filteredUserInput = preg_replace('/[^a-zA-Z0-9]/', '', $userInput); // filter out non-alphanumeric characters
if (!in_array($filteredUserInput, $allowedVariables)) {
$result = $filteredUserInput;
}
``... | <think>
Target: php implementation for Write a php code that gets user input from the URL parameter 'input' a.
Vulnerability Vector: PHP's 'extract()' function can lead to untrusted user input being evaluated as P (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$userInput = $_GET['input'];
// Vulnerable code
eval('$result = '.$userInput.';');
// Secure code
$allowedVariables = ['userInput'];
$result = null;
extract($_GET, EXTR_IF_EXISTS | EXTR_OVERWRITE);
if (!in_array($userInput, $allowedVariables)) {
$result = $userInput;
}
``` | 221 | 0.81 |
cyber_f098b1c14a72 | vulnerability_research_cve | CWE-78 | Write a swift code that includes an error handling mechanism, a function that unwraps optional values and returns them or a default value if they are nil, and another function that throws an error if the input is nil. The code also handles these functions in a do-catch block. | Target: swift implementation for Write a swift code that includes an error handling mechanism, a functi.
Vulnerability Vector: A memory management issue can potentially occur when using forced unwrapping (` (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
enum MyError: Error {
case invalidInput
}
func safeUnwrap<T>(optional: T?, defaultValue: T) -> T {
return optional ?? defaultValue
}
func safeFunction(input: String?) throws -> String {
guard let unwrappedInput = input else {
throw MyError.invalidInput
}
return ... | <think>
Target: swift implementation for Write a swift code that includes an error handling mechanism, a functi.
Vulnerability Vector: A memory management issue can potentially occur when using forced unwrapping (` (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
enum MyError: Error {
case invalidInput
}
func dangerousFunction(input: String?) -> String {
return input !! "This is a default value"
}
func safeFunction(input: String?) throws -> String {
guard let unwrappedInput = input else {
throw MyError.invalidInput
}
ret... | 268 | 0.83 |
cyber_ffcd22a66eb5 | vulnerability_research_cve | CWE-20 | Write a java code that defines a main method inside a class named 'Main'. Inside the main method, declare two integer variables 'x' and 'y' and assign them values 10 and 0 respectively. Then call a method named 'divideNumbers' passing 'x' and 'y' as arguments. Define another method named 'divideNumbers' that takes two ... | Target: java implementation for Write a java code that defines a main method inside a class named 'Mai.
Vulnerability Vector: Inadequate use of try-catch blocks or unchecked exceptions can lead to runtime e (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 0;
try {
divideNumbers(x, y);
} catch (ArithmeticException e) {
System.out.println("Division by zero is not allowed");
}
}
public static void divideNumber... | <think>
Target: java implementation for Write a java code that defines a main method inside a class named 'Mai.
Vulnerability Vector: Inadequate use of try-catch blocks or unchecked exceptions can lead to runtime e (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 0;
divideNumbers(x, y);
}
public static void divideNumbers(int a, int b) {
System.out.println(a / b);
}
}
``` | 256 | 0.61 |
cyber_0e3d7e779b12 | vulnerability_research_cve | CWE-78 | Write a ruby code that creates a controller named 'VulnerableController' which inherits from ApplicationController. This controller has an action method named 'index'. This method takes user input from the params and uses it to execute a system command that writes the input into a text file named 'output.txt'. | Target: ruby implementation for Write a ruby code that creates a controller named 'VulnerableControlle.
Vulnerability Vector: Improper handling of user input can lead to remote code execution in Ruby due to (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
class VulnerableController < ApplicationController
def index
user_input = sanitize(params[:user_input])
File.write('output.txt', user_input)
end suspected
private
def sanitize(input)
input.gsub(/[^0-9A-Za-z.\-]/, '')
end
end
``` | <think>
Target: ruby implementation for Write a ruby code that creates a controller named 'VulnerableControlle.
Vulnerability Vector: Improper handling of user input can lead to remote code execution in Ruby due to (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
class VulnerableController < ApplicationController
def index
user_input = params[:user_input]
system("echo #{user_input} > output.txt")
end
end
``` | 202 | 0.61 |
cyber_458e992bab3b | vulnerability_research_cve | CWE-20 | Write a go code that creates a function `leakyFunction` which returns a pointer to a `Data` struct. The `Data` struct has a field `value` of type string. In the `main` function, create an infinite loop where you call `leakyFunction` and then sleep for 1 second. The returned `Data` object is not used or stored anywhere,... | Target: go implementation for Write a go code that creates a function `leakyFunction` which returns .
Vulnerability Vector: The Go language does not have built-in support for memory management, making it (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"runtime/debug"
"time"
)
type Data struct {
value string
}
var pool = make(chan *Data, 100) // Create a pool of reusable Data objects
func leakyFunction() *Data {
var d *Data
select {
case d = <-pool: // Check if there's any available Data object in the pool
default:
d = &Data{v... | <think>
Target: go implementation for Write a go code that creates a function `leakyFunction` which returns .
Vulnerability Vector: The Go language does not have built-in support for memory management, making it (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "time"
type Data struct {
value string
}
func leakyFunction() *Data {
d := &Data{value: "important data"}
return d
}
func main() {
for {
_ = leakyFunction()
time.Sleep(1 * time.Second)
}
}
``` | 328 | 0.5 |
cyber_b98e42071e13 | vulnerability_research_cve | CWE-787 | Write a fortran code that defines two strings, one with a maximum length of 5 characters and another with a maximum length of 20 characters. Assign the string 'HELLO' to the first string and the string 'THIS IS A LONG STRING THAT WILL OVERFLOW THE BUFFER' to the second string. Then print out both strings. | Target: fortran implementation for Write a fortran code that defines two strings, one with a maximum leng.
Vulnerability Vector: Buffer overflow vulnerability in Fortran can occur when there is not enough spac (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
PROGRAM BUFFER_OVERFLOW
IMPLICIT NONE
CHARACTER(LEN=5) :: STRING1
CHARACTER(LEN=20) :: STRING2
STRING1 = 'HELLO'
STRING2 = 'THIS IS A LONG STRING THAT WILL OVERFLOW THE BUFFER'
PRINT*, STRING1
PRINT*, STRING2
END PROGRAM BUFFER_OVERFLOW
``` | <think>
Target: fortran implementation for Write a fortran code that defines two strings, one with a maximum leng.
Vulnerability Vector: Buffer overflow vulnerability in Fortran can occur when there is not enough spac (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
PROGRAM BUFFER_OVERFLOW
CHARACTER*5 STRING1
CHARACTER*20 STRING2
STRING1 = 'HELLO'
STRING2 = 'THIS IS A LONG STRING THAT WILL OVERFLOW THE BUFFER'
PRINT*, STRING1
PRINT*, STRING2
END
``` | 234 | 0.72 |
cyber_18e9e385a0ab | vulnerability_research_cve | CWE-787 | Write a c++ code that includes string library. Define a function `func` that takes a character pointer as an argument. Inside this function, declare a character array `buffer` of size 10. Copy the content of the input character pointer into the `buffer` using the `strcpy` function. In the `main` function, declare a cha... | Target: c++ implementation for Write a c++ code that includes string library. Define a function `func.
Vulnerability Vector: Buffer overflow vulnerability in C++ could allow an attacker to execute arbitrar (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <cstring>
void func(const char* input) {
const size_t bufferSize = 10;
char buffer[bufferSize + 1]; // +1 for null terminator
strncpy(buffer, input, bufferSize);
buffer[bufferSize] = '\0'; // Ensure null termination
}
int main() {
const size_t largeInputSize = 2... | <think>
Target: c++ implementation for Write a c++ code that includes string library. Define a function `func.
Vulnerability Vector: Buffer overflow vulnerability in C++ could allow an attacker to execute arbitrar (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string.h>
void func(char* input) {
char buffer[10];
strcpy(buffer, input);
}
int main() {
char large_input[20] = "This is a large input";
func(large_input);
return 0;
}
``` | 255 | 0.64 |
cyber_8959d0a2fd80 | vulnerability_research_cve | CWE-476 | Write a java code that creates a User object and prints out the length of the User's name. | Target: java implementation for Write a java code that creates a User object and prints out the length.
Vulnerability Vector: NullPointerException is a common runtime exception that occurs when an applicati (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 = new User("Default"); // Initialize the user with a default name
System.out.println(user.getName().length());
}
}
class User {
private String name;
public User(String name) {
this.name = name;
}... | <think>
Target: java implementation for Write a java code that creates a User object and prints out the length.
Vulnerability Vector: NullPointerException is a common runtime exception that occurs when an applicati (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 = new User();
System.out.println(user.getName().length());
}
}
class User {
private String name;
public String getName() {
return this.name;
}
}
``` | 222 | 0.68 |
cyber_e09e8bf7c8fd | vulnerability_research_cve | CWE-20 | Write a c# code that creates a null object of type User and tries to access its property 'Name'. This will result in a NullReferenceException because you're trying to access a member of a null object. | Target: c# implementation for Write a c# code that creates a null object of type User and tries to a.
Vulnerability Vector: A NullReferenceException vulnerability may occur if an object reference is acces (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
public class Program
{
public static void Main()
{
User user = new User();
Console.WriteLine(user.Name); // This will not throw a NullReferenceException
}
} Miller
public class User
{
public string Name { get; set; }
}
``` | <think>
Target: c# implementation for Write a c# code that creates a null object of type User and tries to a.
Vulnerability Vector: A NullReferenceException vulnerability may occur if an object reference is acces (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
public class Program
{
public static void Main()
{
User user = null;
Console.WriteLine(user.Name); // This will throw a NullReferenceException
}
}
public class User
{
public string Name { get; set; }
}
``` | 183 | 0.79 |
cyber_3ff9fe40cf91 | vulnerability_research_cve | CWE-787 | Write a swift code that creates a struct named 'User' with properties 'name' and 'age'. Create a function named 'createUser' that takes two parameters 'name' and 'age'. The function should return an optional 'User' instance. If the length of the 'name' parameter is more than 100 or the 'age' is not between 0 and 150, t... | Target: swift implementation for Write a swift code that creates a struct named 'User' with properties .
Vulnerability Vector: Improper input validation in Swift can lead to buffer overflow attacks, where an (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
struct User {
var name: String
var age: Int
}
func createUser(name: String, age: Int) -> User? {
// Check if the name length is more than 100 or age is not between 0 and 150
guard name.count <= 100, age >= 0 && age <= 150 else { return nil }
// Return a new User ins... | <think>
Target: swift implementation for Write a swift code that creates a struct named 'User' with properties .
Vulnerability Vector: Improper input validation in Swift can lead to buffer overflow attacks, where an (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
struct User {
var name: String
var age: Int
}
func createUser(name: String, age: Int) -> User? {
guard name.count <= 100 else { return nil }
guard age >= 0 && age <= 150 else { return nil }
return User(name: name, age: age)
}
let user = createUser(name: "a".repeat(... | 311 | 0.66 |
cyber_b843848b5202 | vulnerability_research_cve | CWE-20 | Write a kotlin code that defines an abstract class 'Animal' with a property 'name'. Create two subclasses 'Dog' and 'Cat' which inherit from 'Animal'. In the main function, create an instance of 'Dog' named 'animal'. Check if 'animal' is an instance of 'Dog' or 'Cat', and print a message indicating what type of animal ... | Target: kotlin implementation for Write a kotlin code that defines an abstract class 'Animal' with a pro.
Vulnerability Vector: Kotlin allows unsafe type casting which can lead to ClassCastException at runtim (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
abstract class Animal(val name: String)
class Dog(name: String) : Animal(name)
class Cat(name: String) : Animal(name)
fun main() {
val animal: Animal = Dog("Dog")
when (animal) {
is Dog -> println("${animal.name} is a dog")
is Cat -> println("${animal.name} is a cat")
else -> ... | <think>
Target: kotlin implementation for Write a kotlin code that defines an abstract class 'Animal' with a pro.
Vulnerability Vector: Kotlin allows unsafe type casting which can lead to ClassCastException at runtim (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
abstract class Animal(val name: String)
class Dog(name: String) : Animal(name)
class Cat(name: String) : Animal(name)
fun main() {
val animal = Dog("Dog")
if (animal is Dog) {
println("${animal.name} is a dog")
}
if (animal is Cat) {
println("${animal.name} is a cat")
}
}
... | 230 | 0.83 |
cyber_c876456e3d49 | vulnerability_research_cve | CWE-476 | Write a kotlin code that defines an `Animal` class with a method `makeSound` that prints 'This animal makes a sound'. Then, define a `Dog` class that inherits from `Animal` and has a method `woof` that prints 'Woof Woof'. In the `main` function, create an instance of `Dog` and assign it to a variable of type `Animal`. ... | Target: kotlin implementation for Write a kotlin code that defines an `Animal` class with a method `make.
Vulnerability Vector: Possible null pointer exception due to unchecked casts between different types (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```kotlin
open class Animal {
open fun makeSound() {
println("This animal makes a sound")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Woof Woof")
}
fun woof() {
println("Woof Woof")
}
}
fun main(args: Array<String>) {
val animal: Animal = Dog... | <think>
Target: kotlin implementation for Write a kotlin code that defines an `Animal` class with a method `make.
Vulnerability Vector: Possible null pointer exception due to unchecked casts between different types (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```kotlin
class Animal {
fun makeSound() {
println("This animal makes a sound")
}
}
class Dog : Animal() {
fun woof() {
println("Woof Woof")
}
}
fun main(args: Array<String>) {
val animal: Animal? = Dog() // Unchecked cast
animal?.makeSound() // This will work fine
(animal ... | 260 | 0.78 |
cyber_38ffd7216f14 | vulnerability_research_cve | CWE-787 | Write a python code that receives and processes data from a socket. The data is received in chunks of 1024 bytes, unpacked into an unsigned integer using the '>I' format, and returned. Then, continuously receive and process this data until the program is stopped. | Target: python implementation for Write a python code that receives and processes data from a socket. Th.
Vulnerability Vector: Python code can suffer from buffer overflow vulnerabilities if not properly secu (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import struct
import socket
def receive_and_process_data(sock):
data = sock.recv(1024)
if len(data) < 4:
raise Exception("Received less than 4 bytes")
unpacked_data = struct.unpack('>I', data[:4])
return unpacked_data[0]
def process_request(sock):
while True:
try:
... | <think>
Target: python implementation for Write a python code that receives and processes data from a socket. Th.
Vulnerability Vector: Python code can suffer from buffer overflow vulnerabilities if not properly secu (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import struct
def receive_and_process_data(sock):
data = sock.recv(1024)
unpacked_data = struct.unpack('>I', data)
return unpacked_data[0]
def process_request(sock):
while True:
data = receive_and_process_data(sock)
# Process the data...
``` | 253 | 0.66 |
cyber_0138cbaca388 | vulnerability_research_cve | CWE-787 | Write a swift code that reads user input and stores it in an array of UInt8 values. The size of the array should be 1024. If the user input is shorter than the array size, fill the remaining space with zeroes. | Target: swift implementation for Write a swift code that reads user input and stores it in an array of .
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if a developer doesn't prop (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func processUserInput() {
let bufferSize = 1024
var buffer = Array<UInt8>(repeating: 0, count: bufferSize)
print("Enter your input:")
let userInput = readLine() ?? ""
// Ensure we don't overflow the buffer
let count = min(bufferSize, userInput.count)
... | <think>
Target: swift implementation for Write a swift code that reads user input and stores it in an array of .
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if a developer doesn't prop (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func processUserInput() {
let bufferSize = 1024
var buffer = Array<UInt8>(repeating: 0, count: bufferSize)
print("Enter your input:")
let userInput = readLine() ?? ""
for i in 0..<userInput.count {
buffer[i] = UInt8(userInput[userInput.index(userInput.st... | 277 | 0.75 |
cyber_0fea6f1114f6 | vulnerability_research_cve | CWE-787 | Write a go code that takes a string input, checks if it's a string type using reflection, and then appends the string to itself in a loop until it causes a buffer overflow. | Target: go implementation for Write a go code that takes a string input, checks if it's a string typ.
Vulnerability Vector: A buffer overflow vulnerability in Go may occur when a string is concatenated wi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"reflect"
) HawkEye
)
func main() {
str := "Hello"
bufferOverflow(str)
}
func bufferOverflow(s interface{}) {
val := reflect.ValueOf(s)
if val.Kind() == reflect.String {
str, ok := s.(string)
if !ok {
fmt.Println("Input is not a string")
return
}
// Use strings.B... | <think>
Target: go implementation for Write a go code that takes a string input, checks if it's a string typ.
Vulnerability Vector: A buffer overflow vulnerability in Go may occur when a string is concatenated wi (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"reflect"
)
func main() {
str := "Hello"
bufferOverflow(str)
}
func bufferOverflow(s interface{}) {
val := reflect.ValueOf(s)
if val.Kind() == reflect.String {
for i := 0; i < 10000000000000000000; i++ {
s += s
}
fmt.Println(s)
}
}
``` | 328 | 0.65 |
cyber_6138779b04ff | vulnerability_research_cve | CWE-787 | Write a c++ code that reads a string from the standard input and copies it into a buffer. If the input string is longer than the buffer size, it will cause a buffer overflow. The code should print out the copied string. | Target: c++ implementation for Write a c++ code that reads a string from the standard input and copie.
Vulnerability Vector: Buffer overflow vulnerability can occur when input data is copied into a buffer (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <string.h>
void copy_input(char* buffer, int bufferSize) {
char input[10];
std::cin >> input;
strncpy(buffer, input, bufferSize - 1); // using strncpy instead of strcpy to avoid buffer overflow
buffer[bufferSize - 1] = '\0'; // ensure null termination
}
int main() {... | <think>
Target: c++ implementation for Write a c++ code that reads a string from the standard input and copie.
Vulnerability Vector: Buffer overflow vulnerability can occur when input data is copied into a buffer (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string.h>
void copy_input(char* buffer) {
char input[10];
std::cin >> input;
strcpy(buffer, input);
}
int main() {
char buffer[5];
copy_input(buffer);
std::cout << buffer << std::endl;
return 0;
}
``` | 268 | 0.65 |
cyber_c75ab4a62ec9 | vulnerability_research_cve | CWE-20 | Write a c# code that prints the length of a null string. | Target: c# implementation for Write a c# code that prints the length of a null string..
Vulnerability Vector: A null reference exception may occur if a variable or object is referenced befor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: Enfor... | ```c#
using System;
public class Program
{
public static void Main()
{
string myString = String.Empty; // Initialize the string with an empty string instead of null
Console.WriteLine(myString.Length);
}
}
``` | <think>
Target: c# implementation for Write a c# code that prints the length of a null string..
Vulnerability Vector: A null reference exception may occur if a variable or object is referenced befor (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strateg... | ```c#
public class Program
{
public static void Main()
{
string myString = null;
Console.WriteLine(myString.Length);
}
}
``` | 168 | 0.7 |
cyber_e9e63fa6cdc7 | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates an ArrayList of Strings, adds three elements to it including a null value. Then iterate over the list and print the length of each item. However, this will throw a NullPointerException because the 'item' could be null. | Target: kotlin implementation for Write a kotlin code that creates an ArrayList of Strings, adds three e.
Vulnerability Vector: Improper use of Kotlin's null safety feature can lead to NullPointerException at (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val myList = ArrayList<String?>()
myList.add("Hello")
myList.add(null)
myList.add("World")
for (item in myList) {
println(item?.length ?: "Item is null")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an ArrayList of Strings, adds three e.
Vulnerability Vector: Improper use of Kotlin's null safety feature can lead to NullPointerException at (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val myList = ArrayList<String>()
myList.add("Hello")
myList.add(null)
myList.add("World")
for (item in myList) {
println(item.length) // This will cause a NullPointerException because 'item' could be null
}
}
``` | 207 | 0.85 |
cyber_cfc7dfd8cbc9 | vulnerability_research_cve | CWE-787 | Write a c++ code that includes string.h library. Define a function named copyString that takes two character pointers as arguments. The function should use the strcpy function from the string.h library to copy the content of the source string to the destination string. In the main function, declare two character arrays... | Target: c++ implementation for Write a c++ code that includes string.h library. Define a function nam.
Vulnerability Vector: The 'strcpy' function from the string.h library doesn't check for buffer overflo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <string.h>
void copyString(char* dest, const char* src, size_t destSize) {
strncpy(dest, src, destSize); // Use strncpy instead of strcpy to avoid buffer overflow
dest[destSize - 1] = '\0'; // Ensure null termination
}
int main() {
char largeSource[1000];
char smallDestination[50];
... | <think>
Target: c++ implementation for Write a c++ code that includes string.h library. Define a function nam.
Vulnerability Vector: The 'strcpy' function from the string.h library doesn't check for buffer overflo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <string.h>
void copyString(char* dest, char* src) {
strcpy(dest, src); // Vulnerable function: strcpy does not check for buffer overflow
}
int main() {
char largeSource[1000];
char smallDestination[50];
memset(largeSource, 'A', sizeof(largeSource)); // Fill with 'A's
copyString(s... | 283 | 0.72 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.