Is DB::raw in insert method vulnerable to SQL Injection?

Viewed 533

I have a simplified code like this in Laravel:

$uid = $request->input('uid');
DB::table('users')->insert([
    'uid' => DB::raw("CONV('$uid', 16, 10)"),
    'created_at' =>  date("Y-m-d H:i:s")
]);

Is my code vulnerable to SQL Injection attack? And Why? If so, how can I prevent it?

2 Answers

Yes, it's vulnerable to SQL Injection since the raw content of $uid will be injected to your sql query.

Although DB::raw() accepts prepared parameters, it cannot be used inside the insert method correctly.

To do that, you will need to write the insert query manually:

$uid = $request->input('uid');

DB::statement('INSERT INTO users (uid, created_at) VALUES (CONV(?, 16, 10), ?)', [
    $uid,
    date("Y-m-d H:i:s")
]);

Yes, copying a request input directly into your raw SQL query is an example of an SQL injection vulnerability.

I suggest this alternative:

$uid = base_convert($request->input('uid'), 16, 10);
DB::table('users')->insert([
    'uid' => $uid,
    'created_at' =>  date("Y-m-d H:i:s")
]);

See base_convert().


Related