-1

Below is a part of my python/pymysql code. I'm basically trying to retrieve data from a database using the input typed into a search box. I don't understand why the data typed in is coming across with this error. "Ihe" is simply a test hostname in my the database.

 @app.route('/result',methods= ['POST', 'GET'])
    def result():
            if request.method == 'POST':
                    result = request.form['hostname']
                    cursor = connection.cursor()
                    query = ("SELECT * FROM StoryData WHERE hostName LIKE %s" %  ( result))
                    cursor.execute(query)
                    search_for = cursor.fetchall()
                    for row in search_for:
                            ID = row['ID']
                            hName = row['hostName']
                            rName = row['reportName']

                    return render_template("result.html", search_for=search_for)
                    connection.close()
Taras Tataryn
  • 21
  • 1
  • 8
  • 1
    the query is incorrect. you need to quote the `LIKE` parameter, like so: `"SELECT * FROM StoryData WHERE hostName LIKE '%s'" % ( result)` EDIT: Since the `result` parameter is coming from the request, this API endpoint is open to SQL injection attacks. You might want to consider protecting against this, by using an ORM or using other techniques – Chitharanjan Das Jun 19 '17 at 15:01
  • 1
    Possible duplicate of [PyMySQL variables in queries](https://stackoverflow.com/questions/37094159/pymysql-variables-in-queries) – ivan_pozdeev Jun 19 '17 at 15:03

1 Answers1

1

As written, this is a very dangerous SQL Injection vulnerability.

What happens when I submit a POST request with hostname set to

''; DROP TABLE StoryData;

?


Use parameterized queries instead of using Python string formatting. Assuming your paramstyle is format, you can pass the parameters to execute():

query = "SELECT * FROM StoryData WHERE hostName LIKE %s"
cursor.execute(query, (result, ))
Jacob Krall
  • 28,341
  • 6
  • 66
  • 76