[CentralOH] 2014-11-14 道場 Scribbles: Injection Attacks

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Mon Nov 17 15:55:41 CET 2014


This stuff just keeps coming up.

    <heavy sarcasm>
    Enhance your career by writing code vulnerable to an SQL injection attack!
    <heavy sarcasm/>

General case:

    http://en.wikipedia.org/wiki/Code_injection

    One must develop a general sense about injection attacks
    and just not allow them, ever. Always use the invulnerable form.

Python:

    exec() gives me the creeps.

SQL:

    http://en.wikipedia.org/wiki/SQL_injection

    http://www.darkreading.com/attacks-breaches/yet-another-security-firm-breached--employee-email-user-accounts-leaked/d/d-id/1135536
    https://www.riskbasedsecurity.com/2014/04/sql-injection-leads-to-bigmoneyjobs-com-leak/
    http://www.out-law.com/en/articles/2014/november/fine-should-prompt-businesses-to-address-threat-of-sql-injection-attacks-says-ico/
    http://www.scmagazine.com/seventeen-companies-including-banks-and-retailers-named-as-victims-in-hacker-campaign/article/304605/

Thanks to Randall Monroe

    http://xkcd.com/327/
    http://www.explainxkcd.com/wiki/index.php/327:_Exploits_of_a_Mom
    http://bobby-tables.com/

It's easy to do wrong in Python. For example:

    query_parameters = {
        'column_name': 'id FROM students; DROP TABLE students; SELECT id ',
        'table_name': 'students',
    }
    query = 'SELECT %(column_name)s FROM %(table_name)s' % query_parameters
    print query
    # cursor.execute(query)

    >>> if True:
    ...     query_parameters = {
    ...         'column_name': 'id FROM students; DROP TABLE students; SELECT id ',
    ...         'table_name': 'students',
    ...     }
    ...     query = 'SELECT %(column_name)s FROM %(table_name)s' % query_parameters
    ...     print query
    ...
    SELECT id FROM students; DROP TABLE students; SELECT id  FROM students
    >>>

It's also easy to do right in Python:

    query_parameters = (
        'id FROM students; DROP TABLE students; SELECT id ',
        'students',
    )
    query = 'SELECT ? FROM ?'
    cursor.execute(query, query_parameters)

It's so easy to do right, there's no excuse for doing it wrong.

Again, see http://downloads.egenix.com/python/EPC-2008-Using-the-Python-Database-API.pdf, especially page 17.

Some ORMs protect you automatically. However, if you have access to raw SQL in
your ORM, then your database is vulnerable.

--------------------------------------------------------------------------------

Premature optimization is the root of all evil.

First, write for clarity. If the code is not fast enough, then measure to find
out which part of the code is too slow and optimize that part.

--------------------------------------------------------------------------------

Start with examples of input and output for TDD.

MySQL & Oracle kick PostGIS' posterior.
https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#compatibility-tables

Not.

Batteries are tempermental. Be gentle to them.

    http://www.wikihow.com/Extend-Your-Li-Ion-Dell-XPS-M1210-Laptop-Battery-Life
    http://batteryuniversity.com/learn/article/how_to_prolong_lithium_based_batteries

Someone showed up who uses Microsoft Windows.

    What's best way to install both Python 2(.7) _and_ 3(.4) on Windows _with_
    Ipython _and_ virtualenv? It's easy to find answers for any one piece, but
    not for all of them together.

        Canopy (formerly EPD) is only for 2.7

        https://www.python.org/downloads/windows/
            https://www.python.org/ftp/python/3.4.2/python-3.4.2.amd64.msi
            https://www.python.org/ftp/python/2.7.8/python-2.7.8.amd64.msi

        http://ipython.org/ipython-doc/stable/install/install.html
        http://ipython.org/install.html

I code, therefore I am.

wp:James Burke (science historian)
wp:Connections (TV series)

stupid unicode fun:

    try:
        1 › 0
    except:
        print u'nuts'
    else:
        print u'ok'

wp:Friendly_Floatees
wp:Moby-Duck

What is your favorite color?

    wp:Monty Python and the Holy Grail

http://learnpythonthehardway.org/

    Zed Shaw needs help:

    Should use print functions instead of print statements.

http://www.meetup.com/girldevelopitcbus/events/214700282/

Notebook viewer can render notebooks at arbitrary URLs. For example,
http://nbviewer.ipython.org/url/colug.net/python/dojo/20140117/word-count-example-rev2.ipynb

http://catb.org/esr/writings/cathedral-bazaar/

http://www.codingame.com/

Someone who smashes tiny things into teensier things needs to see a demo of:
https://github.com/brandon-rhodes/astronomy-notebooks

running sum

    What's the Pythonic way of doing a running sum? How about in balance.py?

http://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
http://stackoverflow.com/questions/1790550/running-average-in-python

to your health
wp:Bénédictine
wp:Benedictine Sisters
wp:Avera Health

Chet Atkins & Les Paul - Chester & Lester

http://xkcd.com/1110/ has a _large_ image.

As usual, wp: prefix means Wikipedia.

------------------------------------------------------------------------

Now for some refactoring.

[jjj at dojo ~]$ head -999 balance.py 
'''
What do you like about the various quantify_parens()?
What do you dislike about the various quantify_parens()?
What do you like about the various parens_are_balanced()?
What do you dislike about the various parens_are_balanced()?
What do you think about the last sum_ = 0 for doing nothing gracefully?
'''

from __future__ import print_function 
import operator

def quantify_parens(s):
    return [{'(': +1, ')': -1}[c] if c in {'(': +1, ')': -1} else 0 for c in s]

def quantify_parens(s):
    weights = {'(': +1, ')': -1}
    return [weights[c] if c in weights else 0 for c in s]

def quantify_parens(s):
    weights = {'(': +1, ')': -1}
    for c in s:
        try:
            weight = weights[c]
        except KeyError:
            weight = 0
        yield weight

def quantify_parens(s):
    weights = {'(': +1, ')': -1}
    for c in s:
        try:
            weight = weights[c]
        except KeyError:
            pass
        else:
            yield weight

def quantify_parens(s):
    weights = {'(': +1, ')': -1}
    for c in s:
        if c in weights:
            yield weights[c]

def parens_are_balanced(s):
    sum_ = 0
    for x in quantify_parens(s):
        sum_ += x
        if sum_ < 0:
            return False
    return sum_ == 0

def running_op(iterable, op=operator.add, initial=0):
    running_result = initial
    for element in iterable:
        running_result = op(running_result, element)
        yield running_result

def running_sum(iterable, initial=0):
    sum_ = initial
    for element in iterable:
        sum_ += element
        yield sum_

def parens_are_balanced(s):
    n = n_unmatched_left_parentheses = 0
    for n in running_sum(quantify_parens(s)):
        if n < 0:
            return False
    return n == 0

def main():
    strings = [
        '',
        'hello world',
        '(',
        ')',
        '()',
        '((())',
        '((()))',
        '(a((b)))',
        '((())))',
        'hello(a(b())))world',
        '(a(b(c)d)e)',
    ]

    for s in strings:
        print(
            repr(s),
            list(quantify_parens(s)),
            sum(quantify_parens(s)),
            parens_are_balanced(s))

    print(list(running_op(range(1, 5), operator.mul, 1)))

main()
[jjj at dojo ~]$ 


More information about the CentralOH mailing list