DEV Community

Cover image for What is Command Injection, and how to protect yourself against it?
Anthony
Anthony

Posted on

What is Command Injection, and how to protect yourself against it?

Command injection is a cyber-attack that involves executing commands on another person's host operating system. This could include removing files and changing data on the host computer. This type of attack happens when the programmer does not use enough input validation to check if the input is malicious or not.

For example, in Python you can code:

import os

domain_name = input()

os.system('ping ' + domain_name)
Enter fullscreen mode Exit fullscreen mode

Then, when I run this in my computer, I can input google.com as the domain_name, such as:
Pinging Google
As you can see, you get a response back from Google!

Although, someone not as nice as me or you may type out something different when prompted for input. Let's say you want to just echo what the user said back to us from the command line.

You would just replace the ping in the os.system with
os.system('echo ' + input)

But this time, lets add ; ls after whatever you want to echo
Command Injection
As you can see, we get the files in the current working directory, which happens to be example.py. This is bad.

You can even take it a step further and use the rm command to remove a file on your system such as:
hello; rm example.py

Removing File

As you can see the file is now gone from your computer. This can lead to a slew of security issues if left unchecked. To combat this (in Python specifically) we can use the call method from the subprocess module. Such as

from subprocess import call

user_input = input()

call(["echo", user_input])
Enter fullscreen mode Exit fullscreen mode

The call function will make sure that only a single command will be run.

Fixing Security Issue

There are language equivalents for the example in Python above.
Be safe!
(Anime CS Girls)

Top comments (0)