10 common security gotchas in Python and the way to avoid them
Writing secure code is difficult. Once you learn a language, a module or a framework, you find out how it imagined to be used. Once thinking about security, you wish to think about how it can be misused. Python isn't any exception, even inside the quality library there are documented bad practices for writing hardened applications.
Here are my top 10, in no explicit order, common gotchas in Python applications.
1. Input injection:
Injection attacks are broad and very common and there are many varieties of injection. They impact all languages, frameworks and environments.
SQL injection is wherever you’re writing SQL queries directly rather than using an ORM and combining your string literals with variables. I’ve read lots of code where “escaping quotes” is deemed a fix. It isn’t.
Command injection is anytime you’re calling a method using popen, subprocess, os.system and taking arguments from variables. once calling local commands there’s a chance of somebody setting those values to something malicious.
Sanitise input using the utilities that associate with your web framework, if you’re using one. Unless you have got a decent reason, don’t construct SQL queries by hand. Most ORMs have builtin sanitation strategies.
2. Parsing XML:
If your application ever loads and parses XML files, the odds are you're using one amongst the XML standard library modules. There are some common attacks through XML. mostly DoS-style (designed to crash systems rather than exfiltration of data). Those attacks are common, particularly if you’re parsing external (ie non-trusted) XML files.
One of those is called “billion laughs”, because of the payload normally containing heaps (billions) of “lols”. Basically, the concept is that you just will do denotive entities in XML, therefore once your retiring XML programme tries to load this XML file into memory it consumes gigabytes of RAM.
Another attack uses external entity growth. XML supports referencing entities from external URLs, the XML parser would generally fetch and load that resource without any qualms. “An attacker will circumvent firewalls and gain access to restricted resources as all the requests are made of an enclosed and trustworthy ip address, not from the outside.”
Another scenario to consider is 3rd party packages you’re depending on that decode XML, like configuration files, remote Apis. you might not even be aware that one in all your dependencies leaves itself open to these kinds of attacks.
Use defusedxml as a drop-in replacement for the quality library modules. It adds safe-guards against these kinds of attacks.
3. Assert statements:
Don’t use assert statements to guard against items of code that a user shouldn’t access.
Only use assert statements to speak with alternative developers, like in unit tests or in to protect against incorrect API usage.
4. timing attacks:
Timing attacks are basically a way of exposing the behaviour and algorithm by timing however long it takes to match provided values. timing attacks require exactness, so that they don’t generally work over a high-latency remote network. due to the variable latency involved in most web-applications, it’s pretty much not possible to write a timing attack over http web servers.
But, if you have got a command-line application that prompts for the countersign, an attacker will write an easy script to time how long it takes to match their value with the particular secret.
Use secrets.compare_digest , introduced in Python 3.5 to match passwords and alternative private values.
5. A contaminated site-packages or import path:
Python’s import system is extremely flexible. which is nice once you’re trying to write down monkey-patches for your tests, or overload core practicality.
But, it’s one amongst the most important security holes in Python.
There are occurrences of packages being printed to PyPi with similar names to popular packages, but instead corporal punishment capricious code. the biggest incidence, fortunately wasn’t harmful and simply “made a point” that the problem isn't really being addressed..
6. Temporary files:
To create temporary files in Python, you’d generally generate a file name using mktemp() function and so produce a file using this name. “This isn't secure, because a different method might create a file with this name within the time between the call to mktemp() and the consequent conceive to produce the file by the primary method.”  this suggests it might trick your application into either loading the incorrect data or exposing other temporary data.
Recent versions of Python can raise a runtime warning if you call the inaccurate methodology.
Use the tempfile module and use mkstemp if you wish to get temporary files.
7. Using yaml.load:
To quote the PyYAML documentation:
“Warning: it's not safe to call yaml.load with any data received from an untrusted source! yaml.load is as powerful as pickle.load then may decision any Python function.”
Use yaml.safe_load, pretty much always unless you have got a really smart reason.
Deserializing pickle data is simply as bad as YAML. Python categories will declare a magic-method referred to as __reduce__ that returns a string, or a tuple with a owed and the arguments to decision once pickling. The offender will use that to incorporate references to 1 of the subprocess modules to run capricious commands on the host.
Never unpickle knowledge from associate untrusted or unauthenticated supply. Use another publishing pattern instead, like JSON.
9. Using the system Python runtime and not fix it:
Most POSIX systems keep company with a version of Python two. generally an previous one.
Since “Python”, that is CPython is written in C, there are times once the Python interpreter itself has holes. Common security problems in C are associated with the allocation of memory, therefore buffer overflow errors.
CPython has had variety of overrun or overflow vulnerabilities over the years, each of which have been patched and fixed in ensuant releases.
Install the newest version of Python for your production applications, and patch it!
10. Not fix your dependencies:
Similar to not fix your runtime, you also got to patch your dependencies regularly.
I realize the apply of “pinning” versions of Python packages from PyPi in packages terrific. the concept is that “these are the versions that work” therefore everybody leaves it alone.
All of the vulnerabilities in code I’ve mentioned above are just as important once they exist in packages that your application uses. Developers of these packages fix security problems. All the time.
Use a service like PyUp.io to check for updates, raise pull/merge requests to your application and run your tests to stay the packages up so far.
Use a tool like InSpec to validate the put in versions on productionenvironments and ensure lowest versions or version ranges are patched.
Learn python courses in Bangalore from Infocampus and get python certification. Get detailed information on fees, coaching quality, duration. Attend free demo classes on Python Training in Bangalore .
Contact Us: 8884166608/9738001024.