How Frequent Python Coding Errors Can Trigger Vulnerabilities

0/5 No votes

Report this app



On this weblog put up we are going to speak about writing safe code. Am I pretending to all the time write safe code?… Heck no! I’m lazy similar to the remainder of us :-). That being mentioned, there are some things that one ought to concentrate on when writing code (even when it’s pattern code). I consider which you could nonetheless write your easy samples. Nonetheless, if not less than what vulnerabilities your code may need then you possibly can write that down in your README. Even the well-known Chinese language thinker Confucius knew this again round 530 BC:

“To know what and what you have no idea, that’s true data.” – Confucius

Ought to I be fearful about my script?

No. Once more, I’m not preaching that you need to all the time go the total mile for some code you may have written to check out an API. Nonetheless, I’ve listed 5 frequent Python errors that may trigger severe vulnerabilities in manufacturing functions. Please be conscious of those and attempt to keep away from them as a lot as you possibly can! Additionally, these coding errors can clearly additionally occur in different programming languages as effectively, so this doesn’t simply apply to Python.

py_vuln00: Arbitrary Code Execution

What’s it?

Arbitrary Code Execution is an attacker’s capacity to run any instructions or code on a goal machine or in a goal course of. That is commonest in Python and happens in many sorts comparable to command injection, SQL injection, and extra. It arises from consumer inputs which can be being immediately handed in a regular Python perform. The dearth of enter sanitization is normally the explanation.

Instance code snippet:

compute_user_input = enter('nType one thing right here to compute: ')
if not compute_user_input:
  print ("No enter")
  print ("Consequence: ", eval(compute_user_input))

Run in terminal as enter:

> __import__("os").system("ls") [playing nice]
> __import__(‘os’).system(‘rm –rf /’) [less nice…]

How will you resolve it?

All the time sanitize and validate consumer inputs first earlier than passing them to the system instructions. Utilizing the `ast` Python module may also be resolution. The Python module `shlex` can even assist to mechanically escape consumer enter.

py_vuln01: Listing Traversal Assault

What’s it?

A Listing Traversal Assault can also be brought on by improper consumer enter validation. This will result in delicate recordsdata to be uncovered and even to distant code execution. It arises if the trail of file entry by Python script isn’t correctly checked. An attacker can manipulate the file path for instance to one thing like /and so forth/passwd…


As instance Python library, the Requests bundle (who doesn’t use this one?) earlier than 2.20.0 for Python sends an HTTP Authorization header to an http URI upon receiving a same-hostname https-to-http redirect, which makes it simpler for distant attackers to find credentials by sniffing the community. 

How will you resolve it? 

This vulnerability could be fastened by updating (and testing!) all of the packages for which updates can be found. (DUH!)
It’s also possible to use instruments to assist with this after the actual fact: 

  • Static utility safety testing (SAST)  
  • Dynamic utility safety testing (DAST)  
  • Interactive utility safety testing (IAST)  
  • Runtime utility self-protection (RASP) (e.g. Cisco AppDynamics with Safe Software, please see the final part of this weblog put up for extra particulars) 

py_vuln03: Incomplete Assertions

What’s it?

This vulnerability occurs when Python assertions are used to guage a situation, comparable to Boolean expressions. If the situation is true, the execution strikes to the next line. In any other case, it would present an error. The `assert` key phrase ought to usually be used when debugging code.

Instance snippet

x = "whats up" 

# if situation returns True, then nothing occurs: 
assert x == "whats up" 

# if situation returns False, AssertionError is raised: 
assert x == "goodbye”

# if situation returns False, customized AssertionError is raised: 
assert x == "goodbye", "x ought to be 'whats up'"

How will you resolve it?

Do NOT use Python assertions for logic, use if-else logic for Boolean circumstances. In manufacturing, assertions is likely to be disabled, so solely use assertions in testing environments. Python assertions are usually not an error-handling software, they’re a debugging software, please use them as such.

py_vuln04: Damaged Entry Management 

What’s it? 

Damaged entry management describes the exploitation of entry management administration by attackers and dangerous actors. This vulnerability was truly moved to OWASP10 spot #1 from #5. A shocking 94% of apps have been examined for some type of damaged entry management. 

Some examples: 

  • Handbook app state modification: These modifications might be URL modification, browser cookies and classes, or using customized API assault instruments. 
  • Key identifier change: This enables the alteration of key identifiers, just like the consumer’s main key, in such a approach that offers undesirable entry to a different consumer to carry out actions in any other case unauthorized. 
  • Privilege escalation: This can be a identified technique of assault the place an attacker logs right into a enterprise database as an administrator. This assault can take the type of appearing as an authenticated consumer with out authentication. 

Instance snippet 

If we take a look at the next authentication URL we are able to see the parameters which can be being handed: 

An attacker could change the URL parameters such because the ID, ACCESS_KEY, and ACCESS_SECRET to something malicious, giving them entry to account data. By way of this assault delicate data is likely to be leaked or altered. 

How will you resolve it? 

Validation and verification of requests ought to all the time be in place. Position-based permissions and object-level permissions also needs to be applied, in order that authorization could be verified between the approved consumer and the requested object useful resource. Beneath is a straightforward instance of such validation and verification:  

def update_details(request, acc_id):
  consumer = Account.objects.get(acc=acc_id)
  if ==
      type = AccountForm(occasion=consumer,request=request)

Builders vs. Safety: Buddies or foes? 

Generally builders and the safety crew do not likely vibe. This may consequence from the truth that they’ve considerably of conflicting pursuits. Builders is likely to be centered on creating helpful options (a.s.a.p.) and solely collaborates with safety groups throughout investigations, remediations, and adjustments to susceptible code. Safety groups (e.g. SecOps and/or AppSec) is likely to be centered extra on making certain builders write safe software program and use safe dependencies. They may additionally create safety guardrails via coaching, testing, tooling, and pipeline integration. They will even examine occasions that might be safety incidents or breaches.  

To sum this up a developer desires to create new traces of code to create options as quick as potential, the place the safety groups need them to be diligent and safe. How can we make these groups collaborate higher? 

Cisco AppDynamics with Safe Software 

Cisco may be capable to assist out with this battle of curiosity. Sadly, it can’t resolve it fully, nevertheless it will possibly assist to alleviate a number of the friction. 

This software can detect utility code dependency and configuration-level safety vulnerabilities in manufacturing with computerized runtime safety. It would repeatedly monitor vulnerabilities to seek out and even block exploits mechanically, maximizing velocity and uptime whereas minimizing threat. As earlier talked about, Cisco Safe Software is a Runtime Software Self-Safety (RASP) resolution for contemporary functions by defending towards assaults to stop breaches. Most significantly, it simplifies the life cycle of vulnerability fixes by giving each builders and safety groups a standard interface to work with. A small be aware: on the time of penning this weblog put up, Cisco Safe Software solely works for Java AppDynamics agent, nevertheless the help is being constructed out to the remainder of the brokers as we converse. 

You made it to the tip of this weblog put up! Thanks! As a reward, I’ve some extra data so that you can take a look at: 

We’d love to listen to what you suppose. Ask a query or depart a remark under.
And keep linked with Cisco DevNet on social!

LinkedIn | Twitter @CiscoDevNet | Fb Developer Video Channel



Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.