|
|
 |
CapÃtulo 24. Instalación como un binario CGI
El uso de PHP como un binario CGI es una
opción para el tipo de situaciones en las que por alguna
razón no se desea integrar PHP como módulo de
algún software de servidor web (como Apache), o en donde
se espera usar PHP con diferentes tipos de capas que envuelven el
entorno CGI para crear ambientes chroot y setuid seguros para la
ejecución de scripts. Esta configuración usualmente
involucra la instalación de un binario ejecutable del
intérprete PHP en el directorio cgi-bin del servidor
web. El aviso de seguridad de CERT CA-96.11 recomienda que se evite la
colocación de cualquier intérprete bajo
cgi-bin. Incluso si el binario PHP puede ser usado como un
intérprete independiente, PHP está diseñado
para prevenir el tipo de ataques que esta configuración
hace posible:
Acceso a archivos del sistema: http://mi.servidor/cgi-bin/php?/etc/passwd
La información del query en una URL, la cual viene
después del signo de interrogación (?), es pasada
como argumentos de lÃnea de comandos al
intérprete por la interfaz CGI. Usualmente los
intérpretes abren y ejecutan el archivo especificado
como primer argumento de la lÃnea de comandos.
Cuando es invocado como un binario CGI, PHP se rehúsa a
interpretar los argumentos de la lÃnea de comandos.
Acceso a cualquier documento web en el servidor: http://mi.servidor/cgi-bin/php/zona_secreta/doc.html
El segmento de la URL que sigue al nombre del binario de PHP,
que contiene la información sobre la ruta /zona_secreta/doc.html es usada
convencionalmente para especificar el nombre de un archivo que
ha de ser abierto e interpretado por el programa
CGI. Usualmente, algunas directivas de
configuración del servidor web (Apache: Action) son
usadas para redireccionar peticiones de documentos
como http://mi.servidor/zona_secreta/script.php
al intérprete de PHP. Bajo este modelo, el servidor web
revisa primero los permisos de acceso al directorio /zona_secreta, y después de eso
crea la petición de redireccionamiento a http://mi.servidor/cgi-bin/php/zona_secreta/script.php.
Desafortunadamente, si la petición se hace originalmente
en esta forma, no se realizan chequeos de acceso por parte del
servidor web para el archivo /zona_secreta/script.php,
únicamente para el archivo /cgi-bin/php. De este modo, cualquier
usuario capaz de acceder a /cgi-bin/php es capaz también de
acceder a cualquier documento protegido en el servidor web.
En PHP, la configuración de tiempo de compilación
--enable-force-cgi-redirect
y las directivas de configuración en tiempo de
ejecución doc_root y
user_dir pueden ser usadas
para prevenir este tipo de ataques, si el árbol de
documentos del servidor llegara a tener directorio alguno con
restricciones de acceso. Consulte las siguientes secciones para
una explicación detallada de las diferentes
combinaciones.
add a note
User Contributed Notes
Instalación como un binario CGI
phpD0TnetATmoritzHYPHONnaumannD0Tcom
09-Jan-2006 09:56
One of the most common reasons why you get 'No input file specified' (AKA 'the second most useful error message in the world') is that you have set 'doc_root' (in php.ini) to a value which is to the 'DocumentRoot' defined in the apache configuration.
This is the same for other webservers. For example, on lighttpd, make sure the 'server.document-root' value is the same as what is defined as 'doc_root' in php.ini.
phil dot ross at gmail dot com
22-Mar-2005 03:56
In response to grange at club-internet dot fr:
There are a couple of errors in the mod_rewrite directives given. I found that the following works:
RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^cgi-bin/php.cgi - [F]
I removed the = from the RewriteCond and took out the leading / from the RewriteRule.
kschroeder at mirageworks dot com
11-Feb-2005 07:23
I have noticed that some people have noted that running PHP as a CGI program can run slowly compared with a compiled in module. Some have noted that they want to use FastCGI but are hesitant. I found that using the Apache 2's CGID module was a great way to speed up performance almost to the same level as an "so"-installed PHP module but you get the added benefit of running each virtual host under it's own user and group.
In my testing I got 44 pages per second using PHP as a module and I got roughly the same performance (within 5%) running PHP as a CGI program through CGID.
CGID is also really easy to set up. Just add --enable-cgid to your Apache configure command and you're good to go. Just set up PHP as a CGI normally.
I'm sure that there's extra RAM used for this method but RAM is as cheap as borscht anyways so it shouldn't be a major factor when trying to speed up PHP CGI.
Omid
04-Jan-2005 10:39
Here are my two cents of knowledge about php-cgi when running CGI script from prompt:
If you get the "No input file specified." error, create the environment variable "SCRIPT_FILENAME=C:\files\test.php".
If you get "Security Alert!" error and it tells you to create the REDIRECT_STATUS environment variable, it is because you have the SERVER_NAME variable set but not the REDIRECT_STATUS variable.
Hence, if you have SERVER_NAME, you also need REDIRECT_STATUS, but not otherwise.
And you pretty much should have SCRIPT_FILENAME at all time.
grange at club-internet dot fr
29-Dec-2004 01:40
--enable-force-cgi-redirect won't work in FastCGI mode : as of 4.3.10, it is only supported in CGI mode.
However, you can achieve the same result with mod_rewrite under Apache :
RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !=200
RewriteRule /cgi-bin/path/to/php - [F]
This will only allow internal redirection, thus forbidding direct HTTP access to php interpreter (http://www.exemple.com/cgi-bin/path/to/php).
martelli at geoserve dot com dot br
12-Jul-2004 12:25
PHP CGI with VirtualHosts.
This is what I found out while trying to get php to work as CGI with Apache VirtualHosts.
By enabling 'force-cgiredirects', you *must*:
1) set 'cgi.fix_pathinfo=1' in php.ini
2) leave doc_root commented out (php.ini also)
If you miss item 1, the apache logs will show 'unexpected T_STRING' in the php binary.
If you miss item 2, you'll only see 'No input file specified.', instead of the expected output.
You can then turn on the php support for a particular vhost by defining:
Action php-script /cgi-bin/php
inside the corresponding <VirtualHost> directive.
13-Jun-2004 08:26
PHP works with Apache and suEXEC like this:
(Assuming that suEXEC ist allready installed and working)
Install PHP as CGI binary (e.g. in /usr/local/bin/php)
(compile with --enable-force-cgi-redirect)
Create a Link inside cgi-bin directory to make php-cgi accessable:
cd /usr/local/apache/cgi-bin
ln /usr/local/bin/php php
Edit your httpd.conf file:
AddHandler php4-script .php
Action php4-script /cgi-bin/php
<VirtualHost 123.456.789.0:80>
User exampleuser
Group examplegroup
...
</VirtualHost>
Restart Apache
PHP-scripts are now called under the user-id of exampleuser and group-id of examplegroup.
geeky at geeky dot de
02-Sep-2003 07:32
a replacement for suexec is suphp (http://www.suphp.org).
"suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter." (from the website)
goran_johansson at yahoo dot com
17-Feb-2003 06:53
A tip for Windows-users
Just a tip for you so do not do the same mistake as I did:
I just found out that PHP first seem to look in the php-directory for php.ini, and if that file does not exist, it looks in the Windows directory.
I renamed the file php.ini-dist to php.ini and copied it to my Windows directory, and then I modified the infamous "cgi.force_redirect = 0" in the php.ini file located in the Windows directory, to make it work. But it did not because it reads from the "original" php.ini - So when I deleted this php.ini things started working again
matled at gmx dot net
28-Sep-2002 03:53
If you are using php per cgi and have additionally mod_gzip enabled you have to disable mod_gzip for the php cgi binary to use --enable-cgi-redirect. mod_gzip sets the REDIRECT_STATUS always to 200 which makes it impossible for the php binary to know when it was called directly or when it was called by a redirect.
ruben at puettmann dot net
20-Sep-2002 06:29
To use php-cgi with suexec it will be nice that each virtual host has ist's own php.ini. This goes with :
SetEnv PHPRC /var/www/server/www.test.com/conf
But suexec will kill this enviromet cause It don't know that it is "save" so you must edit the suexec.c for compiling ....
phobo#paradise.net.nz
02-Oct-2001 07:28
If you do virutal hosting, you can turn safe mode on and off for different Apache Virutal Hosts using the php_admin_value directive. This also allows you to have customised maximum execution times, disabled functions, etc; anything which is set in php.ini. Note that by placing a base_dir for each virutal host, this means PHP CANNOT access files below this heirachy; strongly recomended for customer hosting.
Example (httpd.conf):
[VirtualHost 127.0.0.1:80]
DocumentRoot /var/www/html/safephphost/
ServerName safephp
php_admin_value safe_mode 1
php_admin_value open_base_dir /var/www/html/safephphost/
php_admin_value sendmail_from phobo#paradise.net.nz
[/VirtualHost]
Am not sure which versions this started working with but does with Apache 1.3.19/PHP4.04pl1.
yohgaki at hotmail dot com
12-Apr-2001 11:44
If you care about security, you are better of setting
register_globals = off
enable_track_vars = on (Always on from PHP4.0.3)
Default setting for variable order is
EGPCS
(ENV VARS/GET VARS/POST VARS/COOKIE VARS/SESSION VARS)
Imagine if you are rely on ENV VAR but it was orver written with GET/POST/COOKIE vars?
michel dot jansens at ulb dot ac dot be
09-Apr-2001 10:21
If you want to use suexec and reference your php interpreter via #!/usr/local/bin/php, be shure to compile php WITHOUT --enable-force-cgi-redirect.
This might seems obvious, but I spent 2 days on this :-(
12-Mar-2001 01:39
The configuration option '--enable-force-cgi-redirect' is supported by Zeus Web Server 3.3.8.2 (at least, that's what I've tried it on - it make work on previous versions).
steeven at kali dot com dot cn
18-Jan-2001 01:54
suEXEC require CGI mode, and slow down the scripts. I did them like this:
1. Install php as DSO mode. (for max speed and low secure)
2. Make a seperate CGI install with --enable-force-cgi-redirect, place php to cgi-bin
3 For more secure with suEXEC, choose one of the following method:
3-1: Place a .htaccess file containing this to override main config:
AddType application/x-httpd-wphp php
Action application/x-httpd-wphp /cgi-bin/php
All php files in subdirectory will be protected.
3-2: add following in httpd.conf:
AddType application/x-httpd-wphp sphp
Action application/x-httpd-wphp /cgi-bin/php
then each sensitive php file should be renamed to .sphp
Add "php_value doc_root /home/user/html_docs" to each virtual host directive in httpd.conf
tech at ovh dot net
22-Oct-2000 05:59
errata:
binfmt_misc only works on linux system.
another clean solution is to hack suexec.c of apache
and force all .php scripts to be executed with php compiled
in cgi mode.
suexec.c
in place
if (!(prg_info.st_mode & S_IXUSR)) {
just
if (!(prg_info.st_mode & S_IXUSR) & (strstr(cmd, ".php") == NULL)) {
in place
execv(cmd, &argv[3]);
just
if (strstr(cmd, ".php")) {
execl("/usr/local/bin/php", "php", cmd, NULL);
}
else {
execv(cmd, &argv[3]);
}
kstone at trivergent dot net
04-May-2000 02:01
Better yet, use binfmt_misc: (linux only)
echo :php3:E::php3::/usr/bin/php: > /proc/sys/fs/binfmt_misc/register
Eliminates the need for the #! at the top of the file.
| |
| | Citas célebres | Encerrado en su naturaleza e infinito, en sus necesidades, el hombre no es sino un dios caído que se acuerda del cielo. Alphonse de Lamartine | | Citas en tu mail | | ©Contenidos Gratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|