Skip to content

Commit bc96aa5

Browse files
committed
fix(security): Sanitize fields list, group_by and order_by clause to prevent SQLi
1 parent 7b19d55 commit bc96aa5

1 file changed

Lines changed: 13 additions & 2 deletions

File tree

frappe/model/db_query.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,12 @@ def build_and_run(self):
111111
if self.distinct:
112112
args.fields = 'distinct ' + args.fields
113113

114-
query = """select %(fields)s from %(tables)s %(conditions)s
115-
%(group_by)s %(order_by)s %(limit)s""" % args
114+
query = """select %(fields)s
115+
from %(tables)s
116+
%(conditions)s
117+
%(group_by)s
118+
%(order_by)s
119+
%(limit)s""" % args
116120

117121
return frappe.db.sql(query, as_dict=not self.as_list, debug=self.debug, update=self.update)
118122

@@ -234,6 +238,11 @@ def _is_query(field):
234238

235239
_is_query(field)
236240

241+
if re.compile(r".*/\*.*").match(field):
242+
frappe.throw(_('Illegal SQL Query'))
243+
244+
if re.compile(r".*\s(union).*\s").match(field.lower()):
245+
frappe.throw(_('Illegal SQL Query'))
237246

238247
def extract_tables(self):
239248
"""extract tables from fields"""
@@ -635,6 +644,8 @@ def validate_order_by_and_group_by(self, parameters):
635644
if 'select' in _lower and ' from ' in _lower:
636645
frappe.throw(_('Cannot use sub-query in order by'))
637646

647+
if re.compile(r".*[^a-z0-9-_ ,`'\"\.\(\)].*").match(_lower):
648+
frappe.throw(_('Illegal SQL Query'))
638649

639650
for field in parameters.split(","):
640651
if "." in field and field.strip().startswith("`tab"):

0 commit comments

Comments
 (0)