flawopen.com/Python में SQL Injection/SQLAlchemy
क्या SQLAlchemy text() SQL Injection से सुरक्षित है?
Bound parameter को query form में sealed value card की तरह समझें: SQLAlchemy SQL statement और उसका parameter mapping underlying DBAPI को देता है, जिससे मान आपके code द्वारा बनाए गए SQL expression में शामिल नहीं होते। DBAPI driver database-specific binding संभालता है, इसलिए wire पर भेजने का तरीका अलग हो सकता है। text() SQL text स्वीकार करता है, लेकिन उसमें पहले से interpolate किए गए मानों को sanitize या parameterize नहीं करता।
stmt = text(
f"SELECT id FROM users WHERE id = {user_id}"
)
rows = conn.execute(stmt)
stmt = text(
"SELECT id FROM users WHERE id = :id"
)
rows = conn.execute(stmt, {"id": user_id})
# Bind values, not identifiers. Choose any
# selectable column from a fixed application map.
columns = {"name": users.c.name,
"created": users.c.created_at}
column = columns.get(requested_sort, users.c.created_at)
stmt = select(users.c.id).order_by(column)
rows = conn.execute(stmt)
text() क्या करता है — और क्या नहीं
text() textual SQL construct बनाता है; यह पहले से interpolated input वाली string को साफ़ नहीं करता। SQL में value placeholders घोषित करें और मानों को Connection.execute() या Session.execute() में अलग दें। SQLAlchemy Core expression API उपयुक्त स्थानों पर Python literal values bind करता है, लेकिन textual fragments SQL syntax ही रहते हैं। Parameters table names, column names या sort directions की जगह नहीं ले सकते। उपयोगकर्ता द्वारा चुनी संरचना को निश्चित SQLAlchemy expressions से map करें। Parameterization SQL Injection रोकता है, पर authorization या business-rule validation का विकल्प नहीं है।
कोडबेस की जाँच कैसे करें
rg -n 'text\(|\.execute\(' --glob '*.py' .अक्सर पूछे जाने वाले प्रश्न
सामान्य expression निर्माण में वे Python मान bind करते हैं, लेकिन सुरक्षा इस पर निर्भर करती है कि statement कैसे बनाया गया है। Textual SQL, literal SQL constructs और dynamic identifiers भी जाँचें। Input जोड़ने के बाद कोई API SQL string को सुरक्षित नहीं बना सकती।
स्रोत
- SQLAlchemy 2.0 ट्यूटोरियल — Parameters भेजना
- SQLAlchemy 2.0 ट्यूटोरियल — SQL Expressions और textual SQL
- OWASP — SQL Injection रोकथाम मार्गदर्शिका
- flawopen.com — Python में SQL Injection