search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP website attack methods - command injection attack

This article mainly introduces command attacks among common attack methods on PHP websites. Command Injection refers to an attack method in which hackers change the dynamically generated content of a web page by entering HTML code into an input mechanism (such as a form field that lacks effective validation restrictions). Using system commands is a dangerous operation, especially if you are trying to use remote data to construct the command to be executed. If contaminated data is used, command injection vulnerabilities arise.

Command injection attack

The following 5 functions can be used in PHP to execute external Application or function

system, exec, passthru, shell_exec, "(same function as shell_exec)

Function prototype

string system(string command, int &return_var)

command The command to be executed

return_var stores the status value after the execution of the command

string exec ( string command, array &output, int &return_var)

command The command to be executed

output Gets each line of string output by executing the command

return_var stores the executed command The status value

void passthru (string command, int &return_var)

command The command to be executed

return_var stores the status value after executing the command

string shell_exec (string command)

command The command to be executed

漏洞实例

例1:

  1. //ex1.php 
    $dir = $_GET["dir"]; 
    if (isset($dir)) 
    { 
    echo "";
    system("ls -al ".$dir); 
    echo ""; 
    } 
    ?>

我们提交http://www.sectop.com/ex1.php?dir=| cat /etc/passwd

提交以后,命令变成了 system("ls -al | cat /etc/passwd");


eval注入攻击

eval函数将输入的字符串参数当作PHP程序代码来执行

函数原型:

mixed eval(string code_str) //eval注入一般发生在攻击者能控制输入的字符串的时候

  1. //ex2.php 
    $var = "var"; 
    if (isset($_GET["arg"])) 
    { 
    $arg = $_GET["arg"]; 
    eval("\$var = $arg;"); 
    echo "\$var =".$var; 
    } 
    ?>

当我们提交http://www.sectop.com/ex2.php?arg=phpinfo();漏洞就产生了;

动态函数

  1. php 
    func A() 
    { 
    dosomething(); 
    } 
    func B() 
    { 
    dosomething(); 
    } 
    if (isset($_GET["func"])) 
    { 
    $myfunc = $_GET["func"]; 
    echo $myfunc(); 
    } 
    ?>

程序员原意是想动态调用A和B函数,那我们提交http://www.sectop.com/ex.php?func=phpinfo漏洞产生

防范方法

1、尽量不要执行外部命令

2、使用自定义函数或函数库来替代外部命令的功能

3、使用escapeshellarg函数来处理命令参数

4. Use safe_mode_exec_dir to specify the path of the executable file

The esacpeshellarg function will escape any characters that cause the end of parameters or commands, single quotes "'", and replace them with "\'", double quotes " "", replace it with "\"", replace the semicolon ";" with "\;"

Use safe_mode_exec_dir to specify the path of the executable file. You can put the commands you will use in this path in advance

safe_mode = On

safe_mode_exec_dir = /usr/local/php/bin/


The above is the detailed content of Detailed explanation of PHP website attack methods - command injection attack. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.