Trending February 2024 # How Does Code Injection Work? # Suggested March 2024 # Top 6 Popular

You are reading the article How Does Code Injection Work? updated in February 2024 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Does Code Injection Work?

Code injection, often referred to as remote code execution (RCE), is an attack perpetrated by an attackers ability to inject and execute malicious code into an application; an injection attack. This foreign code is capable of breaching data security, compromising database integrity or private properties. In many instances, it can bypass authentication control, and usually these attacks are associated with applications that depend on user input for execution.

Generally, applications are more vulnerable if the code is executed without first passing through validation. A simple case of a vulnerable code is shown below.

Due to the fact that user interaction with applications is more and more a necessity in today’s online world, code injection has grown and has become a real threat to many online resources.

Types of code injections

There are mainly four types of code injections: SQL injection, Script injection, Shell injection, and Dynamic evaluation. All of these have the same working principle, that is, the code is introduced into and executed by applications, but the two I will pay focus on are SQL injection and Script injection.

How SQL injections work

In the case of SQL injection, the attack is aimed at corrupting a legitimate database query to produce falsified data. The attacker first has to locate an input within the targeted web application that is included inside of an SQL query.

This method is only effective if the web application has user input included within an SQL statement. A payload (a malicious SQL statement) can then be inserted and run against the database server.

The following server-side pseudo-code is a simple example of authentication that can prove vulnerable to SQL injections.

In the above code the attacker could insert a payload that would change the SQL statement executed by the database server. An example would set the password field to:






This automatically causes the following statement to be run against the database server:

















What SQL injection can do

This is the most common type of code injection. Considering the fact that SQL is the language used to manipulate data stored in Relational Database Management Systems (RDBMS), an attack with the power to give and execute SQL statements can be used to access, modify and even delete data.

It can give the attacker the ability to bypass authentication, have full disclosure of data stored in the database, compromise data integrity and cause repudiation issues, altering balances and voiding transactions.

How to prevent SQL injections

There are a few steps to make your applications less vulnerable, but before any of these steps, it is best to assume all user-submitted data is evil and to trust no one. Then you could consider the following:

Disable the use of dynamic SQL – this means don’t construct database queries with user input. If required, sanitize, validate and escape values before making a query with user input data.

Make use of a firewall – A web application firewall (software or application based) will help filter malicious data.

Purchase better software – This simply means coders will be responsible for checking and fixing flaws.

Encrypt or hash passwords and every other confidential data you have, this should include connection strings.

Avoid connecting to your database with admin privileged accounts unless you absolutely need to.

Script injection How to prevent script injections

The steps to prevent script injections are dependent on the programming code you are using. Generally, you will want to:

validate and sanitize user input (any form of input fields) by striping out or escaping potentially malicious content

clean up query strings in URLs

validate and sanitize all forms of data, arrays and objects before executing in the server


Simply said, prevention is better than a cure. With new updates in technology, there are more threats our systems are going to be exposed to. To stay on top of things, it’s important to have the latest patches and updates and to keep an ear out for best practices. This makes it harder to fall victim to these malicious attacks.

Afam Onyimadu

Afam is a writer with a passion for technology amongst many other fields. Aside from putting pen to paper, he is a passionate soccer lover, a dog breeder and enjoys playing the guitar and piano.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

You're reading How Does Code Injection Work?

What Is Code Injection? (How It Works, How To Prevent)

These attacks are typically made feasible by a lack of sufficient input/output data validation, such as −

Data format

Quantity of anticipated data

Allowable characters

SQL injection, Script injection, Shell injection, and Dynamic evaluation are the four primary forms of code injections. All of them function on the same idea that a code is injected into and executed by programs.

What is Command Injection?

In Command Injection, an attacker’s options are restricted solely by the capabilities of the injected language. An attacker is only restricted by PHP’s capabilities if they are able to inject PHP code into an application and have it executed. Using existing code to execute commands, generally inside the context of a shell, is known as command injection.

How Does Code Injection Work?

When an application doesn’t have adequate input validation or doesn’t sanitize the data it stores, it’s exposed to code injection.

Let’s talk about what “user input” is before we get into functioning. In simple terms, user input refers to any data that a user enters into an application and that the program subsequently processes.

The program is only designed to accept particular input types, according to its creators. The application into which the code is being injected anticipates certain sorts of data. In rare circumstances, the developer may be careless in ensuring that the right data is provided to the program.

Code injection attacks may affect a variety of apps. Code injection is done via the eval() function. By inserting code as user input, the attacker abuses the program. The attackers gain access to the system information and database after the attack is successful.

Hackers initially look for attack surfaces in the application that can receive untrusted data and utilize it to execute computer code. Direct sources like cookies and query string parameters, are the examples.

A straight concatenation of character strings, the PHP eval() function, or its counterpart in another language is usually used to introduce code. An attacker can get access to the application’s server-side interpreter if the vulnerability is successful. The attackers can utilize system calls to execute instructions on the server and get access to further information.

How to Prevent Code Injection Attacks?

Developers can take the following precautions to prevent Code Injection Attacks −

Use Whitelisting for Input Validation

Whitelisting is easier to set up and allows security teams more control over what data or types of input the application may handle, lowering the chance of malicious code being executed by an attacker.

Use Contextual Output Encoding

Use contextual output encoding to transform harmful input into safer representations, where user data can be presented but not executed as code.

Use a Static Type System

To ensure language separation, use a static type system. With static type systems, teams may create declarative control checks without the added runtime cost.

Avoid Using Unsafe Functions in the Source Code

It’s vital to avoid utilizing any vulnerable code evaluation structures when developing source code. Instead, developers should employ safe, language-specific functionality to manage user-supplied inputs.

Use the HttpOnly Flag on Cookies

Use the HttpOnly flag on cookies to prevent client-side script interaction. The HttpOnly flag on every cookie that the server creates indicates that the cookie should not be accessible from the client-side. As a consequence, even if there are issues with HTML injection, the cookies cannot be shared with third parties.

How Does Opencv Findcontour() Work

Introduction to OpenCV findContours

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

It works essentially well on binary pictures and images, thought at the first application of Sobel edges and thresholding techniques should be implemented. Each of the individual contour is representative of an individual numpy array with coordinates x and y, which represents the boundary point for the object that the user has entered.

Syntax of OpenCV findContour()

Following is the syntax used for application of the OpenCV findContour method:

void cv :: findContours (InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point() ) Parameters of OpenCV findContour():

Following are the parameters used for the Open CV findContour() method:

Image It is the source image that is used which is generated through a single channel of about eight bits. Any pixels that are in the non-zero category designated as 1’s, the pixels with zero categories are designated as 0’s, perforce converting the image into a binary form. Various parameters (such as adaptiveThreshold, inRange, Canny, threshold, etc.) can then be further applied in order to create the binary images using the coloured or grayscale image that is the user. In case the mode is equal to RETR_FLOODFILL or RETR_CCOMP, then the image which is being entered by the user as the source image be a 3- bit integer-based image of label CV_32SC1.

Contours Detection of contour – each of the single contour has been stored in the form of multiple points that are vectors.


Mode Mode activated specifically to contour retrieval.

Method Mode activated specifically to depict the approximation method for the image contour.

Offset It is an optional parameter by using which every contour point can be shifted. It is essentially useful when the contour has been extracted are image ROI, and then further analysis should be done in the context of the whole image.

How does OpenCV findContour() Work?

When the computer is made to detect the edges of an input image, it then finds the points where specifically, there is a significant difference notice in the intensity of colouration, then simply those pixels are turned on. A stark differences noticed when the system is instructed to perform contouring.

Contours are basically an abstract collection of segments and points that correspond to the reflective shapes of the objects that are present in the images that have been processed through the system. as a result of this; it is in our capacity to manipulate the contouring within the programs through which they are being accessed.

This can be done in multiple ways, such as having a count on the number of contours in an image and then using that to categorize the object shapes, for segmentation of images or cropping objects from the image that is being processed and many more such similar functions.


Given below is the example of OpenCV findContour:


import numpy as np1 import cv2 img_1 = cv2.imread('EduCBA.png') print (“The Gray scale image is ” /n) imgray_1 = cv2.cvtColor(img_1, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray_1, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) print("The Total Number of Contours in the Image = ") print (str(len(contours))) print(contours[0]) cv2.drawContours(img_1, contours, -1,(0,2550,0),3) cv2.drawContours(imgray_1, contours, -1,(0,255,0),3) print (“The original image is: “ /n) cv2.imshow('Image', img_1) cv2.imshow('Image GRAY', imgray_1) cv2.waitKey(0) cv2.destroyAllWindows()

The output screen displays the screenshot on the compiling of the above code.

Conclusion – OpenCV findContours

The OpenCV find contour method is essentially useful as it provides for a pre-defined function that can be called without implementation of an entire code and can be modified using the various parameters. It is essentially helpful in terms of analysing the shape of the image provided, in the detection of the size and dimension of the object that has to be detected in the provided image and in the detection of specific objects. This is done in order to categorize the object shapes, for segmentation of images or cropping objects from the image that is being processed and many more such similar functions.

Recommended Articles

We hope that this EDUCBA information on “OpenCV findContours” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Join Work In Linux?

Introduction to Linux Join

In a certain situation in today’s world, when the data is sparse, it becomes necessary to join 2 files that contain parts of the same data. In other words, using join, one can achieve the utility of “joining” 2 files so that the join output makes more sense and is complete. There are many applications where the join command finds its use. Let us make it more clear to you with an example. Suppose there are 2 files; in one file, we have a list of employees, and in the other, their addresses. Join in Linux comes in handy for these kinds of join situations!

Start Your Free Software Development Course

Web development, programming languages, Software testing & others


The basic syntax attached to the join is:


Where FILE1 and FILE 2 are the files, where contents are located, and OPTION denotes the various options we would discuss here, which help achieve the desired requirement.


2. -v option: Way to ONLY print non-paired lines.

3. Join custom columns from 2 files


4. -i / –ignore-case option: Case insensitive join



5. –check-order / –nocheck-order: Check for sort through all input lines.



6. –help option: Display of help message.


Join --help How does Join Work in Linux?

Join in Linux finds its application in various uses, and in this section, we will look into some of the most used ones during the explanation of each of them; we will take turns explaining the working of each in due course of the section.

The first and foremost is the basic join, where the intent is to join 2 files through a common key; here, the key is also referred to as an index and acts like matching 2 contents on similar grounds. Think of this as a sports tournament, where teams play against each other on some common ground, may it be goals scored in soccer, runs scored in cricket, and so on. Now since only 2 teams can play against each other in contrast to so many teams in the tournament, there are some common rules to judge the winners and runners-up.

Now, with the same analogous situation, the 2 files will be compared, and wherever the index would match, the contents corresponding to the index will be copied along with a gap. Now, one needs to be careful about any gap or empty character in place as they will tend to be concatenated along. In the next one, there might be conditions where the “index” might be missing from any one of the files, and hence the user may choose to add the non-paired ones during the join with the intent that the result file is something like a union of the files and would contain “best of both worlds”.

Also, one must be aware of the act that the join in Linux is case sensitive. In some scenarios, the user would like to neglect the case of the indexes used for joining. Now, obviously, if the index is a number, the case won’t matter, but in case the index is alphabets, the ascii value of small caps in comparison to all caps is different and hence problematic for Linux to join by default. Hence, the user can use -i to make the indexes case-insensitive during the join.

At last, there are other sets of commands which one can access using –help in Linux, should one feel the need to explore more of Linux join.

Examples of Linux Join

Given below are the examples mentioned:

Example #1

Join with printing all non-paired rows in File 2.


join chúng tôi chúng tôi -a 2

Join with printing all non-paired rows in File 1.


join chúng tôi chúng tôi -a 1


Inputs files:

Join with printing all non-paired rows in File 2:

Join with printing all non-paired rows in File 1:

Example #2

Join with printing ONLY non-paired rows in File 2:


join chúng tôi chúng tôi -v 2

Join with printing ONLY non-paired rows in File 1:


join chúng tôi chúng tôi -v 1


Example #3


When the order of custom columns is different:

join chúng tôi chúng tôi -1 2 -2 1

When the order of the custom column is the same:

join chúng tôi chúng tôi -j 2


When the order of custom columns is different:

When the order of the custom column is the same:

Example #4


join -i chúng tôi file2.txt join --ignore-case chúng tôi file2.txt


When no option is used, the join returns empty!

Example #5


No option

join -i chúng tôi file2.txt

Using the option of check order

join -i --check-order chúng tôi file2.txt

Using the option to not check the order.

join -i --nocheck-order chúng tôi file2.txt


When the option “–nocheck-order” is not available, an error is reported if there is unsorted data. However, when the “–nocheck-order” option is used, the error is suppressed, and the unsorted line is simply omitted from the process.

Example #6


join --help



With the set of examples and explanations to the working of join in Linux, you must be quite used to the usage of the same, and this will enable you to experiment more with other arguments of Linux join.

Recommended Articles

We hope that this EDUCBA information on “Linux Join” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Numpy.mean() Work With Example

Introduction to numpy.mean()

Numpy.mean() is function in Python language which is responsible for calculating the arithmetic mean for the all the elements present in the array entered by the user. Simply put the functions takes the sum of all the individual elements present along the provided axis and divides the summation by the number of individual calculated elements. The axis along which the calculation is made has to be prespecified or else the default value for axes will be taken.

Start Your Free Software Development Course

Syntax and Parameters

The following is the syntax that displays how to implement numpy.mean().

The syntax entered by the user is sent in terms of float * 64 intermediate and there by returns the value for the associated integers corresponding for the mean value.

The parameter used in the Syntax for using numpy.mean()

a *: *array *_ *like *

The array is being entered by the user or prompted to be entered. In case the array entered is not of an integer data type, then the conversion of the form is tried on the data entered.

axis : None *, *  *int *, *  *tuple * (optional parameter)

The computation of the axis along the elements of the specified array entered by the user is done. By default, the mean of the pre-flattened array is computed. In case the array entered is a tuple, in such a case the mean is computed over various axes of the array.

 dtype * *: * *data *– *type *, (parameter is optional)

For the computation of the mean the parameter type is utilized. By default, the float 64data type is used for arrays with integer data sets. In case the data being input is floating it remains the same as the dtype entered.

out : ndarray, (parameter is optional)

keepdims: bool, (parameter is optional)

If the parameter specified is True, the axis or axes which are deduced are kept in the expected result as the dimensions having size one. The option enables the result to be broadcasted correctly in response to the array which has been entered. In case value by default, a parameter is passed then the keepdims parameter would not be passed on to the method-specific for mean with respect to the array and its sub-classes. However, it must be noted that for non-default values passed the keepdims parameter would be applicable to raising exceptions if any.

m : ndarray

If the parameter out=None, then in such a case a new array is returned which contains the mean values. Else, in such cases, the reference values with respect to the elements if retuned.

Example to Implementation NumPy.mean()

Below are the examples mentioned:


import numpy as n1 a1 = n1.array([[10,20,30],[30,40,50],[40,50,60]]) print 'The new array entered by the user is:' print a1 print 'Application of the Numpy.mean() function on the array entered:' print n1.mean(a1) print 'Application of the mean() function alongside the axis - 0:' print n1.mean(a1, axis = 0) print ' Application of the mean() function alongside the axis - 1:' print n1.mean(a1, axis = 1)

The following output would be produced for the code specified above:

How Does the numpy.mean() Work?

The function scans through the values which are specified in the array which is provided by the user. It firstly tries to flatten the resultant array before the computation of the arithmetic mean on the same. The below diagrammatic systemic representation shows the function actually executes the calculation:

We can use the NumPy mean function to compute the mean value:

As the function for mean travels through various axis or axes provided by the user, it scan through and tries to integrate the arithmetic mean functionality for all integral values, Where the elements do not match up to be integral data type, it tries to convert such numbers.

Here you can see for a single dimensional array with six specified elements, the functions scans each of the elements and then divides the total summation of the elements by the total number of elements present in the array (here 6).

This way for arrays with multiple dimensions all or specified axis is mentioned along which the mean is calculated which is displayed in an array form for more than one-dimensional arrays.


The function mean() in NumPy is very useful for calculating the arithmetic average of elements especially in terms of data given in array subsets. This being calculated through manual code impacts the verbosity of the code and thus impacts on the computation time for long codes with large data sets.

Recommended Articles

This is a guide to numpy.mean(). Here we discuss the introduction and working of numpy.mean() along with different examples and its code implementation. You may also look at the following articles to learn more –

How Does Ansible Fetch Work? (Examples)

Introduction to Ansible Fetch

Ansible fetch module is a file-based module, which is intended to work on files. This module is similar to Ansible copy module, but by default works in reverse order, in terms of source and destination. It is one of such modules that you might need on day to day basis while working on administrative or change management tasks on remote target machines. There are many other modules like a copy, template, etc. which works more or less in a similar way, there usability completely depends on the available feature parameters. In this article, we will learn about the Ansible Fetch module by using some examples and details on parameters that are usable under this module.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

What is Ansible Fetch?

This module will treat remote machines as a source of files and local controller machines as a destination.

Fetched files are organized by hostname, in a file tree structure.

Files with different contents but the same name are overwritten on destination.

This module works as it is, for Microsoft Windows machines as well.

It is suggested to not use this module with Ansible to become parameters as this will lead to doubling the size of the transfer file. As checksum will also be calculating. This will then lead to consuming all available memory on remote or local hosts causing MemoryError.

When reading of remote files is not possible, then we shall use fail_whenor ignore_errorsor fail_on_missing, to avoid failure of the playbook.

How Does Ansible Fetch Work?

To efficiently use Ansible fetch module, one much learn about all available parameters, their acceptable values. Also, there are some parameters that have default values set always, which will be realized to your playbook even if you do not mention the related parameter in the playbook. So these become more important to know. Below is a list of all available parameters and related acceptable or default values.

dest: This is to set the directory where fetched files will be saved. Point to note that under this directory another directory will be created which is named after the hostname of target remote systems, but based of inventory entries. Under this directory, the whole directory structure as a source will be created and then file will be copied into it.

fail_on_missing: Default is yes. This will cause the playbook failure when Ansible is unable to read files on source systems, reason can be anything like permission, non-existence, etc. Available values are yes and no.

flat: Default is no. Acceptable values are yes and no. This is to set the override the default behavior of the fetch module. Thus to behave in such a way where files will be copied directly to destination location without creating hostname-based directory structure.

src: To give the file name on remote systems to fetch. This must be a filename, not any directory name, as fetching of the directory is not supported yet.

validate_checksum: Default is yes. Acceptable values are yes and no. To verify the source and destination checksum of files after fetching.

Examples to Implement Ansible Fetch

In this section, we will learn by doing looking at some examples where we tried to test the functionality of the Ansible reboot module. But we shall know about our lab environment first before moving ahead in this section.

Here we have one Ansible controller node named as ansible-controller. As target nodes, we have two remote machines. First machine is a Red Hat Enterprise Linux machine named as host-one and the second machine is an Ubuntu machine named as host-two. We will run our playbooks on the Ansible controller machine and make changes on remote target machines.

Example #1

In this example, we have a playbook that is used to fetch a file from remote target nodes and store on the local Ansible controller machine. Then we will check on the local Ansible controller machine that how the file is stored and what directory tree structure is created for this.


dest: /tmp/fetched

Then running this playbook like below:

# ansible-playbook ansible_fetch.yaml

Now in the output, we can see that files are fetched and stored on Ansible local machine in a directory structure.


Upon checking the directory structure, we found that a full directory structure has been created on the local machine.

Also, check the timestamp of files and directories.

Example #2

In this example, we have a playbook that is used to fetch a file from remote target nodes and store on local Ansible controller machine. Here we have used a parameter named flat=yes. This is used to override the default behavior of the Ansible fetch module and copy file as it is with name and under path mentioned in the dest parameter. Then we will check on the local Ansible controller machine that how the file is stored and what directory tree structure is created for this.


Then running this playbook like below: –

# ansible-playbook ansible_fetch_flat.yaml -v


Then stored on Ansible local machine in the same directory with a new name and no new directory structure is created.


As we saw in this article, Ansible fetch module is easy to use though a very useful module, which you will definitely need in your Ansible skill set. Also having knowledge of its all available features and possibilities will enable you to use it to full extend. So learn it first and then use it.

Recommended Article

This is a guide to Ansible Fetch. Here we discuss What is Ansible Fetch and its syntax along with examples as well as code implementation. You can also go through our other suggested articles to learn more –

Update the detailed information about How Does Code Injection Work? on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!