Home > Backend Development > PHP Tutorial > How to Execute Root Commands from PHP on CentOS?

How to Execute Root Commands from PHP on CentOS?

Linda Hamilton
Release: 2024-11-16 04:24:02
Original
197 people have browsed it

How to Execute Root Commands from PHP on CentOS?

Executing Root Commands through PHP

You have expressed a desire to execute commands with root privileges from your PHP code on your CentOS server. Let's explore the issue and present potential solutions.

The Issue:

You've attempted to use the exec() function to restart the sshd service, but it requires root access, which is not granted to the Apache user. While you've tried solutions such as running Apache with root privileges or modifying your sudoers file, they haven't resolved the issue.

Solution Using Binary Wrapper (With Suid Bit):

  1. Create a Shell Script: Begin by creating a script (e.g., php_shell.sh) containing the command you want to execute as root.
  2. Set Ownership and Permissions: Ensure that the root user owns the script and that it has the following permissions:

    • Owner: Read, Write, Execute (rwx)
    • Group: Read, Execute (rx)
    • Others: Read, Execute (rx)
  3. Create a Binary Wrapper: Create a binary wrapper that will execute your shell script with root privileges. Here's an example wrapper:

    # cat > wrapper.c <<CONTENT
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int
    main (int argc, char *argv[])
    {
       setuid (0);
       system ("/bin/sh /path/to/php_shell.sh");
       return 0;
     }
    CONTENT
    Copy after login
  4. Compile and Set Permissions: Compile the binary wrapper and set it with the suid bit:

    • Compile: gcc wrapper.c -o php_root
    • Set ownership: chown root php_root
    • Set permissions: chmod u=rwx,go=xr, s php_root

This php_root wrapper will execute the commands specified in php_shell.sh with root privileges when called.

Alternative Solution:

Instead of using an external shell script, you can embed the commands directly into the binary wrapper. Simply replace the content in step 3 with the commands you want executed with root privileges.

Caution:

It's essential to use absolute paths to the script you want executed to prevent malicious users from exploiting the binary to execute arbitrary commands.

The above is the detailed content of How to Execute Root Commands from PHP on CentOS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template