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_ce2eeae25973 | vulnerability_research_cve | CWE-787 | Write a swift code that defines an unsafe function that allocates memory for an array of 10 integers and initializes them to zero. Then access the 11th element of the array which is out of bounds. | Target: swift implementation for Write a swift code that defines an unsafe function that allocates memo.
Vulnerability Vector: In Swift, there's a potential buffer overflow vulnerability when dealing with Un (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func safeFunction() -> UnsafeMutableRawBufferPointer? {
let count = 10
let stride = MemoryLayout<Int8>.stride
guard let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: count * stride, alignment: stride) else {
return nil
}
buffer.initialize(to: 0, as: I... | <think>
Target: swift implementation for Write a swift code that defines an unsafe function that allocates memo.
Vulnerability Vector: In Swift, there's a potential buffer overflow vulnerability when dealing with Un (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func unsafeFunction() -> UnsafeMutableRawBufferPointer {
let count = 10
let stride = MemoryLayout<Int8>.stride
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: count * stride, alignment: stride)
buffer.initialize(to: 0, as: Int8.self)
return buffer
}
let bu... | 275 | 0.7 |
cyber_3ef7cc413eda | vulnerability_research_cve | CWE-918 | Write a go code that sends an HTTP GET request to 'http://example.com/' and prints out the response body. If there is any error during the process, print out the error message. | Target: go implementation for Write a go code that sends an HTTP GET request to 'http://example.com/.
Vulnerability Vector: The use of unverified data in HTTP requests can lead to server-side request forg (CWE-918).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
url := "http://example.com/"
// Create a new http client with a timeout
client := &http.Client{
Timeout: 30 * time.Second,
}
// Create a new http request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Pr... | <think>
Target: go implementation for Write a go code that sends an HTTP GET request to 'http://example.com/.
Vulnerability Vector: The use of unverified data in HTTP requests can lead to server-side request forg (CWE-918).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"io/ioutil"
"net/http"
"fmt"
)
func main() {
url := "http://example.com/"
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading... | 415 | 0.56 |
cyber_0a0cfb0a3fcd | vulnerability_research_cve | CWE-190 | Write a go code that prints the maximum value of an unsigned 8-bit integer and then adds 10 to it. Print the result. | Target: go implementation for Write a go code that prints the maximum value of an unsigned 8-bit int.
Vulnerability Vector: In Go, an integer overflow can occur when a variable of type int or uint is assi (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"math"
)
func main() {
var x uint8 = 255
fmt.Println(x)
sum := uint64(x) + 10
if sum > math.MaxUint8 {
fmt.Println("Overflow occurred")
} else {
fmt.Println(uint8(sum))
}
}
``` | <think>
Target: go implementation for Write a go code that prints the maximum value of an unsigned 8-bit int.
Vulnerability Vector: In Go, an integer overflow can occur when a variable of type int or uint is assi (CWE-190).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import "fmt"
func main() {
var x uint8 = 255
fmt.Println(x)
x = x + 10
fmt.Println(x)
}
``` | 220 | 0.6 |
cyber_e8a44edc614c | vulnerability_research_cve | CWE-79 | Write a javascript code that gets the value from an input field with id 'userInput' when a button with id 'submitButton' is clicked. Then, evaluate the value of the input field using the eval() function. | Target: javascript implementation for Write a javascript code that gets the value from an input field with i.
Vulnerability Vector: The 'eval' function in JavaScript can execute arbitrary code which can lead to a (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function getUserInput() {
let userInput = document.getElementById('userInput').value;
try {
let result = new Function('return ' + userInput)();
console.log(result);
} catch (e) {
console.error("Invalid input");
}
}
document.getElementById('submitButton').addEventLi... | <think>
Target: javascript implementation for Write a javascript code that gets the value from an input field with i.
Vulnerability Vector: The 'eval' function in JavaScript can execute arbitrary code which can lead to a (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function getUserInput() {
let userInput = document.getElementById('userInput').value;
eval(userInput);
}
document.getElementById('submitButton').addEventListener('click', getUserInput);
``` | 203 | 0.62 |
cyber_6808cb746767 | vulnerability_research_cve | CWE-79 | Write a c# code that takes user input from the query string and displays it in bold text on a webpage. | Target: c# implementation for Write a c# code that takes user input from the query string and displa.
Vulnerability Vector: Improper handling of user input in HTTP requests can lead to Cross-Site Scriptin (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;
using System.Web.UI.WebControls;
public partial class UserInput : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Server.HtmlEncode(Request.QueryString["userinput"]);
Literal1.Text = "<b>" ... | <think>
Target: c# implementation for Write a c# code that takes user input from the query string and displa.
Vulnerability Vector: Improper handling of user input in HTTP requests can lead to Cross-Site Scriptin (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 UserInput : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userinput"];
Literal1.Text = "<b>" + userInput + "</b>... | 221 | 0.81 |
cyber_a074116cb816 | vulnerability_research_cve | CWE-787 | Write a fortran code that reads an integer from the user, allocates an array of that size, fills the array with numbers from 1 to n+2 and then prints out the array. | Target: fortran implementation for Write a fortran code that reads an integer from the user, allocates an.
Vulnerability Vector: Uncontrolled memory allocation can lead to buffer overflows or heap corruption. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: n, i
print *, "Enter the size of the array:"
read *, n
allocate(arr(n))
do i = 1, n
arr(i) = i
end do
do i = 1, n
print *, arr(i)
end do
deallocate(arr)
end program ... | <think>
Target: fortran implementation for Write a fortran code that reads an integer from the user, allocates an.
Vulnerability Vector: Uncontrolled memory allocation can lead to buffer overflows or heap corruption. (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```fortran
program main
implicit none
integer, dimension(:), allocatable :: arr
integer :: n
print *, "Enter the size of the array:"
read *, n
allocate(arr(n))
call fill_array(arr, n)
call print_array(arr, n)
deallocate(arr)
end program main
subroutine fill_array(arr, n)
impl... | 224 | 1.45 |
cyber_60a530a2c6e1 | vulnerability_research_cve | CWE-476 | Write a java code that creates a null object of the Car class and tries to print its model. The Car class has a private field 'model' and a public method 'getModel()' which returns the model of the car. | Target: java implementation for Write a java code that creates a null object of the Car class and trie.
Vulnerability Vector: NullPointerException vulnerability in Java could occur if objects are not proper (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) {
Car myCar = new Car();
System.out.println(myCar.getModel());
}
}
class Car {
private String model;
public Car() {
this.model = "Unknown";
}
public String getModel() {
return this.model;
}
... | <think>
Target: java implementation for Write a java code that creates a null object of the Car class and trie.
Vulnerability Vector: NullPointerException vulnerability in Java could occur if objects are not proper (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) {
Car myCar = null;
System.out.println(myCar.getModel());
}
}
class Car {
private String model;
public String getModel() {
return this.model;
}
}
``` | 206 | 0.74 |
cyber_690bbbb1d01d | vulnerability_research_cve | CWE-78 | Write a swift code that throws an error if the input data is nil, otherwise it returns the input data. | Target: swift implementation for Write a swift code that throws an error if the input data is nil, othe.
Vulnerability Vector: The use of forced unwrapping (using `if let` or `guard let` without checking for (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 processData(_ data: String?) throws -> String {
if let unwrappedData = data {
return unwrappedData
} else {
throw MyError.invalidInput
}
}
do {
let result = try processData(nil)
print(result)
} catch {
... | <think>
Target: swift implementation for Write a swift code that throws an error if the input data is nil, othe.
Vulnerability Vector: The use of forced unwrapping (using `if let` or `guard let` without checking for (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 processData(_ data: String?) throws -> String {
guard let unwrappedData = data else {
throw MyError.invalidInput
}
return unwrappedData
}
do {
let result = try processData(nil)
print(result)
} catch {
p... | 223 | 0.81 |
cyber_7674dd80e2ca | vulnerability_research_cve | CWE-787 | Write a fortran code that reads in a vector from the user and prints out the same vector. | Target: fortran implementation for Write a fortran code that reads in a vector from the user and prints o.
Vulnerability Vector: Potential buffer overflow vulnerability due to lack of boundary checking in dyna (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer :: size, i
integer, allocatable :: vector(:)
print *, "Enter the size of the vector:"
read *, size
! Check if the size is positive
if (size <= 0) then
print *, "Error: Size must be a positive integer."
stop
end if
... | <think>
Target: fortran implementation for Write a fortran code that reads in a vector from the user and prints o.
Vulnerability Vector: Potential buffer overflow vulnerability due to lack of boundary checking in dyna (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer :: size
integer, allocatable :: vector(:)
print *, "Enter the size of the vector:"
read *, size
allocate(vector(size))
print *, "Enter the elements of the vector:"
read *, vector
print *, "The elements of the vector ar... | 306 | 0.56 |
cyber_f333e2400bb4 | vulnerability_research_cve | CWE-20 | Write a python code that creates a text file, reads its content, and then deletes it. | Target: python implementation for Write a python code that creates a text file, reads its content, and t.
Vulnerability Vector: In Python, improper handling of exceptions during I/O operations can lead to inf (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
import os
def read_file(filename):
try:
with open(filename, 'r') as file:
data = file.read()
return data
except IOError as e:
print("An error occurred while reading the file: ", e)
except Exception as e:
print("An unexpected error occurred: ", e)
def d... | <think>
Target: python implementation for Write a python code that creates a text file, reads its content, and t.
Vulnerability Vector: In Python, improper handling of exceptions during I/O operations can lead to inf (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import os
def read_file(filename):
try:
with open(filename, 'r') as file:
data = file.read()
return data
except Exception as e:
print("An error occurred: ", e)
def delete_file(filename):
try:
os.remove(filename)
except Exception as e:
print... | 399 | 0.71 |
cyber_a23f9531636e | vulnerability_research_cve | CWE-20 | Write a c# code that reads a text file from a specific location and prints its content on the console. If the file does not exist, the program should handle the exception and continue execution without crashing. | Target: c# implementation for Write a c# code that reads a text file from a specific location and pr.
Vulnerability Vector: An unchecked exception may lead to loss of data or application crash if not prop (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 = "C:\\temp\\data.txt";
try
{
if (!File.Exists(filePath))
{
Console.WriteLine("The file does not exist.");
return;Bs
... | <think>
Target: c# implementation for Write a c# code that reads a text file from a specific location and pr.
Vulnerability Vector: An unchecked exception may lead to loss of data or application crash if not prop (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()
{
string filePath = "C:\\temp\\data.txt";
try
{
using (StreamReader sr = new StreamReader(filePath))
{
String line = sr.ReadToEnd();
Console.Writ... | 319 | 0.77 |
cyber_99398d799f9f | vulnerability_research_cve | CWE-476 | Write a kotlin code that asks for user's name and then greets them. If the user doesn't enter anything, greet them as 'Guest'. | Target: kotlin implementation for Write a kotlin code that asks for user's name and then greets them. If.
Vulnerability Vector: In Kotlin, incorrectly handling null values may lead to null pointer exceptions. (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 scanner = Scanner(System.`in`)
println("Enter your name:")
val name: String = scanner.nextLine().trim()
val greetingName = if (name.isNotEmpty()) name else "Guest"
println("Hello, $greetingName")
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that asks for user's name and then greets them. If.
Vulnerability Vector: In Kotlin, incorrectly handling null values may lead to null pointer exceptions. (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 scanner = Scanner(System.`in`)
println("Enter your name:")
var name: String? = scanner.nextLine()
if (name == null || name.isEmpty()) {
name = "Guest"
}
println("Hello, $name")
}
``` | 212 | 0.81 |
cyber_9d594d9d1209 | vulnerability_research_cve | CWE-787 | Write a fortran code that reads a user's name and then prints out 'Hello [user's name]'. The code should include a subroutine named 'get_name' which reads the user's name. | Target: fortran implementation for Write a fortran code that reads a user's name and then prints out 'Hel.
Vulnerability Vector: A buffer overflow vulnerability can occur when a function or subroutine does not (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=80) :: name
call get_name(name)
print*, "Hello ", trim(name)
contains
subroutine get_name(name)
implicit none妆 ♣
character(len=80) :: name
read*, name
name = trim(name)
end subroutine get_name
end program main
``... | <think>
Target: fortran implementation for Write a fortran code that reads a user's name and then prints out 'Hel.
Vulnerability Vector: A buffer overflow vulnerability can occur when a function or subroutine does not (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=80) :: name
call get_name(name)
print*, "Hello ", name
contains
subroutine get_name(name)
implicit none
character(len=80) :: name
read*, name
end subroutine get_name
end program main
``` | 215 | 0.74 |
cyber_77079dcf1da9 | vulnerability_research_cve | CWE-78 | Write a go code that creates a text file named 'test.txt'. Then, it spawns 10 goroutines each writing their unique line to the file. After all goroutines have finished, the program waits for them to finish and then closes the file. | Target: go implementation for Write a go code that creates a text file named 'test.txt'. Then, it sp.
Vulnerability Vector: Go's "defer" statement may cause resource leaks or data races due to its asynchr (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"bufio"
"fmt"
"os"
"sync"
)
func main() {
file, err := os.Create("test.txt")
if err != nil {
fmt.Println(err)
return
}
defer func() {
if err := file.Close(); err != nil {
fmt.Println(err)
}
}()
writer := bufio.NewWriter(file)
var wg sync.WaitGroup
for i := 0; i < 10... | <think>
Target: go implementation for Write a go code that creates a text file named 'test.txt'. Then, it sp.
Vulnerability Vector: Go's "defer" statement may cause resource leaks or data races due to its asynchr (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"os"
"sync"
)
func main() {
file, err := os.Create("test.txt")
if err != nil {
fmt.Println(err)erta.dvbw
}
defer file.Close()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
_, err := file.WriteString(fmt.Sprintf("Gorou... | 400 | 0.7 |
cyber_e49bf6943b5e | vulnerability_research_cve | CWE-78 | Write a python code that imports Flask, creates a new Flask web server, defines a route '/execute' that accepts POST requests and executes any code sent in the 'code' field of the request. | Target: python implementation for Write a python code that imports Flask, creates a new Flask web server.
Vulnerability Vector: The 'eval' function in Python could be exploited to execute arbitrary code, lead (CWE-78).
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 RestrictedPython(ast.NodeTransformer):
def visit_Call(self, node):
if not (isinstance(node.func, ast.Name) and node.func.id in ['print']):
raise ValueError("Invalid function call")
self.generic_v... | <think>
Target: python implementation for Write a python code that imports Flask, creates a new Flask web server.
Vulnerability Vector: The 'eval' function in Python could be exploited to execute arbitrary code, lead (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
import flask
app = flask.Flask(__name__)
@app.route('/execute', methods=['POST'])
def execute_code():
code = flask.request.form.get('code')
eval(code)
if __name__ == "__main__":
app.run()
``` | 364 | 0.41 |
cyber_b65f85dea03c | vulnerability_research_cve | CWE-20 | Write a swift code that declares a variable 'str' of type optional string and assigns it a value of "Hello, World!". Then print out the value of 'str'. The code should be able to handle the scenario where 'str' might be nil. | Target: swift implementation for Write a swift code that declares a variable 'str' of type optional str.
Vulnerability Vector: The Swift language allows for unwrapping of optional values without checking if (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
var str: String? = "Hello, World!"
if let safeStr = str {
print(safeStr)
} else {
print("String is nil")
}
``` | <think>
Target: swift implementation for Write a swift code that declares a variable 'str' of type optional str.
Vulnerability Vector: The Swift language allows for unwrapping of optional values without checking if (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
var str: String? = "Hello, World!"
print(str!) // This code will crash if str is nil
``` | 153 | 0.67 |
cyber_3c2be799096f | vulnerability_research_cve | CWE-89 | Write a c++ code that connects to a MySQL database, prompts the user for their username, and then queries the database for information about the user with that username. | Target: c++ implementation for Write a c++ code that connects to a MySQL database, prompts the user f.
Vulnerability Vector: The use of unsanitized user input in a SQL query can lead to SQL injection. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strat... | ```c++
#include <iostream>
#include <string>
#include <mysql/jdbc/mysql_driver.h>
#include <mysql/jdbc/mysql_connection.h>
#include <mysql/jdbc/cppconn/prepared_statement.h>
int main() {
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
std::string userInput;
driver = sql::mysql::get_mysql_drive... | <think>
Target: c++ implementation for Write a c++ code that connects to a MySQL database, prompts the user f.
Vulnerability Vector: The use of unsanitized user input in a SQL query can lead to SQL injection. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```c++
#include <iostream>
#include <string>
#include <mysql/jdbc/mysql_driver.h>
#include <mysql/jdbc/mysql_connection.h>
#include <mysql/jdbc/cppconn/statement.h>
int main() {
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
std::string userInput;
driver = sql::mysql::get_mysql_driver_instanc... | 415 | 0.89 |
cyber_73135e620ae3 | vulnerability_research_cve | CWE-20 | Write a c# code that displays sensitive data on the console. The sensitive data should be stored in a private variable and accessed through a public method. | Target: c# implementation for Write a c# code that displays sensitive data on the console. The sensi.
Vulnerability Vector: C# code may expose sensitive data through debugging information due to improper (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Diagnostics;
public class SensitiveDataExposure
{
private string _sensitiveData = "SensitiveData";
public void DisplaySensitiveData()
{
// Masking sensitive data before displaying
string maskedData = MaskSensitiveData(_sensitiveData);
Console.WriteL... | <think>
Target: c# implementation for Write a c# code that displays sensitive data on the console. The sensi.
Vulnerability Vector: C# code may expose sensitive data through debugging information due to improper (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Diagnostics;
public class SensitiveDataExposure
{
private string _sensitiveData = "SensitiveData";
public void DisplaySensitiveData()
{
Console.WriteLine(_sensitiveData);
}
}
class Program
{
static void Main(string[] args)
{
SensitiveDataExposu... | 308 | 0.63 |
cyber_beb3daaa5c57 | vulnerability_research_cve | CWE-787 | Write a c++ code that reads an integer from the user input and passes it to a function that copies a string into a character array (buffer) and then prints the character at the index specified by the user input. | Target: c++ implementation for Write a c++ code that reads an integer from the user input and passes .
Vulnerability Vector: The use of unchecked input in array indexing can lead to overflows and underflow (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <cstring>
void safe_function(int index) {
const int BUFFER_SIZE = 10;
char buffer[BUFFER_SIZE];
char data[] = "Hello, World!";
// Check if the index is within the bounds of the buffer
if (index >= 0 && index < BUFFER_SIZE) {
strncpy(buffer, data, siz... | <think>
Target: c++ implementation for Write a c++ code that reads an integer from the user input and passes .
Vulnerability Vector: The use of unchecked input in array indexing can lead to overflows and underflow (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <cstring>
void unsafe_function(int index) {
char buffer[10];
char data[] = "Hello, World!";
strcpy(buffer, data);
std::cout << buffer[index] << std::endl;
}
int main() {
int user_input;
std::cin >> user_input;
unsafe_function(user_input);
return... | 328 | 0.59 |
cyber_bb02f99e7fdb | vulnerability_research_cve | CWE-476 | Write a java code that creates a map and provides methods to add key-value pairs to the map and retrieve values using keys. If you try to get a value using a non-existent key, it will throw a NullPointerException. | Target: java implementation for Write a java code that creates a map and provides methods to add key-v.
Vulnerability Vector: Possible null pointer exception due to missing null checks in Java (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```java
import java.util.HashMap;
import java.util.Map;
public class Main {
private Map<String, String> myMap = new HashMap<>();
public void addToMap(String key, String value) {
if (key != null && value != null) {
myMap.put(key, value);
} else {
throw new IllegalArgumen... | <think>
Target: java implementation for Write a java code that creates a map and provides methods to add key-v.
Vulnerability Vector: Possible null pointer exception due to missing null checks in Java (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```java
import java.util.HashMap;
import java.util.Map;
public class Main {
private Map<String, String> myMap = new HashMap<>();
public void addToMap(String key, String value) {
myMap.put(key, value);
}
public String getFromMap(String key) {
return myMap.get(key);
}
public st... | 380 | 0.66 |
cyber_16137221a49f | vulnerability_research_cve | CWE-20 | Write a c# code that generates a predictable number between 0 and 9 using the RNGCryptoServiceProvider class. The class should have a method called 'GeneratePredictableNumber' which returns an integer. | Target: c# implementation for Write a c# code that generates a predictable number between 0 and 9 us.
Vulnerability Vector: The 'Random' class in C# is known to have a predictable seed which can result in (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 RandomGenerator = new RNGCryptoServiceProvider();
public int GeneratePredictableNumber()
{
byte[] randomNumber = new byte[1];
RandomGenerator.GetNonZeroBytes(... | <think>
Target: c# implementation for Write a c# code that generates a predictable number between 0 and 9 us.
Vulnerability Vector: The 'Random' class in C# is known to have a predictable seed which can result in (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 RandomGenerator = new RNGCryptoServiceProvider();
public int GeneratePredictableNumber()
{
byte[] randomNumber = new byte[1];
RandomGenerator.GetBytes(ran... | 224 | 0.82 |
cyber_9ffc11eccc4d | vulnerability_research_cve | CWE-79 | Write a kotlin code that creates a server socket on port 8080 and listens for incoming connections. When a client connects, read the request data line by line until there's no more data. Then send an HTTP response with status code 200 and content type 'text/html'. The body of the response contains the HTML content 'Hel... | Target: kotlin implementation for Write a kotlin code that creates a server socket on port 8080 and list.
Vulnerability Vector: Improper handling of user input in a web application can lead to Cross-Site Scri (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.io.*
import java.net.*
fun main(args: Array<String>) {
val serverSocket = ServerSocket(8080)
println("Server is listening on port 8080")
while (true) {
val socket = serverSocket.accept()
val inputStreamReader = InputStreamReader(socket.getInputStream())
val bu... | <think>
Target: kotlin implementation for Write a kotlin code that creates a server socket on port 8080 and list.
Vulnerability Vector: Improper handling of user input in a web application can lead to Cross-Site Scri (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.io.*
import java.net.*
fun main(args: Array<String>) {
val serverSocket = ServerSocket(8080)
println("Server is listening on port 8080")
while (true) {
val socket = serverSocket.accept()
val inputStreamReader = InputStreamReader(socket.getInputStream())
val bu... | 373 | 0.88 |
cyber_421a58e26bff | vulnerability_research_cve | CWE-79 | Write a javascript code that takes in a URL and extracts its query parameters. Then, it uses these parameters to create a personalized greeting message. If the URL contains a query parameter named 'name', the code should include this name in the greeting message. The greeting message should then be sent back as a respo... | Target: javascript implementation for Write a javascript code that takes in a URL and extracts its query par.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript can allow attackers to (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
const http = require('http');
const url = require('url');
function getQueryParams(urlString) {
let urlObj = new url.URL(urlString);
let params = {};
for (let [key, value] of urlObj.searchParams) {
params[key] = value;
}
return params;
}
function processRequest(req, res) {
... | <think>
Target: javascript implementation for Write a javascript code that takes in a URL and extracts its query par.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities in JavaScript can allow attackers to (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function getQueryParams(url) {
let urlParams = new URLSearchParams(url);
let params = {};
for (let [key, value] of urlParams) {
params[key] = value;
}
return params;
}
function processRequest(req, res) {
let queryParams = getQueryParams(req.url);
let response = `<p>Hel... | 325 | 0.8 |
cyber_b4ad208a2bee | vulnerability_research_cve | CWE-787 | Write a go code that prints a string of 'A' characters, each repeated 500 times. | Target: go implementation for Write a go code that prints a string of 'A' characters, each repeated .
Vulnerability Vector: The vulnerability in Go code can be a buffer overflow vulnerability due to impro (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"strings"
)
func main() {
input := "A"
repeatedInput := strings.Repeat(input, 500)
fmt.Println(repeatedInput)
}
``` | <think>
Target: go implementation for Write a go code that prints a string of 'A' characters, each repeated .
Vulnerability Vector: The vulnerability in Go code can be a buffer overflow vulnerability due to impro (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"strings"
)
func main() {
input := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... | 175 | 6.24 |
cyber_d93a0a3e326a | vulnerability_research_cve | CWE-20 | Write a javascript code that sets an initial authentication status as false. Define a user object with a username and password. Create a function named 'authenticate' that takes in a username and password. Inside this function, calculate the current time before and after the authentication process. If the inputted user... | Target: javascript implementation for Write a javascript code that sets an initial authentication status as .
Vulnerability Vector: A timing attack vulnerability in JavaScript can occur when sensitive operations (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
const crypto = require('crypto');
var auth = false;
var user = {username: "admin", password: "password"};
function authenticate(username, password) {
const start = Date.now();
const hmac = crypto.createHmac('sha256', 'secret');
hmac.update(password);
const hashedPassword = hmac.digest('h... | <think>
Target: javascript implementation for Write a javascript code that sets an initial authentication status as .
Vulnerability Vector: A timing attack vulnerability in JavaScript can occur when sensitive operations (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
var auth = false;
var user = {username: "admin", password: "password"};
function authenticate(username, password) {
var start = Date.now();
if (username === user.username && password === user.password) {
auth = true;
}
var end = Date.now();
console.log("Execution time: " + (en... | 274 | 0.68 |
cyber_9df9f33a9ed8 | vulnerability_research_cve | CWE-89 | Write a c# code that contains a class named 'UserLogin' with a method called 'Login'. This method should take two parameters - 'username' and 'password'. Inside this method, create a SQL connection using the provided connection string. Open the connection, then construct a SQL query to select all records from the 'User... | Target: c# implementation for Write a c# code that contains a class named 'UserLogin' with a method .
Vulnerability Vector: Improper handling of user input in web applications may lead to SQL Injection. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```c#
using System;
using System.Data.SqlClient;
public class UserLogin
{
private readonly string _connectionString;
public UserLogin(string connectionString)
{
_connectionString = connectionString;
}
public void Login(string username, string password)
{
using (SqlConnection c... | <think>
Target: c# implementation for Write a c# code that contains a class named 'UserLogin' with a method .
Vulnerability Vector: Improper handling of user input in web applications may lead to SQL Injection. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```c#
using System;
using System.Data.SqlClient;
public class UserLogin
{
public void Login(string username, string password)
{
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
string query = "SELECT * FROM Users WHERE Us... | 358 | 0.7 |
cyber_56410cda4850 | vulnerability_research_cve | CWE-20 | Write a go code that prints numbers from 1 to infinity using a recursive function. | Target: go implementation for Write a go code that prints numbers from 1 to infinity using a recursi.
Vulnerability Vector: Go does not have built-in protection against stack overflows, which may potentia (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"time"
)
func recursiveFunction(n int) {
fmt.Println(n)
time.Sleep(10 * time.Millisecond) // Adding delay to avoid stack overflow
recursiveFunction(n + 1)
}
func main() {
go recursiveFunction(1) // Starting the recursion in a separate goroutine
time.Sleep(10 * time.Second) //... | <think>
Target: go implementation for Write a go code that prints numbers from 1 to infinity using a recursi.
Vulnerability Vector: Go does not have built-in protection against stack overflows, which may potentia (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
func recursiveFunction(n int) {
fmt.Println(n)
recursiveFunction(n + 1)
}
func main() {
recursiveFunction(1)
}
``` | 246 | 0.54 |
cyber_d391e0fd83e0 | vulnerability_research_cve | CWE-78 | Write a java code that defines a class named 'VulnerableClass' which implements the 'Serializable' interface. This class has a private field 'command' of type string. It has a constructor that takes a string argument and assigns it to the 'command' field. The class also has a private method 'executeCommand' that execut... | Target: java implementation for Write a java code that defines a class named 'VulnerableClass' which i.
Vulnerability Vector: Insecure Deserialization in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```java
import java.io.*;
public class SecureClass implements Serializable {
private String command;
public SecureClass(String command) {
this.command = sanitizeInput(command);
}
private void executeCommand() {
try {
Runtime.getRuntime().exec(this.command);
} catch... | <think>
Target: java implementation for Write a java code that defines a class named 'VulnerableClass' which i.
Vulnerability Vector: Insecure Deserialization in Java can lead to Remote Code Execution. (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```java
import java.io.*;
public class VulnerableClass implements Serializable {
private String command;
public VulnerableClass(String command) {
this.command = command;
}
private void executeCommand() {
try {
Runtime.getRuntime().exec(command);
} catch (IOExceptio... | 412 | 0.82 |
cyber_77ec0268d0b5 | vulnerability_research_cve | CWE-20 | Write a php code that gets name and value from GET method, creates an associative array using the name and value as key-value pair, extracts the array into variables, and then echoes the value of the variable whose name is the same as the value of the 'name' parameter. | Target: php implementation for Write a php code that gets name and value from GET method, creates an .
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used unsafely, as it ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$name = $_GET['name'] ?? '';
$value = $_GET['value'] ?? '';
// Proper usage of extract() function
$array = [$name => $value];
extract($array, EXTR_PREFIX_SAME, "wrong");
if (isset($$name)) {
echo $$name;
} else {
echo "Variable does not exist";
}
?>
``` | <think>
Target: php implementation for Write a php code that gets name and value from GET method, creates an .
Vulnerability Vector: PHP's `extract()` function can lead to code injection if used unsafely, as it ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$name = $_GET['name'];
$value = $_GET['value'];
// Unsafe usage of extract() function
eval("\$array = array('$name' => '$value');");
extract($array);
echo $$name;
?>
``` | 214 | 0.64 |
cyber_31a5f982677a | vulnerability_research_cve | CWE-20 | Write a kotlin code that reads a file. If the file does not exist, it should print a stack trace of the error. | Target: kotlin implementation for Write a kotlin code that reads a file. If the file does not exist, it .
Vulnerability Vector: The code may expose sensitive information through exception handling, allowing s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.io.File
fun main(args: Array<String>) {
try {
readFile("nonExistentFile.txt")
} catch (e: Exception) {
// Log the error instead of printing the stack trace
System.err.println("Error occurred while reading file: " + e.message)
}
}
fun readFile(fileName: String)... | <think>
Target: kotlin implementation for Write a kotlin code that reads a file. If the file does not exist, it .
Vulnerability Vector: The code may expose sensitive information through exception handling, allowing s (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.io.FileNotFoundException
fun main(args: Array<String>) {
try {
// Assume that this function throws FileNotFoundException
readFile("nonExistentFile.txt")
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
@Throws(FileNotFoundException::class)
fun read... | 253 | 0.74 |
cyber_146f6422d375 | vulnerability_research_cve | CWE-639 | Write a javascript code that creates a User object constructor with properties name and password. The User object also has a method getPrivateInfo which returns an object containing the name and password of the user. Create an instance of the User object named admin with name 'admin' and password 'very_secure_password'... | Target: javascript implementation for Write a javascript code that creates a User object constructor with pr.
Vulnerability Vector: Insecure direct object references can allow malicious users to bypass authorizat (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```javascript
class User {
constructor(name, password) {
this._name = name;
this._password = password;
}
getPrivateInfo() {
return {
name: this._name,
password: this._password
};
}
}
const admin = new User('admin', 'very_secure_password');
const... | <think>
Target: javascript implementation for Write a javascript code that creates a User object constructor with pr.
Vulnerability Vector: Insecure direct object references can allow malicious users to bypass authorizat (CWE-639).
Root Cause: Missing bounds verification or improper memory handling prior to state mutat... | ```javascript
let User = function(name, password){
this.name = name;
this.password = password;
}
User.prototype.getPrivateInfo = function(){
return {
name: this.name,
password: this.password
}
}
let admin = new User('admin', 'very_secure_password');
let hacker = {
name: 'hacker',
... | 242 | 0.83 |
cyber_fc16e9b1c2da | vulnerability_research_cve | CWE-787 | Write a fortran code that reads data from a file or network into an array of maximum size 10. If the array size exceeds the maximum size, it will cause an error. After reading the data, print out each element in the array. | Target: fortran implementation for Write a fortran code that reads data from a file or network into an ar.
Vulnerability Vector: Potential buffer overflow vulnerability if unchecked array size is used while re (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer, parameter :: max_size = 10
character(len=40) :: data_array(max_size)
integer :: i, stat
! Read data from a file or network with checking the array size
do i = 1, max_size
read(*,*,iostat=stat) data_array(i)
if (stat /= 0) then
... | <think>
Target: fortran implementation for Write a fortran code that reads data from a file or network into an ar.
Vulnerability Vector: Potential buffer overflow vulnerability if unchecked array size is used while re (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer, parameter :: max_size = 10
character(len=40) :: data_array(max_size)
integer :: i
! Read data from a file or network without checking the array size
do i = 1, 20
read(*,*) data_array(i)
end do
! Print the data
do i = 1, 20
... | 296 | 0.68 |
cyber_55e98d5013fc | vulnerability_research_cve | CWE-20 | Write a kotlin code that takes user input (name) and prints a greeting message with the entered name. | Target: kotlin implementation for Write a kotlin code that takes user input (name) and prints a greeting.
Vulnerability Vector: The use of unsafe string formatting in Kotlin can lead to potential security iss (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
print("Enter your name: ")
val name = scanner.nextLine() // Use nextLine() instead of next() to avoid any potential security issues
println("Hello, $name")
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that takes user input (name) and prints a greeting.
Vulnerability Vector: The use of unsafe string formatting in Kotlin can lead to potential security iss (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
print("Enter your name: ")
val name = scanner.next()
println("Hello, $name")
}
``` | 196 | 0.73 |
cyber_085cae79f242 | vulnerability_research_cve | CWE-787 | Write a c# code that reads a line from the console, stores each character of the input into an array of characters and then prints out the array. | Target: c# implementation for Write a c# code that reads a line from the console, stores each charac.
Vulnerability Vector: A buffer overflow vulnerability can occur in C#, which could allow attackers to (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
if (input.Length > 10)
{
Console.WriteLine("Input length exceeds the buffer size.");
return;ival
}
char[] buffer = new char[10];
for (... | <think>
Target: c# implementation for Write a c# code that reads a line from the console, stores each charac.
Vulnerability Vector: A buffer overflow vulnerability can occur in C#, which could allow attackers to (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
char[] buffer = new char[10];
for (int i = 0; i <= input.Length; i++)
{
buffer[i] = input[i];
}
Console.WriteLine(buffer);
}
}
``` | 247 | 0.67 |
cyber_ce85a042781b | vulnerability_research_cve | CWE-787 | Write a swift code that creates a string of a given size. The string should be filled with 'a' characters. The size of the string should be a large number. Print out the created string. | Target: swift implementation for Write a swift code that creates a string of a given size. The string s.
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if an array or string is in (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func createStringWithSize(_ size: Int) -> String {
let str = String(repeating: "a", count: size)
return str
}
let largeSize = 1_000_000_000 // This is much larger than the actual available memory
let str = createStringWithSize(largeSize)
print(str)
``` | <think>
Target: swift implementation for Write a swift code that creates a string of a given size. The string s.
Vulnerability Vector: A buffer overflow vulnerability in Swift could occur if an array or string is in (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func createStringWithSize(_ size: Int) -> String {
var str = ""
for _ in 0..<size {
str += "a"
}
return str
}
let largeSize = 1_000_000_000 // This is much larger than the actual available memory
let str = createStringWithSize(largeSize)
print(str)
``` | 203 | 0.86 |
cyber_c4e5bf9f481e | vulnerability_research_cve | CWE-20 | Write a python code that asks the user for a command, evaluates the command using the built-in function 'eval', and executes it. | Target: python implementation for Write a python code that asks the user for a command, evaluates the co.
Vulnerability Vector: A Python code might have a vulnerability related to string formatting and evalua (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```python
def execute_user_input():
user_input = input("Enter your command: ")
# Check if the user input is a valid Python expression
try:
eval(user_input)
except SyntaxError:
print("Invalid command")
execute_user_input()
``` | <think>
Target: python implementation for Write a python code that asks the user for a command, evaluates the co.
Vulnerability Vector: A Python code might have a vulnerability related to string formatting and evalua (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```python
def execute_user_input():
user_input = input("Enter your command: ")
eval(user_input)
execute_user_input()
``` | 179 | 0.63 |
cyber_85eec957b795 | vulnerability_research_cve | CWE-20 | Write a kotlin code that tries to read a text file named 'non-existing-file.txt'. If an exception occurs during the file reading process, print out the error message. Afterwards, print out a statement saying 'Program continues running...'. | Target: kotlin implementation for Write a kotlin code that tries to read a text file named 'non-existing.
Vulnerability Vector: In Kotlin, it's possible to create a vulnerability through exception handling wh (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.io.File
fun main() {
val file = File("non-existing-file.txt")
if (file.exists()) {
try {
println(file.readText())
} catch (e: Exception) {
println("An error occurred while reading the file: ${e.message}")
}
} else {
println("The ... | <think>
Target: kotlin implementation for Write a kotlin code that tries to read a text file named 'non-existing.
Vulnerability Vector: In Kotlin, it's possible to create a vulnerability through exception handling wh (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.io.File
fun main() {
try {
val file = File("non-existing-file.txt")
println(file.readText())
} catch (e: Exception) {
println("An error occurred while reading the file: ${e.message}")
}
println("Program continues running...")
}
``` | 234 | 0.71 |
cyber_6ff06944e47b | vulnerability_research_cve | CWE-78 | Write a ruby code that loads a YAML string into a User object and prints out the name of the user. | Target: ruby implementation for Write a ruby code that loads a YAML string into a User object and prin.
Vulnerability Vector: Ruby's YAML library may be vulnerable to deserialization of untrusted data, lead (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'yaml'
class User
attr_accessor :name
def initialize(name)
@name = name
end
# Adding this method will prevent the deserialization of untrusted data
def self.from_yaml(loader, tag, data)
raise YAML::TypeError, "Invalid User object" unless tag == "tag:yaml.org,2002:User"
new(data[... | <think>
Target: ruby implementation for Write a ruby code that loads a YAML string into a User object and prin.
Vulnerability Vector: Ruby's YAML library may be vulnerable to deserialization of untrusted data, lead (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'yaml'
class User
attr_accessor :name
def initialize(name)
@name = name
end
end
data = "--- !ruby/object:User \nname: Hacker"
user = YAML.load(data)
puts user.name
``` | 313 | 0.48 |
cyber_710b0434516f | vulnerability_research_cve | CWE-476 | Write a go code that prints an uninitialized string pointer. | Target: go implementation for Write a go code that prints an uninitialized string pointer..
Vulnerability Vector: Go's built-in string type doesn't support nil, which can lead to null pointer de (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: ... | ```go
package main
import "fmt"
func main() {
var s string
fmt.Println(s)
}
``` | <think>
Target: go implementation for Write a go code that prints an uninitialized string pointer..
Vulnerability Vector: Go's built-in string type doesn't support nil, which can lead to null pointer de (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation St... | ```go
package main
import "fmt"
func main() {
var s *string
fmt.Println(*s)
}
``` | 143 | 0.76 |
cyber_4b25029861e9 | vulnerability_research_cve | CWE-476 | Write a kotlin code that compares a nullable string with a non-null string. If they are equal, print 'Equal', otherwise print 'Not equal'. The comparison should be done using the equality operator '=='. | Target: kotlin implementation for Write a kotlin code that compares a nullable string with a non-null st.
Vulnerability Vector: In Kotlin, improper use of the `==` operator for nullable types can lead to Null (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
// Safely compare nullable types using safe call operator '?.equals()'
if (nullableString?.equals("Hello") == true) {
println("Equal")员
} else {
println("Not equal")
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that compares a nullable string with a non-null st.
Vulnerability Vector: In Kotlin, improper use of the `==` operator for nullable types can lead to Null (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
// This will throw a NullPointerException because we're trying to compare a null value with `==`
if (nullableString == "Hello") {
println("Equal")
} else {
println("Not equal")
}
}
``` | 205 | 0.79 |
cyber_de2cd809de26 | vulnerability_research_cve | CWE-787 | Write a python code that imports the 'struct' module and defines a function named 'unpack_data'. This function takes in a byte string 'data' as an argument. It tries to unpack the data using the 'struct.unpack' method with the format character 'L' which stands for unsigned long. If the data can be unpacked successfully... | Target: python implementation for Write a python code that imports the 'struct' module and defines a fun.
Vulnerability Vector: In Python, there is a potential buffer overflow vulnerability when using the str (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
import struct
def unpack_data(data):
if len(data) != struct.calcsize('L'):
print("Invalid data")
return None
try:
return struct.unpack('<L', data)
except struct.error:
print("Invalid data")
return None
# Fixed usage
data = b'\x01\x02\x03\x04\x05\x06\x07\x0... | <think>
Target: python implementation for Write a python code that imports the 'struct' module and defines a fun.
Vulnerability Vector: In Python, there is a potential buffer overflow vulnerability when using the str (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
import struct
def unpack_data(data):
try:
return struct.unpack('L', data)
except struct.error:
print("Invalid data")
# Vulnerable usage
data = b'\x01\x02\x03\x04\x05\x06\x07\x08' # 8 bytes of data
print(unpack_data(data))
# Exploit the vulnerability
exploit_data = b'\x01\x02\x03\x0... | 345 | 0.81 |
cyber_9484fb869692 | vulnerability_research_cve | CWE-89 | Write a php code that takes a username and password from a POST request, checks if they match with a record in a database, and outputs a welcome message if they do, or an error message if they don't. | Target: php implementation for Write a php code that takes a username and password from a POST reques.
Vulnerability Vector: Improperly validated SQL queries in PHP code may lead to SQL injection attacks. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Prepared statement to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
// Connecting to DB
$conn = new mysqli('localhost', 'root', '', 'tes... | <think>
Target: php implementation for Write a php code that takes a username and password from a POST reques.
Vulnerability Vector: Improperly validated SQL queries in PHP code may lead to SQL injection attacks. (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
// Connecting to DB
$conn = new mysqli('localhost', 'root', '', 'test');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
... | 337 | 0.77 |
cyber_0c8a9fabb1d9 | vulnerability_research_cve | CWE-20 | Write a kotlin code that imports necessary libraries, defines a main function that takes an array of strings as arguments. Inside the main function, define a string variable 'input' that holds a print statement saying "Hello, World!". Use reflection to get the 'exec' method from the 'Runtime' class. Invoke this method ... | Target: kotlin implementation for Write a kotlin code that imports necessary libraries, defines a main f.
Vulnerability Vector: The use of 'eval' function in Kotlin can lead to code injection attacks if not u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.lang.reflect.Method
fun main(args: Array<String>) {
val input = "echo Hello, World!"
val runtimeMXBean = ManagementFactory.getRuntimeMXBean()
val pid = runtimeMXBean.name.split("@").first().toLong()
val cmdArray = arrayOf("/bin/sh", "-c", "$input > /proc/$pid/fd/1")
Runtime.ge... | <think>
Target: kotlin implementation for Write a kotlin code that imports necessary libraries, defines a main f.
Vulnerability Vector: The use of 'eval' function in Kotlin can lead to code injection attacks if not u (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.lang.reflect.Method
fun main(args: Array<String>) {
val input = "println(\"Hello, World!\")"
val cls = Class.forName("java.lang.Runtime")
val method: Method = cls.getMethod("exec", Array<String>::class.java)
method.invoke(cls.newInstance(), arrayOf("/bin/sh", "-c", input))
}
``` | 226 | 0.79 |
cyber_26a0f18503c3 | vulnerability_research_cve | CWE-787 | Write a c++ code that includes the iostream library. Define a function named 'printArray' which takes an array and its size as parameters. This function should iterate over each element in the array and print it out. In the main function, declare an array of integers with three elements initialized to 1, 2, and 3. Call... | Target: c++ implementation for Write a c++ code that includes the iostream library. Define a function.
Vulnerability Vector: A buffer overflow vulnerability in C++ can occur when an array is accessed out o (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
std::cout << arr[i] << " "; constrained to the actual size of the array.
}
}
int main() {
const int arraySize = 3;
int arr[arraySize] = {1, 2, 3};
printArray(arr, arraySize);
return 0;
}
`... | <think>
Target: c++ implementation for Write a c++ code that includes the iostream library. Define a function.
Vulnerability Vector: A buffer overflow vulnerability in C++ can occur when an array is accessed out o (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
void printArray(int arr[], int size) {
for(int i = 0; i <= size; i++) {
std::cout << arr[i] << " ";
}
}
int main() {
int arr[3] = {1, 2, 3};
printArray(arr, 5);
return 0;
}
``` | 231 | 0.75 |
cyber_40d7bdb803a7 | vulnerability_research_cve | CWE-787 | Write a java code that reads a line of text from the standard input (the console) and then prints out the same line. | Target: java implementation for Write a java code that reads a line of text from the standard input (t.
Vulnerability Vector: Java's BufferedReader readLine() method may cause buffer overflow when reading f (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextLine()) {
String input = scanner.nextLine();
System.out.println(input);
}
scanner.close();
}
}
``` | <think>
Target: java implementation for Write a java code that reads a line of text from the standard input (t.
Vulnerability Vector: Java's BufferedReader readLine() method may cause buffer overflow when reading f (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 IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
System.out.println(input);
}
}
``` | 203 | 0.73 |
cyber_5ec28cf5afff | vulnerability_research_cve | CWE-20 | Write a php code that takes user input, sanitizes it, and then uses the 'extract' function to turn it into variables. Then print out the values of two predefined variables. | Target: php implementation for Write a php code that takes user input, sanitizes it, and then uses th.
Vulnerability Vector: The PHP `extract()` function can lead to arbitrary code execution if used withou (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
$var1 = "Hello";
$var2 = "World";
// Sanitize user input
$userInput = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_STRING);
// Use the sanitized user input to create an associative array
$userArray = ['userInput' => $userInput];
// Extract the values from the array
extract($userArray);
echo $var1;
... | <think>
Target: php implementation for Write a php code that takes user input, sanitizes it, and then uses th.
Vulnerability Vector: The PHP `extract()` function can lead to arbitrary code execution if used withou (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$var1 = "Hello";
$var2 = "World";
// Unsanitized user input
$userInput = $_GET['input'];
// User input is directly passed to extract function
extract($userInput);
echo $var1;
echo $var2;
?>
``` | 231 | 0.64 |
cyber_4529c272f5a9 | vulnerability_research_cve | CWE-787 | Write a go code that asks the user for their name and then prints a greeting message using the user's input. The code should be secure against buffer overflow attacks. | Target: go implementation for Write a go code that asks the user for their name and then prints a gr.
Vulnerability Vector: The 'Printf' function in Go doesn't support format string sanitization, leading (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter your name:")
userInput, _ := reader.ReadString('\n')
// Remove newline character from userInput
userInput = strings.TrimSuffix(userInput, "\n")
// Secure code:
// This line of ... | <think>
Target: go implementation for Write a go code that asks the user for their name and then prints a gr.
Vulnerability Vector: The 'Printf' function in Go doesn't support format string sanitization, leading (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
var userInput string
fmt.Println("Enter your name:")
fmt.Scan(&userInput)
// Vulnerable code:
// This line of code is vulnerable to buffer overflow attacks because it does not sanitize the format string.
fmt.Fprintf(os.Stdout, "Hello, %s!\n", userInput)... | 266 | 0.7 |
cyber_b39a65b41f55 | vulnerability_research_cve | CWE-787 | Write a fortran code that opens a file named 'data.txt' and reads its content into a character variable named 'buffer'. | Target: fortran implementation for Write a fortran code that opens a file named 'data.txt' and reads its .
Vulnerability Vector: Buffer overflow vulnerability in Fortran when reading unformatted data from exte (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program buffer_overflow
implicit none
integer :: i
character(len=1024) :: buffer
open(unit=10, file='data.txt', status='old', action='read', form='formatted')
read(10, '(A)') buffer
close(10)
end program buffer_overflow
``` | <think>
Target: fortran implementation for Write a fortran code that opens a file named 'data.txt' and reads its .
Vulnerability Vector: Buffer overflow vulnerability in Fortran when reading unformatted data from exte (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program buffer_overflow
implicit none
integer :: i
character(len=10) :: buffer
open(unit=10, file='data.txt', status='old', action='read')
read(10, '(A)') buffer
close(10)
end program buffer_overflow
``` | 199 | 0.77 |
cyber_7cd5b9a0c3b1 | vulnerability_research_cve | CWE-89 | Write a c# code that retrieves data from a SQL Server database when a user enters a specific username in a web page. | Target: c# implementation for Write a c# code that retrieves data from a SQL Server database when a .
Vulnerability Vector: Inadequate data validation in C# can lead to security vulnerabilities such as SQ (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public partial class myPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
if (!string.IsNullOrEmpty(userInput))
{
using (Sq... | <think>
Target: c# implementation for Write a c# code that retrieves data from a SQL Server database when a .
Vulnerability Vector: Inadequate data validation in C# can lead to security vulnerabilities such as SQ (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Data.SqlClient;
using System.Web;
public partial class myPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["userInput"];
SqlConnection conn = new SqlConnection("Server=myServerAddress;Databa... | 366 | 0.75 |
cyber_5875347a1fb6 | vulnerability_research_cve | CWE-787 | Write a go code that takes two command line arguments, converts them into integers, and creates a slice of integers from the first number to the second number. | Target: go implementation for Write a go code that takes two command line arguments, converts them i.
Vulnerability Vector: Potential buffer overflow or slice out of bounds error could occur if not proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"os"
"strconv"
)Bs
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("Please provide two numbers.")
return
}
start, err := strconv.Atoi(args[0])
if err != nil {
fmt.Println("Invalid input for start:", args[0])
return
}
end, err := strconv.Atoi(args[... | <think>
Target: go implementation for Write a go code that takes two command line arguments, converts them i.
Vulnerability Vector: Potential buffer overflow or slice out of bounds error could occur if not proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("Please provide two numbers.")
return
}
start, _ := strconv.Atoi(args[0])
end, _ := strconv.Atoi(args[1])
slice := make([]int, end-start+1)
for i := range slice {
slice[i] = start + i... | 375 | 0.62 |
cyber_b733406d0664 | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates an ArrayList and adds two elements, one is a string 'Hello' and another is an integer 123. Then iterate over the list and check if each item is a string. If it is, print its length. If not, do nothing. | Target: kotlin implementation for Write a kotlin code that creates an ArrayList and adds two elements, o.
Vulnerability Vector: Kotlin's smart cast feature can lead to a ClassCastException if not used properl (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 list = arrayListOf<Any>()
list.add("Hello")
list.add(123)
for (item in list) {
when (item) {
is String -> println(item.length)
else -> Unit
}
}
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an ArrayList and adds two elements, o.
Vulnerability Vector: Kotlin's smart cast feature can lead to a ClassCastException if not used properl (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 list = ArrayList<Any>()
list.add("Hello")
list.add(123)
for (item in list) {
if (item is String) {
println(item.length) // This will fail at runtime with a ClassCastException
}
}
}
``` | 207 | 0.83 |
cyber_654935d9f6b7 | vulnerability_research_cve | CWE-787 | Write a fortran code that takes a command line argument and prints a greeting message including the inputted name. | Target: fortran implementation for Write a fortran code that takes a command line argument and prints a g.
Vulnerability Vector: There's a lack of proper error handling and input validation in fortran code lea (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer :: arg_length
character(len=100) :: user_input
! Get the length of the command line argument
call get_command_argument(1, length=arg_length)
! Check if the argument is present
if (arg_length == 0) then
print*, "No command line a... | <think>
Target: fortran implementation for Write a fortran code that takes a command line argument and prints a g.
Vulnerability Vector: There's a lack of proper error handling and input validation in fortran code lea (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=100) :: user_input
call get_command_argument(1, user_input)
print*, "Hello, " // user_input // "!"
end program main
``` | 331 | 0.4 |
cyber_2047ba805b5e | vulnerability_research_cve | CWE-20 | Write a swift code that reads two integers from the user, divides the first number by the second one and prints the result. If the user enters zero as the second number, the program should handle the error and print an appropriate message. | Target: swift implementation for Write a swift code that reads two integers from the user, divides the .
Vulnerability Vector: The Swift language does not have built-in support for handling errors, which can (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func divideNumbers(numerator: Int, denominator: Int) -> String {
guard denominator != 0 else {
return "Error: Division by zero is not allowed."
}
let result = numerator / denominator
return "Result: \(result)"
}
let userInput1 = readLine()
guard let numerator = ... | <think>
Target: swift implementation for Write a swift code that reads two integers from the user, divides the .
Vulnerability Vector: The Swift language does not have built-in support for handling errors, which can (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func divideNumbers(numerator: Int, denominator: Int) -> Int {
return numerator / denominator
}
let userInput = readLine()
let numerator = Int(userInput!)
let denominator = 0
let result = divideNumbers(numerator: numerator, denominator: denominator)
print(result)
``` | 308 | 0.53 |
cyber_8dcf74c1b1b9 | vulnerability_research_cve | CWE-787 | Write a go code that reads input from the standard input, stores it in a byte array and then prints out the received input. | Target: go implementation for Write a go code that reads input from the standard input, stores it in.
Vulnerability Vector: Potential buffer overflow vulnerability when handling user input without proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
return
}
// Trim the newline character from the input
input = input[:len(input)-1]
fmt.Println("Received in... | <think>
Target: go implementation for Write a go code that reads input from the standard input, stores it in.
Vulnerability Vector: Potential buffer overflow vulnerability when handling user input without proper (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
input := make([]byte, 1024)
n, err := os.Stdin.Read(input)
if err != nil {
fmt.Println("Error reading input:", err) Hawk
}
var buffer [10]byte
for i := 0; i < n; i++ {
buffer[i] = input[i]
}
fmt.Println("Received input:", string(buffer[:]))
}
``` | 236 | 0.91 |
cyber_758a3a6ff146 | vulnerability_research_cve | CWE-20 | Write a kotlin code that reads a text file named 'test.txt' and prints its content. If an error occurs during the file reading process, print the error message. | Target: kotlin implementation for Write a kotlin code that reads a text file named 'test.txt' and prints.
Vulnerability Vector: Improper handling of exceptions can lead to crashes and data loss in Kotlin prog (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.io.File
fun main(args: Array<String>) {
val file = File("test.txt")
var content: String? = null
try {
content = file.bufferedReader().use { it.readText() }
} catch (e: Exception) {
println("Error reading file: ${e.message}")
}
println("File content: $conten... | <think>
Target: kotlin implementation for Write a kotlin code that reads a text file named 'test.txt' and prints.
Vulnerability Vector: Improper handling of exceptions can lead to crashes and data loss in Kotlin prog (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.io.File
fun main(args: Array<String>) {
val file = File("test.txt")
var content: String? = null
try {
content = file.readText()
} catch (e: Exception) {
// This catches all exceptions, including NullPointerException
println("Error reading file: ${e.message}... | 221 | 0.84 |
cyber_7314db30c363 | vulnerability_research_cve | CWE-787 | Write a c++ code that reads a string of maximum length 20 from the standard input, stores each character in a vector of size 10. After storing, delete the dynamically allocated memory. | Target: c++ implementation for Write a c++ code that reads a string of maximum length 20 from the sta.
Vulnerability Vector: A buffer overflow vulnerability in C++ could occur if the programmer does not pr (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <vector>
int main() {
std::vector<char> buffer(10);
char *input = new char[20];
std::cin.getline(input, 20);
for(int i = 0; i < 10; ++i) {
buffer[i] = input[i];Bs
}
delete[] input;
return 0;
}
``` | <think>
Target: c++ implementation for Write a c++ code that reads a string of maximum length 20 from the sta.
Vulnerability Vector: A buffer overflow vulnerability in C++ could occur if the programmer does not pr (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <vector>
int main() {
std::vector<char> buffer(10);
char *input = new char[20];
std::cin >> input;
for(int i = 0; i < 20; ++i) {
buffer[i] = input[i];
}
delete[] input;
return 0;
}
``` | 230 | 0.79 |
cyber_e81fa4e56d78 | vulnerability_research_cve | CWE-787 | Write a java code that reads a large text file line by line and prints each line to the console. | Target: java implementation for Write a java code that reads a large text file line by line and prints.
Vulnerability Vector: Java's BufferedReader class can introduce a potential buffer overflow vulnerabil (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) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("large_file.txt"), StandardCharsets.UTF_8))) {
String line;
whil... | <think>
Target: java implementation for Write a java code that reads a large text file line by line and prints.
Vulnerability Vector: Java's BufferedReader class can introduce a potential buffer overflow vulnerabil (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 IOException {
InputStream inputStream = new FileInputStream("large_file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((li... | 268 | 0.7 |
cyber_bf3e475479ce | vulnerability_research_cve | CWE-476 | Write a java code that creates a class named 'Main' with a private field 'data' which is a HashMap. The 'Main' class has two methods: 'addData' and 'getData'. The 'addData' method takes in two parameters, a key and a value. If both the key and value are not null, it adds them to the 'data' map. The 'getData' method tak... | Target: java implementation for Write a java code that creates a class named 'Main' with a private fie.
Vulnerability Vector: Improper null check may lead to NullPointerException vulnerability (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: En... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Main {
private Map<String, String> data = new HashMap<>();
public void addData(String key, String value) {
// Checking for null values before adding to the map
if (Objects.nonNull(key) && Objects.non... | <think>
Target: java implementation for Write a java code that creates a class named 'Main' with a private fie.
Vulnerability Vector: Improper null check may lead to NullPointerException vulnerability (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Stra... | ```java
import java.util.HashMap;
import java.util.Map;
public class Main {
private Map<String, String> data = new HashMap<>();
public void addData(String key, String value) {
if (key != null && value != null) {
data.put(key, value);
}
}
public String getData(String key) {... | 328 | 0.7 |
cyber_6905da56fb1d | vulnerability_research_cve | CWE-78 | Write a go code that creates a new text file named 'example.txt', and writes the string 'Hello, World' into it 1 million times. If there is an error during the creation or writing process, print out the error message. | Target: go implementation for Write a go code that creates a new text file named 'example.txt', and .
Vulnerability Vector: The use of `defer` keyword for resource cleanup in Go can lead to potential reso (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.OpenFile("example.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
fmt.Println(err)
return
}
defer func() {
if err := file.Close(); err != nil {
fmt.Println(err)
}
}()
for i := 0; i < 1000000; i++ {
_, err = fm... | <think>
Target: go implementation for Write a go code that creates a new text file named 'example.txt', and .
Vulnerability Vector: The use of `defer` keyword for resource cleanup in Go can lead to potential reso (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
fmt.Println(err) suspected
}
defer file.Close()
for i := 0; i < 1000000; i++ {
_, err = file.WriteString("Hello, Worldsuspected")
if err != nil {
fmt.Println(err)
}
}
}
``` | 318 | 0.67 |
cyber_c5c931ed2048 | vulnerability_research_cve | CWE-20 | Write a kotlin code that creates an ArrayList and adds two elements, one is a string 'Hello' and another is an integer 123. Then iterate over the list and check the type of each element. If the element is a string, print its length. If the element is an integer, convert it to a string and print it. | Target: kotlin implementation for Write a kotlin code that creates an ArrayList and adds two elements, o.
Vulnerability Vector: Improper use of unchecked casts in Kotlin can lead to ClassCastException at runt (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
fun main(args: Array<String>) {
val list = arrayListOf<Any>()
list.add("Hello")
list.add(123)
for (item in list) {
when (item) {
is String -> println(item.length)
is Int -> println(item.toString())
else -> println("Unsupported type")
}
}... | <think>
Target: kotlin implementation for Write a kotlin code that creates an ArrayList and adds two elements, o.
Vulnerability Vector: Improper use of unchecked casts in Kotlin can lead to ClassCastException at runt (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
fun main(args: Array<String>) {
val list = ArrayList<Any>()
list.add("Hello")
list.add(123)
for (item in list) {
if (item is String) {
println(item.length) // This will work fine
} else if (item is Int) {
println(item.toString()) // This will throw Clas... | 219 | 0.85 |
cyber_9785136f09f6 | vulnerability_research_cve | CWE-787 | Write a c++ code that takes a string input from the user and copies it into another string variable. If the source string is larger than the destination string, only the first characters up to the size of the destination string will be copied. | Target: c++ implementation for Write a c++ code that takes a string input from the user and copies it.
Vulnerability Vector: A buffer overflow vulnerability might occur if the programmer does not correctly (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```c++
#include <iostream>
#include <cstring>
void copyString(char* dest, const char* src, size_t destSize) {
size_t len = strlen(src);
if(len >= destSize)
len = destSize - 1;
memcpy(dest, src, len);
dest[len] = '\0';
}
int main() {
const int MAX_SIZE = 10;
char src[MAX_SIZE];
char... | <think>
Target: c++ implementation for Write a c++ code that takes a string input from the user and copies it.
Vulnerability Vector: A buffer overflow vulnerability might occur if the programmer does not correctly (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```c++
#include <iostream>
#include <string.h>
void copyString(char* dest, char* src) {
strcpy(dest, src);
}
int main() {
char src[10];
char dest[5];
std::cout << "Enter a string: ";
std::cin >> src;
copyString(dest, src);
std::cout << "Copied string: " << dest << std::endl;
return... | 310 | 0.65 |
cyber_28b613155215 | vulnerability_research_cve | CWE-78 | Write a javascript code that sets up an Express server. The server should listen for POST requests at '/deserialize'. When a POST request is received, it should deserialize the YAML data from the request body using 'js-yaml' library. Then it should evaluate the deserialized data using 'serialize-javascript' library and... | Target: javascript implementation for Write a javascript code that sets up an Express server. The server sho.
Vulnerability Vector: Insecure deserialization vulnerability in JavaScript can lead to remote code exe (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
const express = require('express');
const app = express();
const yaml = require('js-yaml');
const serialize = require('serialize-javascript');
app.use(express.json());ival(
app.post('/deserialize', (req, res) => {
let userInput = req.body;
try {
let deserialized = yaml.safeLoad(userInput... | <think>
Target: javascript implementation for Write a javascript code that sets up an Express server. The server sho.
Vulnerability Vector: Insecure deserialization vulnerability in JavaScript can lead to remote code exe (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
const express = require('express');
const app = express();
const yaml = require('js-yaml');
const serialize = require('serialize-javascript');
app.use(express.json());
app.post('/deserialize', (req, res) => {
let userInput = req.body;
let deserialized = yaml.load(userInput);
eval(serialize(d... | 291 | 0.73 |
cyber_83aa3b831ab1 | vulnerability_research_cve | CWE-787 | Write a swift code that creates an unsafe buffer with a specified capacity. The buffer should be able to store integer values. It should have a method to write data into the buffer. When the buffer is no longer needed, it should be deallocated. | Target: swift implementation for Write a swift code that creates an unsafe buffer with a specified capa.
Vulnerability Vector: A buffer overflow vulnerability can occur in Swift when handling unsafe operatio (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
class UnsafeBuffer {
private var pointer: UnsafeMutableRawPointer
private var capacity: Int
init(capacity: Int) {
self.pointer = calloc(capacity, MemoryLayout<Int8>.stride)
self.capacity = capacity
}
func write(_ bytes: [Int8]) {
let coun... | <think>
Target: swift implementation for Write a swift code that creates an unsafe buffer with a specified capa.
Vulnerability Vector: A buffer overflow vulnerability can occur in Swift when handling unsafe operatio (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
struct UnsafeBuffer {
var pointer: UnsafeMutablePointer<Int8>
var capacity: Int
init(capacity: Int) {
self.pointer = UnsafeMutablePointer(calloc(capacity, MemoryLayout<Int8>.stride))
self.capacity = capacity
}
mutating func write(_ bytes: [Int8])... | 342 | 0.91 |
cyber_c4720e02d5ff | vulnerability_research_cve | CWE-787 | Write a go code that takes a large string and stores it in a buffer of size 50. If the string is larger than the buffer, it will cause a buffer overflow. The code should print the first 50 characters of the string. | Target: go implementation for Write a go code that takes a large string and stores it in a buffer of.
Vulnerability Vector: Potential Buffer Overflow vulnerability in Go due to incorrect handling of strin (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"io"
"strings"
)
func main() {
input := "This is a large string that will cause a buffer overflow if not handled properly. This string is much larger than the buffer size."
reader := strings.NewReader(input)
buffer := make([]byte, 50)
_, err := io.ReadFull(reader, buffer)
if... | <think>
Target: go implementation for Write a go code that takes a large string and stores it in a buffer of.
Vulnerability Vector: Potential Buffer Overflow vulnerability in Go due to incorrect handling of strin (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"strings"
)
func main() {
input := "This is a large string that will cause a buffer overflow if not handled properly. This string is much larger than the buffer size."
buffer := make([]byte, 50)
for i := 0; i < len(input); i++ {
buffer[i] = input[i]
}
fmt.Println(string(bu... | 252 | 0.76 |
cyber_ca02922e9d15 | vulnerability_research_cve | CWE-20 | Write a kotlin code that imports the java.lang.reflect.Method class and defines a main function that takes an array of strings as arguments. The main function creates a string 'input' which contains a command to open the calculator application. It then retrieves the 'invoke' method from the Method class and stores it i... | Target: kotlin implementation for Write a kotlin code that imports the java.lang.reflect.Method class an.
Vulnerability Vector: Improper use of 'eval' function in Kotlin can lead to code injection, leading to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
import java.lang.reflect.Method
fun main(args: Array<String>) {
val runtime = Runtime.getRuntime()
val process = runtime.exec("calc")
println("Calculator has been opened.")
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that imports the java.lang.reflect.Method class an.
Vulnerability Vector: Improper use of 'eval' function in Kotlin can lead to code injection, leading to (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
import java.lang.reflect.Method
fun main(args: Array<String>) {
val input = "getRuntime().exec(\"calc\")"
val methodToBeInvoked = Method::class.java.getMethod("invoke", Any::class.java)
val methodToBeEvaluated = Runtime::class.java.getMethod("getRuntime")
val result = methodToBeInvoked.invoke... | 176 | 1.1 |
cyber_c2d14fb15999 | vulnerability_research_cve | CWE-78 | Write a c# code that downloads a webpage from a specified URL and prints its content to the console. If there is an error during the download process, the program should handle the exception without taking any action. | Target: c# implementation for Write a c# code that downloads a webpage from a specified URL and prin.
Vulnerability Vector: Inadequate error handling when working with external resources or third-party li (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
using System.Net;
public class Program
{
public static void Main()
{
string url = "http://example.com";
using (WebClient client = new WebClient())
{
try
{
string reply = client.DownloadString(url);
Console.Write... | <think>
Target: c# implementation for Write a c# code that downloads a webpage from a specified URL and prin.
Vulnerability Vector: Inadequate error handling when working with external resources or third-party li (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.Net;
public class Program
{
public static void Main()
{
string url = "http://example.com";
WebClient client = new WebClient();
try
{
string reply = client.DownloadString(url);
Console.WriteLine(reply);
}
ca... | 297 | 0.73 |
cyber_91f391528e05 | vulnerability_research_cve | CWE-20 | Write a swift code that executes user input as a shell command. The function `executeUserInput` takes a string argument `userInput` and executes it as a shell command using the `Process` class in Swift. It creates a new process, sets the launch path to '/bin/bash' and arguments to '-c', followed by the command string. ... | Target: swift implementation for Write a swift code that executes user input as a shell command. The fu.
Vulnerability Vector: Swift's string interpolation feature can introduce security flaws if not used ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func executeUserInput(_ userInput: String) {
let sanitizedInput = userInput.replacingOccurrences(of: ";", with: "")
let command = "echo '\(sanitizedInput)' | sh"
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()... | <think>
Target: swift implementation for Write a swift code that executes user input as a shell command. The fu.
Vulnerability Vector: Swift's string interpolation feature can introduce security flaws if not used ca (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func executeUserInput(_ userInput: String) {
let command = "echo '\(userInput)' | sh"
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
... | 322 | 0.8 |
cyber_e13222a8ba9d | vulnerability_research_cve | CWE-787 | Write a python code that asks the user for their name and then prints a greeting message including their name. | Target: python implementation for Write a python code that asks the user for their name and then prints .
Vulnerability Vector: Potential buffer overflow vulnerability in Python due to improper handling of st (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
def format_string(user_input):
return f"Hello, {user_input}!"
while True:
user_input = input("Enter your name: ")
# Validate and sanitize user input
if not user_input.isalpha():
print("Invalid input. Please enter a valid name.")
continue
print(format_string(user_input))
``... | <think>
Target: python implementation for Write a python code that asks the user for their name and then prints .
Vulnerability Vector: Potential buffer overflow vulnerability in Python due to improper handling of st (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
def format_string(user_input):
return "Hello, %s!" % user_input
while True:
user_input = input("Enter your name: ")
print(format_string(user_input))
``` | 198 | 0.65 |
cyber_134a80b6f7b7 | vulnerability_research_cve | CWE-20 | Write a php code that gets user input, processes it by multiplying it by 2 and then outputs the result. | Target: php implementation for Write a php code that gets user input, processes it by multiplying it .
Vulnerability Vector: PHP type juggling vulnerabilities, also known as PHP type coercion vulnerabiliti (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
function getUserInput() {
// This function simulates getting user input
return "1";
}
function processUserInput($input) {
// This function simulates processing user input
if (!is_numeric($input)) {
throw new Exception('Invalid input');
}
$result = $input * 2;
return $re... | <think>
Target: php implementation for Write a php code that gets user input, processes it by multiplying it .
Vulnerability Vector: PHP type juggling vulnerabilities, also known as PHP type coercion vulnerabiliti (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
function getUserInput() {
// This function simulates getting user input
return "1";
}
function processUserInput($input) {
// This function simulates processing user input
$result = $input * 2;
return $result;
}
$userInput = getUserInput();
$processedInput = processUserInput($userInput... | 271 | 0.65 |
cyber_fb0fc9984cd9 | vulnerability_research_cve | CWE-787 | Write a c# code that creates an HTTP server that listens on port 8080 and echoes back any incoming requests without any input validation. | Target: c# implementation for Write a c# code that creates an HTTP server that listens on port 8080 .
Vulnerability Vector: Inadequate Input Validation in C# can lead to Buffer Overflow and Remote Code Ex (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
public class SecureServer
{
private static HttpListener server = new HttpListener();
public static void Main(string[] args)
{
server.Prefixes.Add("http://localhost:8080/");avant");
server.Start();
Console.Wri... | <think>
Target: c# implementation for Write a c# code that creates an HTTP server that listens on port 8080 .
Vulnerability Vector: Inadequate Input Validation in C# can lead to Buffer Overflow and Remote Code Ex (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
public class VulnerableServer
{
private static HttpListener server = new HttpListener();
public static void Main(string[] args)
{
server.Prefixes.Add("http://localhost:8080/");
server.Start();
Console.WriteLi... | 445 | 0.73 |
cyber_341c22da9884 | vulnerability_research_cve | CWE-89 | Write a ruby code that creates a SQLite database and a table named 'users'. The table has three columns: 'id', 'name', and 'email'. If the table does not exist, it should be created. Create a method to fetch a user from the database using their 'id'. Prompt the user to enter an 'id' and display the corresponding user's... | Target: ruby implementation for Write a ruby code that creates a SQLite database and a table named 'us.
Vulnerability Vector: The vulnerability in Ruby exists when improper sanitization and validation of us (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'sqlite3'
class User
attr_accessor :db
def initialize
@db = SQLite3::Database.new "users.db"
create_table_if_not_exists
end
def create_table_if_not_exists
query = <<-SQL
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
... | <think>
Target: ruby implementation for Write a ruby code that creates a SQLite database and a table named 'us.
Vulnerability Vector: The vulnerability in Ruby exists when improper sanitization and validation of us (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'sqlite3'
class User
attr_accessor :db
def initialize
@db = SQLite3::Database.new "users.db"
create_table_if_not_exists
end
def create_table_if_not_exists
query = <<-SQL
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
... | 362 | 0.79 |
cyber_d68a558a2bc4 | vulnerability_research_cve | CWE-787 | Write a java code that reads a file named 'file.txt' and prints its content to the console. | Target: java implementation for Write a java code that reads a file named 'file.txt' and prints its co.
Vulnerability Vector: A buffer overflow vulnerability in Java can occur when data is directly written (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) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line =... | <think>
Target: java implementation for Write a java code that reads a file named 'file.txt' and prints its co.
Vulnerability Vector: A buffer overflow vulnerability in Java can occur when data is directly written (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 {
byte[] data = new byte[1024];
int bytesRead;
try {
InputStream is = new FileInputStream("file.txt");
while ((bytesRead = is.read(data)) != -1) {
Sy... | 243 | 0.84 |
cyber_92ffd4bd7d29 | vulnerability_research_cve | CWE-20 | Write a swift code that converts Data into String using UTF-8 encoding and print the converted string. | Target: swift implementation for Write a swift code that converts Data into String using UTF-8 encoding.
Vulnerability Vector: Swift's `String` initialization from `Data` does not handle encoding correctly, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigatio... | ```swift
import Foundation
func convertToStringFromData(_ data: Data) -> String? {
if let string = String(data: data, encoding: .utf8) {
return string
} else {
print("Unable to convert data to string")
return nil
}
}
if let myData = "Hello, World!".data(using: .utf8) {
if let m... | <think>
Target: swift implementation for Write a swift code that converts Data into String using UTF-8 encoding.
Vulnerability Vector: Swift's `String` initialization from `Data` does not handle encoding correctly, (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
M... | ```swift
import Foundation
func convertToStringFromData(_ data: Data) -> String {
return String(data: data, encoding: .utf8)!
}
let myData = Data("Hello, World!".utf8)
let myString = convertToStringFromData(myData)
print(myString)
``` | 232 | 0.64 |
cyber_aefcbd640bfd | vulnerability_research_cve | CWE-476 | Write a kotlin code that creates an 'Account' class with a mutable property 'balance'. The 'deposit' function should add the given amount to the current balance. In the main function, create an instance of the 'Account' class and call the 'deposit' function with 100.0 as the argument. Then print the current balance. | Target: kotlin implementation for Write a kotlin code that creates an 'Account' class with a mutable pro.
Vulnerability Vector: The use of Kotlin's 'lateinit' keyword can lead to NullPointerExceptions if not (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
class Account(initialBalance: Double = 0.0) {
var balance: Double = initialBalance
private set
fun deposit(amount: Double) {
balance += amount
}
}
fun main() {
val account = Account()
account.deposit(100.0)
println(account.balance)
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that creates an 'Account' class with a mutable pro.
Vulnerability Vector: The use of Kotlin's 'lateinit' keyword can lead to NullPointerExceptions if not (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
class Account {
lateinit var balance: Double
fun deposit(amount: Double) {
balance += amount
}
}
fun main() {
val account = Account()
account.deposit(100.0)
println(account.balance)
}
``` | 211 | 0.72 |
cyber_0d07c242d387 | vulnerability_research_cve | CWE-787 | Write a fortran code that prints a string that is longer than the defined character length. | Target: fortran implementation for Write a fortran code that prints a string that is longer than the defi.
Vulnerability Vector: Buffer overflow vulnerability can occur when data is written beyond the end of a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
PROGRAM BUFFER_OVERFLOW
IMPLICIT NONE
CHARACTER(LEN=20) :: NAME
NAME = 'A STRING WITH MORE THAN 20 CHARS'
PRINT*, NAME
END PROGRAM BUFFER_OVERFLOW
``` | <think>
Target: fortran implementation for Write a fortran code that prints a string that is longer than the defi.
Vulnerability Vector: Buffer overflow vulnerability can occur when data is written beyond the end of a (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
PROGRAM BUFFER_OVERFLOW
IMPLICIT NONE
CHARACTER*20 NAME
NAME = 'A STRING WITH MORE THAN 20 CHARS'
PRINT*, NAME
END PROGRAM BUFFER_OVERFLOW
``` | 188 | 0.79 |
cyber_5905364caa75 | vulnerability_research_cve | CWE-20 | Write a php code that starts a session and checks if a username is set in the session. If it is, set a variable 'logged_in' to true. If not, set the username from a POST request to the session. | Target: php implementation for Write a php code that starts a session and checks if a username is set.
Vulnerability Vector: In PHP, improperly configured session management can lead to session hijacking o (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
session_start();
// Secure code starts here
if(isset($_SESSION['username'])) {
$logged_in = true;
}
else {
// Safe code here
if(isset($_POST['username']) && ctype_alnum($_POST['username'])){
$_SESSION['username'] = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
}
}
//... | <think>
Target: php implementation for Write a php code that starts a session and checks if a username is set.
Vulnerability Vector: In PHP, improperly configured session management can lead to session hijacking o (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
session_start();
// Vulnerable code starts here
if(isset($_SESSION['username'])) {
$logged_in = true;
}
else {
// Unsafe code here
$_SESSION['username'] = $_POST['username'];
}
// Vulnerable code ends here
?>
``` | 225 | 0.68 |
cyber_dffdc5e2e3ec | vulnerability_research_cve | CWE-78 | Write a go code that creates a new resource and defers its closing for 10 million times. After all resources have been created, sleep for 5 seconds. | Target: go implementation for Write a go code that creates a new resource and defers its closing for.
Vulnerability Vector: Go's garbage collector can lead to memory leaks if not handled properly. Unclose (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
"runtime/debug"
"sync"
"time"
)
type Resource struct {
data string
}
func NewResource() *Resource {
return &Resource{data: "some data"}
}
func (r *Resource) Close() {
fmt.Println("Closing resource...")
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10000000; i++ {... | <think>
Target: go implementation for Write a go code that creates a new resource and defers its closing for.
Vulnerability Vector: Go's garbage collector can lead to memory leaks if not handled properly. Unclose (CWE-78).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import (
"fmt"
"time"
)
type Resource struct {
data string
}
func NewResource() *Resource {
return &Resource{data: "some data"}
}
func (r *Resource) Close() {
fmt.Println("Closing resource...")
}
func main() {
for i := 0; i < 10000000; i++ {
resource := NewResource()
defer resource.Clo... | 329 | 0.67 |
cyber_46e994d783bd | vulnerability_research_cve | CWE-787 | Write a fortran code that assigns each character from a string 'overflow' to a character variable 'buffer' one by one until the buffer is full. | Target: fortran implementation for Write a fortran code that assigns each character from a string 'overfl.
Vulnerability Vector: A buffer overflow vulnerability exists when the programmer allocates too little (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=50) :: overflow
overflow = "This is an overflow string that will overflow the buffer"
do i = 1, len_trim(overflow)
buffer(i:i) = overflow(i:i)
end do
print*, buffer
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that assigns each character from a string 'overfl.
Vulnerability Vector: A buffer overflow vulnerability exists when the programmer allocates too little (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
integer :: i
character(len=10) :: buffer
character(len=50) :: overflow
overflow = "This is an overflow string that will overflow the buffer"
do i = 1, 50
buffer(i:i) = overflow(i:i)
end do
print*, buffer
end program main
``` | 196 | 0.86 |
cyber_42cf2484887e | vulnerability_research_cve | CWE-787 | Write a fortran code that takes a string 'Smith' and appends it to another string 'JohnSmith'. The result should be 'JohnSmithSmith'. | Target: fortran implementation for Write a fortran code that takes a string 'Smith' and appends it to ano.
Vulnerability Vector: Buffer Overflow Vulnerability in Fortran when handling strings and arrays withou (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=5) :: surname
character(len=10) :: fullname
integer :: i
surname = 'Smith'
fullname = 'John'
do i = 1, len_trim(surname)
fullname(i+4) = surname(i:i)
end do
print*, fullname
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that takes a string 'Smith' and appends it to ano.
Vulnerability Vector: Buffer Overflow Vulnerability in Fortran when handling strings and arrays withou (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=5) :: surname
character(len=10) :: fullname
integer :: i
surname = 'Smith'
fullname = 'JohnSmith'
do i = 1, len(surname)
fullname(i+5) = surname(i)
end do
print*, fullname
end program main
``` | 219 | 0.8 |
cyber_7c29a3003ab8 | vulnerability_research_cve | CWE-20 | Write a java code that uses Spring Boot framework. The code has two services, `UserService` and `AdminService`. Both services use the `UserRepository` to perform operations. `UserService` gets a user from the repository using the `getUser` method. It takes an ID as input and returns the corresponding user object. `Admi... | Target: java implementation for Write a java code that uses Spring Boot framework. The code has two se.
Vulnerability Vector: Incorrect use of Spring `@Autowired` annotation can lead to unintended dependenc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository... | <think>
Target: java implementation for Write a java code that uses Spring Boot framework. The code has two se.
Vulnerability Vector: Incorrect use of Spring `@Autowired` annotation can lead to unintended dependenc (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser(Long id) {
return userRepository.findById(id).orElseThrow();
}
}
@Ser... | 304 | 0.68 |
cyber_a3d74b31f4f3 | vulnerability_research_cve | CWE-20 | Write a c# code that prints 'HELLO WORLD' to the console. The string 'Hello World' should be stored in a dynamic variable and then converted to uppercase using the ToUpperCase() method. | Target: c# implementation for Write a c# code that prints 'HELLO WORLD' to the console. The string '.
Vulnerability Vector: The use of `dynamic` keyword in C# can lead to runtime binding errors. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Strategy: E... | ```c#
using System;
public class Program
{
public static void Main()
{
string d = "Hello World";
Console.WriteLine(d.ToUpper());
}
}
``` | <think>
Target: c# implementation for Write a c# code that prints 'HELLO WORLD' to the console. The string '.
Vulnerability Vector: The use of `dynamic` keyword in C# can lead to runtime binding errors. (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```c#
public class Program
{
public static void Main()
{
dynamic d = "Hello World";
Console.WriteLine(d.ToUpperCase());
}
}
``` | 165 | 0.73 |
cyber_f9755268d13d | vulnerability_research_cve | CWE-79 | Write a php code that checks if a name is passed through GET method. If a name is present, print 'Hello, [name]'. If no name is present, print 'Hello, Guest'. | Target: php implementation for Write a php code that checks if a name is passed through GET method. I.
Vulnerability Vector: Incorrect use of `$_GET` and `$_POST` superglobals can lead to Cross-Site Script (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
if(isset($_GET['name']) && ctype_alpha($_GET['name'])) {
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_STRING);
echo 'Hello, '.htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
} else {
echo 'Hello, Guest';
}
?>
``` | <think>
Target: php implementation for Write a php code that checks if a name is passed through GET method. I.
Vulnerability Vector: Incorrect use of `$_GET` and `$_POST` superglobals can lead to Cross-Site Script (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
if(isset($_GET['name'])) {
echo 'Hello, '.$_GET['name'];
} else {
echo 'Hello, Guest';
}
?>
``` | 213 | 0.56 |
cyber_39c917257644 | vulnerability_research_cve | CWE-787 | Write a swift code that prints out characters from a given string starting from a specific index to another specific index. | Target: swift implementation for Write a swift code that prints out characters from a given string star.
Vulnerability Vector: Potential buffer overflow vulnerability in Swift due to lack of bound checking o (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```swift
import Foundation
func printCharacters(from startIndex: Int, to endIndex: Int, fromString string: String) {
let characters = Array(string)
let safeEndIndex = min(endIndex, characters.count - 1)
var index = max(startIndex, 0)
while index <= safeEndIndex {
print(characters[index]) Hawkin... | <think>
Target: swift implementation for Write a swift code that prints out characters from a given string star.
Vulnerability Vector: Potential buffer overflow vulnerability in Swift due to lack of bound checking o (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```swift
import Foundation
func printCharacters(from startIndex: Int, to endIndex: Int, fromString string: String) {
let characters = Array(string)
var index = startIndex
while index < endIndex {
print(characters[index])
index += 1
}
}
let sampleString = "Hello, World!"
printCharacters... | 246 | 0.75 |
cyber_b7a2cfb02294 | vulnerability_research_cve | CWE-787 | Write a go code that takes a long string and truncates it to a maximum length without checking its length first. Print out the truncated string. | Target: go implementation for Write a go code that takes a long string and truncates it to a maximum.
Vulnerability Vector: In Go, a buffer overflow vulnerability can occur in situations where a string sl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"fmt"
"strings"
) constrained by
func main() {
input := "This is a long string that will cause a buffer overflow if not checked properly."
maxLength := 50
// Check the length of the input string before slicing
if len(input) > maxLength {
input = strings.TrimSpace(input[:maxLength... | <think>
Target: go implementation for Write a go code that takes a long string and truncates it to a maximum.
Vulnerability Vector: In Go, a buffer overflow vulnerability can occur in situations where a string sl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"strings"
)
func main() {
input := "This is a long string that will cause a buffer overflow if not checked properly."
maxLength := 50
// Vulnerability: No check for string length before slicing
truncatedInput := input[:maxLength]
fmt.Println(truncatedInput)
}
``` | 226 | 0.77 |
cyber_73c41c3d67c0 | vulnerability_research_cve | CWE-89 | Write a ruby code that connects to a PostgreSQL database named 'test', searches for a user in the 'users' table where the username matches the input parameter, and prints out each matching row. | Target: ruby implementation for Write a ruby code that connects to a PostgreSQL database named 'test',.
Vulnerability Vector: Ruby code may suffer from SQL injection if raw SQL queries are used without para (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation... | ```ruby
require 'pg'
def search_user(username)
conn = PG.connect(dbname: 'test')
conn.prepare('select_user', "SELECT * FROM users WHERE username = $1")
res = conn.exec_prepared('select_user', [username])
res.each do |row|
puts row
end
ensure
conn.close if conn
end
search_user("test' OR '1'='1")
``` | <think>
Target: ruby implementation for Write a ruby code that connects to a PostgreSQL database named 'test',.
Vulnerability Vector: Ruby code may suffer from SQL injection if raw SQL queries are used without para (CWE-89).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mi... | ```ruby
require 'pg'
def search_user(username)
conn = PGconn.connect(:dbname => 'test')
res = conn.exec("SELECT * FROM users WHERE username = '#{username}'")
res.each do |row|
puts row
end
ensure
conn.close if conn
end
search_user("test' OR '1'='1")
``` | 224 | 0.76 |
cyber_45f5073e891e | vulnerability_research_cve | CWE-20 | Write a c# code that reads a text file and prints its content on the console. If there's an error while reading the file, it should print an error message. | Target: c# implementation for Write a c# code that reads a text file and prints its content on the c.
Vulnerability Vector: Improper error handling and logging of exception details could potentially expos (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 MyClass
{
public void ReadFile(string filePath)
{
try
{
string text = File.ReadAllText(filePath);
Console.WriteLine(text);
}
catch (IOException ex)
{
// Log the exception details
... | <think>
Target: c# implementation for Write a c# code that reads a text file and prints its content on the c.
Vulnerability Vector: Improper error handling and logging of exception details could potentially expos (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
using System.IO;
public class MyClass
{
public void ReadFile(string filePath)
{
try
{
string text = File.ReadAllText(filePath);
Console.WriteLine(text);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Mess... | 313 | 0.55 |
cyber_977740b02693 | vulnerability_research_cve | CWE-787 | Write a go code that takes user input, converts it into a command and executes it. If the command is invalid, print an error message. | Target: go implementation for Write a go code that takes user input, converts it into a command and .
Vulnerability Vector: Improper handling of user inputs or untrusted data can lead to buffer overflows (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter your command:")
input, _ := reader.ReadString('\n')
input = strings.TrimSuffix(input, "\n")
err := validateInput(input)
if err != nil {
fmt.Println("Invalid... | <think>
Target: go implementation for Write a go code that takes user input, converts it into a command and .
Vulnerability Vector: Improper handling of user inputs or untrusted data can lead to buffer overflows (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os/exec"
)
func main() {
var input string
fmt.Println("Enter your command:")
fmt.Scan(&input)
cmd := exec.Command(input)
err := cmd.Run()
if err != nil {
fmt.Println("Error:", err)ivalid command)
}
}
``` | 368 | 0.47 |
cyber_eb0cdf94d0b8 | vulnerability_research_cve | CWE-20 | Write a fortran code that prints an uninitialized variable 'x'. | Target: fortran implementation for Write a fortran code that prints an uninitialized variable 'x'..
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected results or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation Str... | ```fortran
program main
implicit none
integer :: x
x = 0 ! Initializing the variable 'x'
print *, "x = ", x
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that prints an uninitialized variable 'x'..
Vulnerability Vector: The use of uninitialized variables in Fortran can lead to unexpected results or (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
integer :: x
print *, "x = ", x
end program main
``` | 152 | 0.68 |
cyber_857adb2e69c3 | vulnerability_research_cve | CWE-476 | Write a kotlin code that prints the name of a user. If the user does not exist, it should print 'No user found'. The user object is retrieved from a function called 'getUser' which returns null if no user exists. | Target: kotlin implementation for Write a kotlin code that prints the name of a user. If the user does n.
Vulnerability Vector: NullPointerException due to not checking for null values before accessing them. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigati... | ```kotlin
fun main(args: Array<String>) {
val user: User? = getUser()
if (user != null) {
println(user.name)
} else {
println("No user found")
}
}
class User(val name: String)
fun getUser(): User? {
return null
}
``` | <think>
Target: kotlin implementation for Write a kotlin code that prints the name of a user. If the user does n.
Vulnerability Vector: NullPointerException due to not checking for null values before accessing them. (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
... | ```kotlin
fun main(args: Array<String>) {
val user: User? = getUser()
println(user.name) // This will lead to NullPointerException if getUser() returns null
}
class User(val name: String)
fun getUser(): User? {
return null
}
``` | 203 | 0.75 |
cyber_e68aa4e79090 | vulnerability_research_cve | CWE-787 | Write a fortran code that reads a surname and a name from the user, then prints a greeting message including the surname and name. | Target: fortran implementation for Write a fortran code that reads a surname and a name from the user, th.
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitiga... | ```fortran
program main
implicit none
character(len=100) :: surname
character(len=100) :: name
read(*,'(A)') surname
read(*,'(A)') name
print*, "Hello, ", trim(surname), " ", trim(name), "!"
end program main
``` | <think>
Target: fortran implementation for Write a fortran code that reads a surname and a name from the user, th.
Vulnerability Vector: Potential buffer overflow vulnerability due to insufficient memory allocation fo (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation... | ```fortran
program main
implicit none
character(len=3) :: surname
character(len=4) :: name
read(*,*) surname, name
print*, "Hello, ", trim(surname), " ", trim(name), "!"
end program main
``` | 194 | 0.74 |
cyber_f3dfd75a68d2 | vulnerability_research_cve | CWE-79 | Write a javascript code that gets the value from an HTML input element with id 'userInput' and displays it on the webpage. | Target: javascript implementation for Write a javascript code that gets the value from an HTML input element.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities allow malicious scripts to be injecte (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
function getUserInput() {
var userInput = document.getElementById('userInput').value;
return encodeURIComponent(userInput);
}
function displayUserInput() {
var userInput = getUserInput();
var div = document.createElement("div");
div.textContent = decodeURIComponent(userInput);
doc... | <think>
Target: javascript implementation for Write a javascript code that gets the value from an HTML input element.
Vulnerability Vector: Cross-Site Scripting (XSS) vulnerabilities allow malicious scripts to be injecte (CWE-79).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
function getUserInput() {
var userInput = document.getElementById('userInput').value;
return userInput;
}
function displayUserInput() {
var userInput = getUserInput();
document.write(userInput);
}
displayUserInput();
``` | 210 | 0.68 |
cyber_e804ef095197 | vulnerability_research_cve | CWE-787 | Write a c# code that handles an HTTP request and retrieves a query string parameter named 'input'. The code then reads each character from the input string and stores them in a character array. If the length of the input string exceeds the size of the buffer array, it will cause a buffer overflow. Finally, the code con... | Target: c# implementation for Write a c# code that handles an HTTP request and retrieves a query str.
Vulnerability Vector: Potential buffer overflow vulnerability in the handling of untrusted input from (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.Web;
using System.Web.UI;ViewById;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["input"];
if (!string.IsNullOrEmpty(userInput)... | <think>
Target: c# implementation for Write a c# code that handles an HTTP request and retrieves a query str.
Vulnerability Vector: Potential buffer overflow vulnerability in the handling of untrusted input from (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string userInput = Request.QueryString["input"];
char[] buffer = new char[10];
for (in... | 314 | 0.75 |
cyber_25a59d32340c | vulnerability_research_cve | CWE-20 | Write a php code that retrieves a page name from the URL parameter 'page', then includes the corresponding .php file. | Target: php implementation for Write a php code that retrieves a page name from the URL parameter 'pa.
Vulnerability Vector: The use of unsanitized user input in the 'include' function can lead to remote f (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```php
<?php
// Define an array of allowed pages
$allowedPages = ['home', 'about', 'contact'];
// Get the page name from the URL parameter 'page'
$requestedPage = $_GET['page'] ?? '';
// Sanitize the page name to prevent any path traversal attacks
$sanitizedPage = basename($requestedPage);
// Check if the requested ... | <think>
Target: php implementation for Write a php code that retrieves a page name from the URL parameter 'pa.
Vulnerability Vector: The use of unsanitized user input in the 'include' function can lead to remote f (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```php
<?php
$file = $_GET['page'];
include($file . '.php');
?>
``` | 288 | 0.34 |
cyber_624e95c8bce2 | vulnerability_research_cve | CWE-787 | Write a go code that takes an input from the user and stores it in a buffer. If the input length is less than the buffer size, store each character of the input into the buffer. Print out the content of the buffer. | Target: go implementation for Write a go code that takes an input from the user and stores it in a b.
Vulnerability Vector: There could be a potential buffer overflow vulnerability when reading from a use (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your input: ")
input, _ := reader.ReadString('\n')
buffer := []byte(input)
fmt.Println("Buffer content:", string(buffer))
}
``` | <think>
Target: go implementation for Write a go code that takes an input from the user and stores it in a b.
Vulnerability Vector: There could be a potential buffer overflow vulnerability when reading from a use (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```go
package main
import (
"fmt"
"os"
)
func main() {
var input string
fmt.Println("Enter your input:")
fmt.Scan(&input)
buffer := make([]byte, 1024)
for i := 0; i < len(input); i++ {
if i < len(buffer) {
buffer[i] = input[i]
}
}
fmt.Println("Buffer content:", string(buffer))
}
``` | 208 | 0.99 |
cyber_ff855d19cf23 | vulnerability_research_cve | CWE-787 | Write a python code that uses Flask to create a web server that listens on port 8000. The server should have one route '/echo' that accepts POST requests. When a POST request is received at this route, it should extract the 'data' field from the request and return a string 'Echo: [data]'. | Target: python implementation for Write a python code that uses Flask to create a web server that listen.
Vulnerability Vector: Potential buffer overflow vulnerability in Python due to unchecked user input si (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```python
from flask import Flask, request, abort
app = Flask(__name__)
@app.route('/echo', methods=['POST'])
def echo():
if 'data' not in request.form:
abort(400, "Missing 'data' field in POST request.")
data = request.form['data']
# Limit the length of the data to prevent buffer overflo... | <think>
Target: python implementation for Write a python code that uses Flask to create a web server that listen.
Vulnerability Vector: Potential buffer overflow vulnerability in Python due to unchecked user input si (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/echo', methods=['POST'])
def echo():
data = request.form['data']
return f"Echo: {data}"
if __name__ == '__main__':
app.run(port=8000)
``` | 304 | 0.52 |
cyber_92b1c2b7c07b | vulnerability_research_cve | CWE-476 | Write a kotlin code that defines a function named 'getStringLength' which takes a nullable string as an argument. The function should return the length of the string. If the string is null, the function should throw a NullPointerException. | Target: kotlin implementation for Write a kotlin code that defines a function named 'getStringLength' wh.
Vulnerability Vector: A possible security vulnerability in Kotlin could be through its handling of nul (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigat... | ```kotlin
// This is a simple function that takes a string as input and returns its length
fun getStringLength(myString: String?): Int? {
return myString?.length // This line will return null if myString is null
}
// This is how you would call this function
println(getStringLength(null)) // This will return null
`... | <think>
Target: kotlin implementation for Write a kotlin code that defines a function named 'getStringLength' wh.
Vulnerability Vector: A possible security vulnerability in Kotlin could be through its handling of nul (CWE-476).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.... | ```kotlin
// This is a simple function that takes a string as input and returns its length
fun getStringLength(myString: String?): Int {
return myString.length // This line will throw a NullPointerException if myString is null
}
// This is how you would call this function
println(getStringLength(null)) // This wil... | 192 | 0.84 |
cyber_c7beff26bd4e | vulnerability_research_cve | CWE-20 | Write a c# code that reads an integer from the console, converts it into an integer and prints it out. If the input is not a valid integer or if the number is too large/small, it should print an appropriate error message. | Target: c# implementation for Write a c# code that reads an integer from the console, converts it in.
Vulnerability Vector: A potential security risk in C# is improper handling of exceptions, which might (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```c#
using System;
class Program
{
static void Main()
{
try
{
string input = Console.ReadLine();
int number = int.Parse(input);
Console.WriteLine("You entered: " + number);
}
catch (FormatException)
{
Console.WriteLine("Inv... | <think>
Target: c# implementation for Write a c# code that reads an integer from the console, converts it in.
Vulnerability Vector: A potential security risk in C# is improper handling of exceptions, which might (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```c#
using System;
class Program
{
static void Main()
{
try
{
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.WriteLine("You entered: " + number);
}
catch (FormatException)
{
Console.WriteLin... | 265 | 0.87 |
cyber_1da8af710704 | vulnerability_research_cve | CWE-20 | Write a javascript code that simulates a timing attack vulnerability. The code should have a function `checkKey` which takes a key as an argument and checks if it matches the secret key. If it does, it calculates the time taken to perform the check and logs it. The `attack` function tries to guess the secret key by cal... | Target: javascript implementation for Write a javascript code that simulates a timing attack vulnerability. .
Vulnerability Vector: A timing attack vulnerability in JavaScript could allow an attacker to guess the (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```javascript
// This is a secure optimized version of a timing attack vulnerability
const crypto = require('crypto');
let secretKey = "mySecretKey";
let hashKey = crypto.createHash('sha256').update(secretKey).digest('hex');
function checkKey(key) {
let startTime = Date.now();
let hashedKey = crypto.createHas... | <think>
Target: javascript implementation for Write a javascript code that simulates a timing attack vulnerability. .
Vulnerability Vector: A timing attack vulnerability in JavaScript could allow an attacker to guess the (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutati... | ```javascript
// This is a simplified version of a timing attack vulnerability
let secretKey = "mySecretKey";
function checkKey(key) {
let startTime = Date.now();
if (key === secretKey) {
let endTime = Date.now();
console.log("Time taken: ", endTime - startTime);
return true;
}
... | 375 | 0.77 |
cyber_9aebf7778ad8 | vulnerability_research_cve | CWE-787 | Write a c# code that reads data from a serial port (COM1 at 9600 baud rate), increments each byte read by one and then prints out the modified data. | Target: c# implementation for Write a c# code that reads data from a serial port (COM1 at 9600 baud .
Vulnerability Vector: A potential buffer overflow vulnerability in the `System.IO.Ports.SerialPort` cl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation ... | ```c#
using System;
using System.IO.Ports;
public class Program
{
static void Main()
{
try
{
using (var serialPort = new SerialPort("COM1", 9600))
{
serialPort.Open();
byte[] buffer = new byte[256];
int bytesRead = serialP... | <think>
Target: c# implementation for Write a c# code that reads data from a serial port (COM1 at 9600 baud .
Vulnerability Vector: A potential buffer overflow vulnerability in the `System.IO.Ports.SerialPort` cl (CWE-787).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mit... | ```c#
using System;
using System.IO.Ports;
public class Program
{
static void Main()
{
SerialPort serialPort = new SerialPort("COM1", 9600);
byte[] buffer = new byte[256];
int bytesRead = serialPort.Read(buffer, 0, 256);
unsafe
{
fixed (byte* ptr = buffer)
... | 340 | 0.81 |
cyber_f74185bbd647 | vulnerability_research_cve | CWE-20 | Write a go code that prints the second character of the string 'hello'. The output should be 'e', not '101'. | Target: go implementation for Write a go code that prints the second character of the string 'hello'.
Vulnerability Vector: Go's string type is a read-only slice of bytes and it doesn't have a character t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Mitigation S... | ```go
package main
import (
"fmt"
)
func main() {
str := "hello"
fmt.Printf("%c\n", str[1]) // This will print 'e'
}
``` | <think>
Target: go implementation for Write a go code that prints the second character of the string 'hello'.
Vulnerability Vector: Go's string type is a read-only slice of bytes and it doesn't have a character t (CWE-20).
Root Cause: Missing bounds verification or improper memory handling prior to state mutation.
Miti... | ```go
package main
import "fmt"
func main() {
str := "hello"
fmt.Println(str[1]) // This will print 101 instead of 'e'
}
``` | 166 | 0.75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.