Buscar..


Método de solicitud: GET

Es bastante fácil llamar a un script CGI a través de GET .
Primero necesitarás la encoded url del script.

Entonces usted agrega un signo de interrogación ? seguido de las variables.

  • Cada variable debe tener dos secciones separadas por = .
    La primera sección debe ser siempre un nombre único para cada variable,
    Mientras que la segunda parte tiene valores solo en ella.
  • Las variables están separadas por &
  • La longitud total de la cadena no debe superar los 255 caracteres
  • Los nombres y valores deben estar codificados en html (reemplace: </, /?: @ & = + $ )
    Insinuación:
    Cuando se utiliza html-forms, el método de solicitud puede generarse por sí mismo.
    Con Ajax puede codificar todo a través de encodeURI y encodeURIComponent

Ejemplo:

http://www.example.com/cgi-bin/script.sh?var1=Hello%20World!&var2=This%20is%20a%20Test.&

El servidor debe comunicarse a través del Intercambio de recursos de origen cruzado (CORS) solamente, para que la solicitud sea más segura. En este escaparate usamos CORS para determinar el tipo de Data-Type que queremos usar.

Hay muchos Data-Types que podemos elegir, los más comunes son ...

  • texto / html
  • Texto sin formato
  • aplicación / json

Al enviar una solicitud, el servidor también creará muchas variables de entorno. Por ahora, las variables de entorno más importantes son $REQUEST_METHOD y $QUERY_STRING .

El Método de Solicitud tiene que ser GET nada más!
La cadena de consulta incluye todos los html-endoded data .

La secuencia de comandos

#!/bin/bash
    
# CORS is the way to communicate, so lets response to the server first
echo "Content-type: text/html"    # set the data-type we want to use
echo ""    # we dont need more rules, the empty line initiate this.

# CORS are set in stone and any communication from now on will be like reading a html-document.
# Therefor we need to create any stdout in html format!
    
# create html scructure and send it to stdout
echo "<!DOCTYPE html>"
echo "<html><head>"
    
# The content will be created depending on the Request Method 
if [ "$REQUEST_METHOD" = "GET" ]; then
   
    # Note that the environment variables $REQUEST_METHOD and $QUERY_STRING can be processed by the shell directly. 
    # One must filter the input to avoid cross site scripting.
    
    Var1=$(echo "$QUERY_STRING" | sed -n 's/^.*var1=\([^&]*\).*$/\1/p')    # read value of "var1"
    Var1_Dec=$(echo -e $(echo "$Var1" | sed 's/+/ /g;s/%\(..\)/\\x\1/g;'))    # html decode
    
    Var2=$(echo "$QUERY_STRING" | sed -n 's/^.*var2=\([^&]*\).*$/\1/p')
    Var2_Dec=$(echo -e $(echo "$Var2" | sed 's/+/ /g;s/%\(..\)/\\x\1/g;'))
    
    # create content for stdout
    echo "<title>Bash-CGI Example 1</title>"
    echo "</head><body>"
    echo "<h1>Bash-CGI Example 1</h1>"
    echo "<p>QUERY_STRING: ${QUERY_STRING}<br>var1=${Var1_Dec}<br>var2=${Var2_Dec}</p>"    # print the values to stdout

else

    echo "<title>456 Wrong Request Method</title>"
    echo "</head><body>"
    echo "<h1>456</h1>"
    echo "<p>Requesting data went wrong.<br>The Request method has to be \"GET\" only!</p>"

fi

echo "<hr>"
echo "$SERVER_SIGNATURE"    # an other environment variable
echo "</body></html>"    # close html
    
exit 0

El documento html se verá así ...

<html><head>
<title>Bash-CGI Example 1</title>
</head><body>
<h1>Bash-CGI Example 1</h1>
<p>QUERY_STRING: var1=Hello%20World!&amp;var2=This%20is%20a%20Test.&amp;<br>var1=Hello World!<br>var2=This is a Test.</p>
<hr>
<address>Apache/2.4.10 (Debian) Server at example.com Port 80</address>


</body></html>

La salida de las variables se verá así ...

var1=Hello%20World!&var2=This%20is%20a%20Test.&
Hello World!
This is a Test.
Apache/2.4.10 (Debian) Server at example.com Port 80

Efectos secundarios negativos ...

  • Toda la codificación y decodificación no se ve bien, pero es necesaria
  • La Solicitud será pública y dejará una bandeja detrás.
  • El tamaño de una solicitud es limitado
  • Necesita protección contra Cross-Side-Scripting (XSS)

Método de solicitud: POST / w JSON

El uso del Método de solicitud POST en combinación con SSL hace que la transferencia de datos sea más segura.

Adicionalmente...

  • La mayoría de la codificación y decodificación ya no es necesaria
  • La URL será visible para cualquiera y debe estar codificada en url.
    Los datos se enviarán por separado y, por lo tanto, se deben proteger mediante SSL.
  • El tamaño de los datos es casi ilimitado.
  • Todavía necesita protección contra Cross-Side-Scripting (XSS)

Para mantener este escaparate simple queremos recibir datos JSON.
y la comunicación debe ser sobre Intercambio de recursos de origen cruzado (CORS).

La siguiente secuencia de comandos también mostrará dos tipos de contenido diferentes.

#!/bin/bash

exec 2>/dev/null    # We dont want any error messages be printed to stdout
trap "response_with_html && exit 0" ERR    # response with an html message when an error occurred and close the script

function response_with_html(){    
    echo "Content-type: text/html"
    echo ""
    echo "<!DOCTYPE html>"
    echo "<html><head>"
    echo "<title>456</title>"
    echo "</head><body>"
    echo "<h1>456</h1>"
    echo "<p>Attempt to communicate with the server went wrong.</p>"
    echo "<hr>"
    echo "$SERVER_SIGNATURE"
    echo "</body></html>"
}
        
function response_with_json(){
    echo "Content-type: application/json"
    echo ""
    echo "{\"message\": \"Hello World!\"}"
}

if [ "$REQUEST_METHOD" = "POST" ]; then
   
    # The environment variabe $CONTENT_TYPE describes the data-type received
    case "$CONTENT_TYPE" in
    application/json)
        # The environment variabe $CONTENT_LENGTH describes the size of the data
        read -n "$CONTENT_LENGTH" QUERY_STRING_POST        # read datastream 

        # The following lines will prevent XSS and check for valide JSON-Data.
        # But these Symbols need to be encoded somehow before sending to this script
        QUERY_STRING_POST=$(echo "$QUERY_STRING_POST" | sed "s/'//g" | sed 's/\$//g;s/`//g;s/\*//g;s/\\//g' )        # removes some symbols (like \ * ` $ ') to prevent XSS with Bash and SQL.
        QUERY_STRING_POST=$(echo "$QUERY_STRING_POST" | sed -e :a -e 's/<[^>]*>//g;/</N;//ba')    # removes most html declarations to prevent XSS within documents
        JSON=$(echo "$QUERY_STRING_POST" | jq .)        # json encode - This is a pretty save way to check for valide json code
    ;;
    *)
        response_with_html
        exit 0
    ;;
    esac

else
    response_with_html
    exit 0
fi

# Some Commands ...

response_with_json

exit 0

Obtendrá {"message":"Hello World!"} Como respuesta cuando envíe datos JSON a través de POST a este script. Todo lo demás recibirá el documento html.

Importante es también el varialbe $JSON . Esta variable está libre de XSS, pero aún podría tener valores incorrectos y debe verificarse primero. Por favor tenlo en mente.

Este código funciona de manera similar sin JSON.
Usted podría obtener cualquier información de esta manera.
Solo necesita cambiar el tipo de Content-Type para sus necesidades.

Ejemplo:

if [ "$REQUEST_METHOD" = "POST" ]; then 
    case "$CONTENT_TYPE" in
    application/x-www-form-urlencoded)
            read -n "$CONTENT_LENGTH" QUERY_STRING_POST
    text/plain)
            read -n "$CONTENT_LENGTH" QUERY_STRING_POST
    ;;
    esac
fi

Por último, pero no menos importante, no olvide responder a todas las solicitudes, de lo contrario, los programas de terceros no sabrán si tuvieron éxito.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow