728x90
1. 개요
Server 로 쿼리 요청을 통해서 Database 의 접근을 하는 경우 Sql Injection 이 발생할 수 있는 위험성이 있다.
이를 해결하는 방법으로 Prepared Statement를 구성하고 입력받은 value 값에 injection 이 들어가서 sql 쿼리의 명령에서 원치 않는 동작이 발생되는 것을 방지한다.
2. Python 구현
Flask 서버를 사용하여 PD를 구현하였다. 우선 get 쿼리를 통해 id와 pw 를 얻고 이를 PD를 적용하여 sql query 를 수행하도록한다.
#Prepared Statement test
@app.route('/psapi', methods=['GET'])
def handlePSApi():
param_id = request.args.get('id')
param_pw = request.args.get('pw')
return sqlConnectTest(param_id, param_pw)
from mysql.connector import connect
def sqlConnectTest(id, pw):
# Connect to the database
db = connect(
host="localhost",
user="server_username",
password="server_password",
database="mydatabase"
)
# Define the query with parameters
query = "SELECT * FROM users WHERE username = %s AND passwd = %s"
# Prepare the statement
cursor = db.cursor(prepared=True)
cursor.execute(query, (id, pw))
# Fetch the results
result = cursor.fetchall()
# Display the results
for row in result:
print(row)
# Close the statement and database connection
cursor.close()
db.close()
if len(result) > 0:
return 'Hello ' + id
else:
return 'Not found ' + id
if __name__ == "__main__":
sqlConnectTest("db_user","db_passwd")
3. Javascript 구현
Node.js 서버에서 javascript를 이용하여 PD를 구현한다.
// Import the mysql2 library
const mysql = require('mysql2/promise');
// Create a connection pool to the database
const pool = mysql.createPool({
host: 'localhost',
user: 'username',
password: 'password',
database: 'mydatabase',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Define the query with parameters
const query = "SELECT * FROM users WHERE username = ? AND password = ?";
// Execute the prepared statement with parameters
const [rows, fields] = await pool.execute(query, ['john_doe', 'my_password']);
// Display the results
console.log(rows);
4. PHP 구현
아파치 서버에서 php 스크립트를 이용하여 PD를 구현한다.
// Connect to the database
$dbh = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Define the query with named parameters
$sql = "SELECT * FROM users WHERE username = :username AND password = :password";
// Prepare the statement
$stmt = $dbh->prepare($sql);
// Bind the values to the named parameters
$stmt->bindValue(':username', $_GET['username']);
$stmt->bindValue(':password', $_GET['password']);
// Execute the statement
$stmt->execute();
// Fetch the results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the results
foreach($result as $row) {
echo $row['username'] . " " . $row['email'] . "<br>";
}
// Close the statement and database connection
$stmt = null;
$dbh = null;
728x90
728x90