FlawOpen

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 नहीं करता।

असुरक्षित — input को SQL में interpolate करना
stmt = text(
  f"SELECT id FROM users WHERE id = {user_id}"
)
rows = conn.execute(stmt)
सुरक्षित — मान bind करें और SQL संरचना सीमित करें
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' .

अक्सर पूछे जाने वाले प्रश्न

क्या SQLAlchemy Core और ORM query builders हमेशा सुरक्षित हैं?

सामान्य expression निर्माण में वे Python मान bind करते हैं, लेकिन सुरक्षा इस पर निर्भर करती है कि statement कैसे बनाया गया है। Textual SQL, literal SQL constructs और dynamic identifiers भी जाँचें। Input जोड़ने के बाद कोई API SQL string को सुरक्षित नहीं बना सकती।

स्रोत

यह भी देखें SQL इंजेक्शन (CWE-89): यह कैसे काम करता है और हर भाषा में इसे कैसे रोकें — flawopen.com क्या sqlx की compile-time query जाँच SQL injection रोकती है? क्या stored procedures SQL injection से सुरक्षित हैं? क्या TypeORM QueryBuilder SQL Injection से सुरक्षित है? Django ORM और SQL Injection: सुरक्षित तरीके Doctrine ORM में SQL Injection: सुरक्षित queries EF Core FromSqlRaw: सुरक्षित पैरामीटरयुक्त SQL