code:
#!/bin/bash
u_dir="/etc/adm-lite/userDIR"
tmp_verifica="/etc/adm-lite/tmp_tmp"
_arquivo1="/etc/adm-lite/tmp_arq1"
_arquivo2="/etc/adm-lite/tmp_arq2"
_arquivo3="/etc/adm-lite/tmp_arq3"
_arquivo4="/etc/adm-lite/tmp_arq4"
[[ ! -d "$u_dir" ]] && mkdir $u_dir
[[ -e "$_arquivo1" ]] && rm $_arquivo1
[[ -e "$_arquivo2" ]] && rm $_arquivo2
[[ -e "$_arquivo3" ]] && rm $_arquivo3
[[ -e "$_arquivo4" ]] && rm $_arquivo4

function_dropb () {
port_dropbear=`ps aux | grep dropbear | awk NR==1 | awk '{print $17;}'`
[[ $port_dropbear = "" ]] && return
log=/var/log/auth.log
loginsukses='Password auth succeeded'
echo ' '
pids=`ps ax |grep dropbear |grep  " $port_dropbear" |awk -F" " '{print $1}'`
for pid in $pids
do
    pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'`
    i=0
    for pidend in $pidlogs
    do
    let i=i+1
    done
    if [ $pidend ]; then
       login=`grep $pid $log |grep "$pidend" |grep "$loginsukses"`
       PID=$pid
       user=`echo $login |awk -F" " '{print $10}' | sed -r "s/'/ /g"`
       waktu=`echo $login |awk -F" " '{print $2"-"$1,$3}'`
       while [ ${#waktu} -lt 13 ]; do
       waktu=$waktu" "
       done
       while [ ${#user} -lt 16 ]; do
       user=$user" "
       done
       while [ ${#PID} -lt 8 ]; do
       PID=$PID" "
       done
     echo "$user $PID $waktu"
    fi
done
echo ""
return
}

function_onlines () {
(
unset _on
for user in `awk -F : '$3 > 900 { print $1 }' /etc/passwd |grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
usurnum=$(ps -u $user | grep sshd |wc -l)
[[ "$usurnum" -gt 0 ]] && _on+="$usurnum+"
usurnum=$(function_dropb | grep "$user" | wc -l)
[[ "$usurnum" -gt 0 ]] && _on+="$usurnum+"
done
#Terceira Etapa#
for userovpn in `cat /etc/passwd | grep ovpn | awk -F: '{print $1}'`; do
us=$(cat /etc/openvpn/openvpn-status.log | grep $userovpn | wc -l)
[[ "$us" != "0" ]] && _on+="1+"
done
#Usuarios Vencidos
datenow=$(date +%s)
for user in $(awk -F: '{print $1}' /etc/passwd); do
expdate=$(chage -l $user|awk -F: '/Account expires/{print $2}')
echo $expdate|grep -q never && continue
datanormal=$(date -d"$expdate" '+%d/%m/%Y')
expsec=$(date +%s --date="$expdate")
diff=$(echo $datenow - $expsec|bc -l)
echo $diff|grep -q ^\- && continue
vencidos[1]+="1+"
done
#Fazendo A Soma#
_on+="0"
_on=$(echo $_on|bc)
vencidos[1]+="0"
vencidos[1]=$(echo ${vencidos[1]}|bc)
echo "$_on" > ./onlines
echo "${vencidos[1]}" > ./vencidos
) &
}

fun_ovpn_onl () {
for userovpn in `cat /etc/passwd | grep ovpn | awk -F: '{print $1}'`; do
us=$(cat /etc/openvpn/openvpn-status.log | grep $userovpn | wc -l)
[[ "$us" != "0" ]] && echo "$userovpn"
done
}

function_usertime () {
(
declare -A data
declare -A time
declare -A time2
declare -A timefinal
tempousers="./tempo_conexao"
usr_pids_var="./userDIR"
[[ ! -e $tempousers ]] && touch $tempousers
_data_now=$(date +%s)
 for user in `awk -F : '$3 > 900 { print $1 }' /etc/passwd |grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
 unset ssh
 [[ -e $usr_pids_var/$user.pid ]] && source $usr_pids_var/$user.pid
ssh+="$(ps -u $user | grep sshd |wc -l)+"
ssh+="$(function_dropb | grep "$user" | wc -l)+"
[[ -e /etc/openvpn/server.conf ]] && ssh+="$(fun_ovpn_onl | grep "$user" | wc -l)+"
ssh+="0"
user_pid=$(echo $ssh|bc)
if [ "$user_pid" -gt "0" ]; then
 [[ "${data[$user]}" = "" ]] && data[$user]="$_data_now"
 if [ ! -e $usr_pids_var/$user.pid2  ]; then
  [[ -e $usr_pids_var/$user.pid ]] && cp $usr_pids_var/$user.pid $usr_pids_var/$user.pid2
 fi
fi
if [ "$user_pid" = "0" ]; then
unset data[$user]
[[ -e "$usr_pids_var/$user.pid" ]] && rm $usr_pids_var/$user.pid
[[ -e $usr_pids_var/$user.pid2 ]] && rm $usr_pids_var/$user.pid2
fi
if [ "${data[$user]}" != "" ]; then
time[$user]=$(($_data_now - ${data[$user]}))
time2[$user]=$(cat $tempousers | grep "$user" | awk '{print $2}')
  [[ "${time2[$user]}" = "" ]] && time2[$user]="0"
timefinal[$user]=$((${time2[$user]} + ${time[$user]}))
_arquivo=$(cat $tempousers |grep -v "$user")
echo "$_arquivo" > $tempousers
echo "$user ${timefinal[$user]}" >> $tempousers
echo "data[$user]=$_data_now" > $usr_pids_var/$user.pid
fi
 done
) &
}

function_killmultiloguin () {
(
for user in `awk -F : '$3 > 900 { print $1 }' /etc/passwd |grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
unset pid_limite && unset sshd_on && unset drop_on
sshd_on=$(ps -u $user|grep sshd|wc -l)
drop_on=$(function_dropb|grep "$user"|wc -l)
[[ -e $u_dir/$user ]] && pid_limite=$(cat $u_dir/$user | grep "limite:" | awk '{print $2}') || pid_limite="999"
[[ $pid_limite != +([0-9]) ]] && pid_limite="999"
#LIMITE DROPBEAR
   [[ "$drop_on" -gt "$pid_limite" ]] && {
           kill=$((${drop_on}-${pid_limite}))
           pids=$(function_dropb|grep "$user"|awk '{print $2}'|tail -n${kill})
           for pid in `echo $pids`; do
           kill $pid
           done
    }
#LIMITE OPENSSH
   [[ "$sshd_on" -gt "$pid_limite" ]] && {
           kill=$((${sshd_on}-${pid_limite}))
           pids=$(ps x|grep [[:space:]]$user[[:space:]]|grep -v grep|grep -v pts|awk '{print $1}'|tail -n${kill})
           for pid in `echo $pids`; do
           kill $pid
           done
    }
done
sleep 3s
) &
}

fun_net () {
(
log_0="/tmp/tcpdum"
log_1="/tmp/tcpdump"
log_2="/tmp/tcpdumpLOG"
usr_dir="/etc/adm-lite/userDIR/usr_cnx"
[[ -e "$log_1" ]] &&  mv -f $log_1 $log_2
[[ ! -e $usr_dir ]] && touch $usr_dir
#ENCERRA TCP
for pd in `ps x | grep tcpdump | grep -v grep | awk '{print $1}'`; do
kill -9 $pd > /dev/null 2>&1
done
#INICIA TCP
tcpdump -s 50 -n 1> /tmp/tcpdump 2> /dev/null &
[[ ! -e /tmp/tcpdump ]] && touch /tmp/tcpdump
#ANALIZA USER
for user in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
touch /tmp/$user
ip_openssh $user > /dev/null 2>&1
ip_drop $user > /dev/null 2>&1
sed -i '/^$/d' /tmp/$user
pacotes=$(paste -sd+ /tmp/$user | bc)
rm /tmp/$user
if [ "$pacotes" != "" ]; then
  if [ "$(cat $usr_dir | grep "$user")" != "" ]; then
  pacotesuser=$(cat $usr_dir | grep "$user" | awk '{print $2}')
  [[ $pacotesuser = "" ]] && pacotesuser=0
  [[ $pacotesuser != +([0-9]) ]] && pacotesuser=0
  ussrvar=$(cat $usr_dir | grep -v "$user")
  echo "$ussrvar" > $usr_dir
  pacotes=$(($pacotes+$pacotesuser))
  echo -e "$user $pacotes" >> $usr_dir
  else
  echo -e "$user $pacotes" >> $usr_dir
  fi
fi
unset pacotes
done
) &
}

ip_openssh () {
user="$1"
for ip in `lsof -u $user -P -n | grep "ESTABLISHED" | awk -F "->" '{print $2}' |awk -F ":" '{print $1}' | grep -v "127.0.0.1"`; do
 packet=$(cat $log_2 | grep "$ip" | wc -l)
 echo "$packet" >> /tmp/$user
 unset packet
done
}

ip_drop () {
user="$1"
loguser='Password auth succeeded'
touch /tmp/drop
for ip in `cat /var/log/auth.log | tail -100 | grep "$user" | grep "$loguser" | awk -F "from" '{print $2}' | awk -F ":" '{print $1}'`; do
 if [ "$(cat /tmp/drop | grep "$ip")" = "" ]; then
 packet=$(cat $log_2 | grep "$ip" | wc -l)
 echo "$packet" >> /tmp/$user
 echo "$ip" >> /tmp/drop
 fi
done
rm /tmp/drop
}

while true; do
function_killmultiloguin > /dev/null 2>&1
sleep 7s
done


code:
#!/bin/bash
source menu-txt
echo -ne "${cor[6]}"
read -p " ${txt[9]} " _selecao
case $_selecao in
0)
clear
echo -e "${cor[0]}"
exit
;;
1)
clear
source user
exit
;;
2)
clear
source ferramentas
exit
;;
3)
fun_atualizar
exit
;;
4)
remover_adm
exit
;;
5)
funcao_cores
source menu
exit
;;
6)
funcao_verificacao > /dev/null 2>&1
source menu
exit
;;
7)
funcao_idioma
source menu
exit
;;
8)
if [[ -e /etc/bash.bashrc-bakup ]]; then
mv -f /etc/bash.bashrc-bakup /etc/bash.bashrc
cat /etc/bash.bashrc | grep -v "/bin/adm" > /tmp/bash
mv -f /tmp/bash /etc/bash.bashrc
echo -e "${cor[1]} =================================== ${cor[0]}"
echo -e "${cor[2]} \033[1;32mREMOVED SUCESS!"
echo -e "${cor[1]} =================================== ${cor[0]}"
elif [[ -e /etc/bash.bashrc ]]; then
cat /etc/bash.bashrc|grep -v /bin/adm > /etc/bash.bashrc.2
echo '/bin/adm' >> /etc/bash.bashrc.2
cp /etc/bash.bashrc /etc/bash.bashrc-bakup
mv -f /etc/bash.bashrc.2 /etc/bash.bashrc
echo -e "${cor[1]} =================================== ${cor[0]}"
echo -e "${cor[2]} \033[1;32mAUTORUN START SUCESS!"
echo -e "${cor[1]} =================================== ${cor[0]}"
fi
sleep 2s
source menu
exit
;;
9)
$value > /dev/null 2>&1
chmod +x /etc/adm-lite/*
[[ -e /etc/adm-lite/idioma_menuinst ]] && idioma=$(cat /etc/adm-lite/idioma_menuinst|head -1) || idioma="pt"
value=$(vary_rex "2f6574632f61646d2d6c6974652f6d656e755f696e7374")
${value} ${idioma}
;;
*)
source menu
;;
esac

path: Modulo/menu

license: unknown


code:
#!/bin/bash
[[ $1 != "" ]] && id="$1" || id="es"
barra="\033[1;34m =================================== \033[1;37m"
_cores="./cores"
_dr="./idioma"
[[ "$(echo ${txt[0]})" = "" ]] && source idioma_geral

#LISTA PORTAS
mportas () {
unset portas
portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
while read port; do
var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n"
done <<< "$portas_var"
i=1
echo -e "$portas"
}

#MEU IP
fun_ip () {
MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
MEU_IP2=$(wget -qO- ipv4.icanhazip.com)
[[ "$MEU_IP" != "$MEU_IP2" ]] && IP="$MEU_IP2" || IP="$MEU_IP"
}

#ETHOOL SSH
fun_eth () {
eth=$(ifconfig | grep -v inet6 | grep -v lo | grep -v 127.0.0.1 | grep "encap:Ethernet" | awk '{print $1}')
    [[ $eth != "" ]] && {
    echo -e "$barra"
    echo -e "${cor[3]} $(source trans -b pt:${id} "Aplicar Sistema Para Melhorar Pacotes Ssh?")"
    echo -e "${cor[3]} $(source trans -b pt:${id} "Opcao Para Usuarios Avancados")"
    echo -e "$barra"
    read -p " [S/N]: " -e -i n sshsn
           [[ "$sshsn" = @(s|S|y|Y) ]] && {
           echo -e "${cor[1]} $(source trans -b pt:${id} "Correcao de problemas de pacotes no SSH...")"
           echo -e " $(source trans -b pt:${id} "Qual A Taxa RX")"
           echo -ne "[ 1 - 999999999 ]: "; read rx
           [[ "$rx" = "" ]] && rx="999999999"
           echo -e " $(source trans -b pt:${id} "Qual A Taxa TX")"
           echo -ne "[ 1 - 999999999 ]: "; read tx
           [[ "$tx" = "" ]] && tx="999999999"
           apt-get install ethtool -y > /dev/null 2>&1
           ethtool -G $eth rx $rx tx $tx > /dev/null 2>&1
           }
     echo -e "$barra"
     }
}

#FUN_BAR
fun_bar () {
comando[0]="$1"
comando[1]="$2"
 (
[[ -e $HOME/fim ]] && rm $HOME/fim
${comando[0]} -y > /dev/null 2>&1
${comando[1]} -y > /dev/null 2>&1
touch $HOME/fim
 ) > /dev/null 2>&1 &
echo -ne "\033[1;33m ["
while true; do
   for((i=0; i<18; i++)); do
   echo -ne "\033[1;31m##"
   sleep 0.1s
   done
   [[ -e $HOME/fim ]] && rm $HOME/fim && break
   echo -e "\033[1;33m]"
   sleep 1s
   tput cuu1
   tput dl1
   echo -ne "\033[1;33m ["
done
echo -e "\033[1;33m]\033[1;31m -\033[1;32m 100%\033[1;37m"
}

#INSTALADOR SQUID
fun_squid  () {
  if [[ -e /etc/squid/squid.conf ]]; then
  var_squid="/etc/squid/squid.conf"
  elif [[ -e /etc/squid3/squid.conf ]]; then
  var_squid="/etc/squid3/squid.conf"
  fi
  #Reiniciando
  service squid3 restart > /dev/null 2>&1
  service squid restart > /dev/null 2>&1
  [[ -e $var_squid ]] && {
  echo -e "$barra\n\033[1;32m $(source trans -b es:${id} "REMOVIENDO SQUID")\n$barra"
  fun_bar "apt-get remove squid3 -y"
  service squid stop > /dev/null 2>&1
  service squid3 stop > /dev/null 2>&1
  echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "Procedimento Concluido")\n$barra"
  [[ -e $var_squid ]] && rm $var_squid
  return 0
  }
#Instalar
echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "INSTALADOR SQUID ADM-ULTIMATE")\n$barra"
fun_ip
echo -ne " $(source trans -b pt:${id} "Confirme seu ip")"; read -p ": " -e -i $IP ip
echo -e "$barra\n $(source trans -b pt:${id} "Agora Escolha as Portas que Deseja No Squid")"
echo -e " $(source trans -b pt:${id} "Escolha As Portas, Exemplo: 80 8080 3128")"
echo -ne " $(source trans -b pt:${id} "Digite as Portas:") "; read portasx
echo -e "$barra"
totalporta=($portasx)
unset PORT
   for((i=0; i<${#totalporta[@]}; i++)); do
        [[ $(mportas|grep "${totalporta[$i]}") = "" ]] && {
        echo -e "\033[1;33m $(source trans -b pt:${id} "Porta Escolhida:")\033[1;32m ${totalporta[$i]} OK"
        PORT+="${totalporta[$i]}\n"
        } || {
        echo -e "\033[1;33m $(source trans -b pt:${id} "Porta Escolhida:")\033[1;31m ${totalporta[$i]} FAIL"
        }
   done
  [[ "$(echo -e $PORT)" = "" ]] && {
  echo -e "\033[1;31m $(source trans -b pt:${id} "Nenhuma Porta Valida Foi Escolhida")\033[0m"
  return 1
  }
echo -e "$barra"
echo -e " $(source trans -b pt:${id} "INSTALANDO SQUID")"
echo -e "$barra"
fun_bar "apt-get install squid3 -y"
echo -e "$barra"
echo -e " $(source trans -b pt:${id} "INICIANDO CONFIGURACAO")"
echo -e "$barra"
echo -e "" > /etc/payloads
#A�adir Host Squid
payload="/etc/payloads"
echo -e "" > /etc/payloads
echo -e " ${txt[219]}"
echo -e " ${txt[220]}"
read -p " $(source trans -b es:${id} "Agregar Host"): " hos
if [[ $hos != \.* ]]; then
echo -e "$barra"
echo -e "\033[1;31m $(source trans -b es:${id} " [!] Host-Squid debe iniciar con "."")\033[0m"
echo -e "\033[1;31m $(source trans -b es:${id} " Asegurese de agregarlo despues corretamente!")\033[0m"
fi
host="$hos/"
if [[ -z $host ]]; then
echo -e "$barra"
echo -e "\033[1;31m $(source trans -b es:${id} " [!] Host-Squid no agregado")"
echo -e "\033[1;31m $(source trans -b es:${id} " Asegurese de agregarlo despues!")\033[0m"
fi
echo "$host" >> $payload && grep -v "^$" $payload > /tmp/a && mv /tmp/a $payload
echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "Agora Escolha Uma Conf Para Seu Proxy")\n$barra"
echo -e " |1| $(source trans -b pt:${id} "Comum")"
echo -e " |2| $(source trans -b pt:${id} "Customizado") -\033[1;31m $(source trans -b pt:${id} "Usuario Deve Ajustar")\033[1;37m\n$barra"
read -p " [1/2]: " -e -i 1 proxy_opt
unset var_squid
if [[ -d /etc/squid ]]; then
var_squid="/etc/squid/squid.conf"
elif [[ -d /etc/squid3 ]]; then
var_squid="/etc/squid3/squid.conf"
fi
if [[ "$proxy_opt" = @(02|2) ]]; then
echo -e "#ConfiguracaoSquiD
acl url1 dstdomain -i $ip
acl url2 dstdomain -i 127.0.0.1
acl url3 url_regex -i '/etc/payloads'
acl url4 dstdomain -i localhost
acl accept dstdomain -i GET
acl accept dstdomain -i POST
acl accept dstdomain -i OPTIONS
acl accept dstdomain -i CONNECT
acl accept dstdomain -i PUT
acl HEAD dstdomain -i HEAD
acl accept dstdomain -i TRACE
acl accept dstdomain -i OPTIONS
acl accept dstdomain -i PATCH
acl accept dstdomain -i PROPATCH
acl accept dstdomain -i DELETE
acl accept dstdomain -i REQUEST
acl accept dstdomain -i METHOD
acl accept dstdomain -i NETDATA
acl accept dstdomain -i MOVE
acl all src 0.0.0.0/0
http_access allow url1
http_access allow url2
http_access allow url3
http_access allow url4
http_access allow accept
http_access allow HEAD
http_access deny all

# Request Headers Forcing

request_header_access Allow allow all
request_header_access Authorization allow all
request_header_access WWW-Authenticate allow all
request_header_access Proxy-Authorization allow all
request_header_access Proxy-Authenticate allow all
request_header_access Cache-Control allow all
request_header_access Content-Encoding allow all
request_header_access Content-Length allow all
request_header_access Content-Type allow all
request_header_access Date allow all
request_header_access Expires allow all
request_header_access Host allow all
request_header_access If-Modified-Since allow all
request_header_access Last-Modified allow all
request_header_access Location allow all
request_header_access Pragma allow all
request_header_access Accept allow all
request_header_access Accept-Charset allow all
request_header_access Accept-Encoding allow all
request_header_access Accept-Language allow all
request_header_access Content-Language allow all
request_header_access Mime-Version allow all
request_header_access Retry-After allow all
request_header_access Title allow all
request_header_access Connection allow all
request_header_access Proxy-Connection allow all
request_header_access User-Agent allow all
request_header_access Cookie allow all
request_header_access All deny all

# Response Headers Spoofing

reply_header_access Via deny all
reply_header_access X-Cache deny all
reply_header_access X-Cache-Lookup deny all

#portas" > $var_squid
for pts in $(echo -e $PORT); do
echo -e "http_port $pts" >> $var_squid
done
echo -e "
#nome
visible_hostname ADM-MANAGER

via off
forwarded_for off
pipeline_prefetch off" >> $var_squid
 else
echo -e "#ConfiguracaoSquiD
acl url1 dstdomain -i $ip
acl url2 dstdomain -i 127.0.0.1
acl url3 url_regex -i '/etc/payloads'
acl url4 dstdomain -i localhost
acl all src 0.0.0.0/0
http_access allow url1
http_access allow url2
http_access allow url3
http_access allow url4
http_access deny all

#portas" > $var_squid
for pts in $(echo -e $PORT); do
echo -e "http_port $pts" >> $var_squid
done
echo -e "
#nome
visible_hostname ADM-MANAGER

via off
forwarded_for off
pipeline_prefetch off" >> $var_squid
fi
fun_eth
echo -e "$barra\n \033[1;31m [ ! ] \033[1;33m$(source trans -b pt:${id} "REINICIANDO SERVICOS")"
squid3 -k reconfigure > /dev/null 2>&1
squid -k reconfigure > /dev/null 2>&1
service ssh restart > /dev/null 2>&1
service squid3 restart > /dev/null 2>&1
service squid restart > /dev/null 2>&1
echo -e " \033[1;32m[OK]"
echo -e "$barra\n ${cor[3]}$(source trans -b pt:${id} "SQUID CONFIGURADO")\n$barra"
mportas > /tmp/portz
while read portas; do
[[ $portas = "" ]] && break
done < /tmp/portz
#UFW
for ufww in $(mportas|awk '{print $2}'); do
ufw allow $ufww > /dev/null 2>&1
done
}

fun_dropbear () {
 [[ -e /etc/default/dropbear ]] && {
 echo -e "$barra\n\033[1;32m $(source trans -b es:${id} "REMOVIENDO DROPBEAR")\n$barra"
 fun_bar "apt-get remove dropbear -y"
 echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "Dropbear Removido")\n$barra"
 [[ -e /etc/default/dropbear ]] && rm /etc/default/dropbear
 user -k 443/tcp > /dev/null 2>&1
 return 0
 }
echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "INSTALADOR DROPBEAR ADM-ULTIMATE")\n$barra"
echo -e " $(source trans -b es:${id} "DROPBEAR USA EL PUERTO 443")\033[1;37m"
echo -e "$barra"
   [[ $(mportas|grep 443) != "" ]] && {
   echo -e "\033[1;31m $(source trans -b pt:${id} "PORTA 443 EM USO")\033[1;37m"
   echo -e "\033[1;31m $(source trans -b es:${id} "INTENTE NUEVAMENTE")\033[1;37m"
   fuser -k 443/tcp > /dev/null 2>&1
   echo -e "$barra"
   return 1
   }
sysvar=$(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/      //' | grep -o Ubuntu)
shells=$(cat /etc/shells|grep "/bin/false")
[[ ! ${shells} ]] && echo -e "/bin/false" >> /etc/shells
[[ "$sysvar" != "" ]] && {
echo -e "Port 22
Protocol 2
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes" > /etc/ssh/sshd_config
echo -e "${cor[2]} $(source trans -b pt:${id} "Instalando dropbear")"
echo -e "$barra"
fun_bar "apt-get install dropbear -y"
echo -e "$barra"
touch /etc/dropbear/banner
echo -e "${cor[2]} $(source trans -b pt:${id} "Configurando dropbear")"
echo -e "NO_START=0" > /etc/default/dropbear
echo -e 'DROPBEAR_EXTRA_ARGS="-p 443"' >> /etc/default/dropbear
echo -e 'DROPBEAR_BANNER="/etc/dropbear/banner"' >> /etc/default/dropbear
echo -e "DROPBEAR_RECEIVE_WINDOW=65536" >> /etc/default/dropbear
} || {
echo -e "Port 22
Protocol 2
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes" > /etc/ssh/sshd_config
echo -e "${cor[2]} $(source trans -b pt:${id} "Instalando dropbear")"
echo -e "$barra"
fun_bar "apt-get install dropbear -y"
touch /etc/dropbear/banner
echo -e "$barra"
echo -e "${cor[2]} $(source trans -b pt:${id} "Configurando dropbear")"
echo -e "NO_START=0" > /etc/default/dropbear
echo -e 'DROPBEAR_EXTRA_ARGS="-p 443"' >> /etc/default/dropbear
echo -e 'DROPBEAR_BANNER="/etc/dropbear/banner"' >> /etc/default/dropbear
echo -e "DROPBEAR_RECEIVE_WINDOW=65536" >> /etc/default/dropbear
}
fun_eth
service ssh restart > /dev/null 2>&1
service dropbear restart > /dev/null 2>&1
echo -e "$barra\n${cor[3]} $(source trans -b pt:${id} "Seu dropbear foi configurado com sucesso")\n$barra"
mportas > /tmp/portz
while read portas; do
[[ $portas = "" ]] && break
done < /tmp/portz
#UFW
for ufww in $(mportas|awk '{print $2}'); do
ufw allow $ufww > /dev/null 2>&1
done
}

instala_ovpn () {
parametros_iniciais () {
#Verifica o Sistema
if [[ "$EUID" -ne 0 ]]; then
	echo -e "$barra"
	echo " Sorry, you need to run this as root"
	echo -e "$barra"
	read -p " Enter"
	exit
fi

if [[ ! -e /dev/net/tun ]]; then
	echo -e "$barra"
	echo " The TUN device is not available"
	echo -e "$barra"
	read -p " Enter"
	exit
fi
if [[ -e /etc/debian_version ]]; then
OS="debian"
VERSION_ID=$(cat /etc/os-release | grep "VERSION_ID")
IPTABLES='/etc/iptables/iptables.rules'
SYSCTL='/etc/sysctl.conf'
 [[ "$VERSION_ID" != 'VERSION_ID="7"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="8"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="9"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="14.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="16.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="17.10"' ]] && {
 echo " Sua vers�o do Debian / Ubuntu n�o � suportada."
 while [[ $CONTINUE != @(y|Y|s|S|n|N) ]]; do
 read -p "Continuar ? [y/n]: " -e CONTINUE
 done
 [[ "$CONTINUE" = @(n|N) ]] && return 2
 }
else
echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "Parece que voc� n�o est� executando este instalador em um sistema Debian ou Ubuntu")\n$barra"
return 1
fi
#Pega Interface
NIC=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1)
echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "Sistema Preparado Para Receber o OPENVPN")\n$barra"
}
add_repo () {
#INSTALACAO E UPDATE DO REPOSITORIO
# Debian 7
if [[ "$VERSION_ID" = 'VERSION_ID="7"' ]]; then
echo "deb http://build.openvpn.net/debian/openvpn/stable wheezy main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
# Debian 8
elif [[ "$VERSION_ID" = 'VERSION_ID="8"' ]]; then
echo "deb http://build.openvpn.net/debian/openvpn/stable jessie main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
# Ubuntu 14.04
elif [[ "$VERSION_ID" = 'VERSION_ID="14.04"' ]]; then
echo "deb http://build.openvpn.net/debian/openvpn/stable trusty main" > /etc/apt/sources.list.d/openvpn.list
wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1
fi
}
coleta_variaveis () {
	#Instal
	echo -e " $(source trans -b pt:${id} "Responda as perguntas para iniciar a instalacao")"
	echo -e " $(source trans -b pt:${id} "Responda corretamente")\n$barra "
	echo -e " \033[1;33m$(source trans -b pt:${id} "Primeiro precisamos do ip de sua maquina, este ip esta correto?")\033[0m"
	# Autodetect IP address and pre-fill for the user
	IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
	read -p " IP address: " -e -i $IP IP
	# If $IP is a private IP address, the server must be behind NAT
	if echo "$IP" | grep -qE '^(10\.|172\.1[6789]\.|172\.2[0-9]\.|172\.3[01]\.|192\.168)'; then
		echo
		echo " \033[1;33m$(source trans -b en:${id} This server is behind NAT. What is the public IPv4 address or hostname?)"
		read -p " Public IP address / hostname: " -e PUBLICIP
	fi
	echo -e "$barra\n \033[1;31m$(source trans -b es:${id} "Elegir el tipo de protocolo para") OPENVPN"
	echo -e " \033[1;31m$(source trans -b pt:${id} "A menos que o UDP esteja bloqueado, voc� n�o deve usar o TCP (mais lento)")\n$barra"
	#PROTOCOLO
	while [[ $PROTOCOL != @(UDP|TCP) ]]; do
	read -p " Protocol [UDP/TCP]: " -e -i TCP PROTOCOL
	done
	[[ $PROTOCOL = "UDP" ]] && PROTOCOL=udp
	[[ $PROTOCOL = "TCP" ]] && PROTOCOL=tcp
	echo -e "$barra\n \033[1;33m$(source trans -b pt:${id} "Qual porta voce deseja usar?")\033[0m\n$barra"
	read -p " Port: " -e -i 1194 PORT
	#DNS
	echo -e "$barra\n \033[1;33m$(source trans -b pt:${id} "Qual DNS voce deseja usar?")\n$barra"
	echo "   1) Usar DNS del sistema"
	echo "   2) Cloudflare (Anycast: worldwide)"
	echo "   3) Quad9 (Anycast: worldwide)"
	echo "   4) FDN (France)"
	echo "   5) DNS.WATCH (Germany)"
	echo "   6) OpenDNS (Anycast: worldwide)"
	echo "   7) Google (Anycast: worldwide)"
	echo "   8) Yandex Basic (Russia)"
	echo "   9) AdGuard DNS (Russia)"
	while [[ $DNS != @(1|2|3|4|5|6|7|8|9) ]]; do
	read -p " DNS [1-9]: " -e -i 1 DNS
	done
	#CIPHER
	echo -e "$barra\n \033[1;33m$(source trans -b es:${id} "Elegir el tipo de codificacion para el canal de datos:")\n$barra"
	echo "   1) AES-128-CBC"
	echo "   2) AES-192-CBC"
	echo "   3) AES-256-CBC"
	echo "   4) CAMELLIA-128-CBC"
	echo "   5) CAMELLIA-192-CBC"
	echo "   6) CAMELLIA-256-CBC"
	echo "   7) SEED-CBC"
	while [[ $CIPHER != @(1|2|3|4|5|6|7) ]]; do
	read -p " Cipher [1-7]: " -e -i 1 CIPHER
	done
	case $CIPHER in
	1) CIPHER="cipher AES-128-CBC";;
	2) CIPHER="cipher AES-192-CBC";;
	3) CIPHER="cipher AES-256-CBC";;
	4) CIPHER="cipher CAMELLIA-128-CBC";;
	5) CIPHER="cipher CAMELLIA-192-CBC";;
	6) CIPHER="cipher CAMELLIA-256-CBC";;
	7) CIPHER="cipher SEED-CBC";;
	esac
	echo -e "$barra\n \033[1;33m$(source trans -b pt:${id} "Estamos prontos para configurar seu servidor OpenVPN")\n$barra"
	read -n1 -r -p " Enter to Continue..."
	echo -e "$barra"
	}
parametros_iniciais # BREVE VERIFICACAO
coleta_variaveis # COLETA VARIAVEIS PARA INSTALA��O
add_repo # ATUALIZA REPOSIT�RIO OPENVPN E INSTALA OPENVPN
# Cria Diretorio
[[ ! -d /etc/openvpn ]] && mkdir /etc/openvpn
# Install openvpn
echo -ne "\033[1;31m [ ! ] apt-get update"
apt-get update -q > /dev/null 2>&1 && echo -e "\033[1;32m [OK]"
echo -ne "\033[1;31m [ ! ] apt-get install openvpn curl openssl"
apt-get install -qy openvpn curl > /dev/null 2>&1 && echo -e "\033[1;32m [OK]"
# IP Address
SERVER_IP=$(wget -qO- ipv4.icanhazip.com)
if [[ -z "${SERVER_IP}" ]]; then
    SERVER_IP=$(ip a | awk -F"[ /]+" '/global/ && !/127.0/ {print $3; exit}')
fi
# Generate CA Config
echo -ne "\033[1;31m [ ! ] Generating CA Config"
(
openssl dhparam -out /etc/openvpn/dh.pem 2048 > /dev/null 2>&1
openssl genrsa -out /etc/openvpn/ca-key.pem 2048 > /dev/null 2>&1
chmod 600 /etc/openvpn/ca-key.pem > /dev/null
openssl req -new -key /etc/openvpn/ca-key.pem -out /etc/openvpn/ca-csr.pem -subj /CN=OpenVPN-CA/ > /dev/null 2>&1
openssl x509 -req -in /etc/openvpn/ca-csr.pem -out /etc/openvpn/ca.pem -signkey /etc/openvpn/ca-key.pem -days 365 > /dev/null 2>&1
echo 01 > /etc/openvpn/ca.srl
) && echo -e "\033[1;32m [OK]"
# Gerando server.con
echo -ne "\033[1;31m [ ! ] Generating Server Config"
(
case $DNS in
1)
i=0
grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
dns[$i]="push \"dhcp-option DNS $line\""
done
if [[ ! "${dns[@]}" ]]; then
dns[0]='push "dhcp-option DNS 8.8.8.8"'
dns[1]='push "dhcp-option DNS 8.8.4.4"'
fi
;;
2)
dns[0]='push "dhcp-option DNS 1.0.0.1"'
dns[1]='push "dhcp-option DNS 1.1.1.1"'
;;
3)
dns[0]='push "dhcp-option DNS 9.9.9.9"'
dns[1]='push "dhcp-option DNS 1.1.1.1"'
;;
4)
dns[0]='push "dhcp-option DNS 80.67.169.40"'
dns[1]='push "dhcp-option DNS 80.67.169.12"'
;;
5)
dns[0]='push "dhcp-option DNS 84.200.69.80"'
dns[1]='push "dhcp-option DNS 84.200.70.40"'
;;
6)
dns[0]='push "dhcp-option DNS 208.67.222.222"'
dns[1]='push "dhcp-option DNS 208.67.220.220"'
;;
7)
dns[0]='push "dhcp-option DNS 8.8.8.8"'
dns[1]='push "dhcp-option DNS 8.8.4.4"'
;;
8)
dns[0]='push "dhcp-option DNS 77.88.8.8"'
dns[1]='push "dhcp-option DNS 77.88.8.1"'
;;
9)
dns[0]='push "dhcp-option DNS 176.103.130.130"'
dns[1]='push "dhcp-option DNS 176.103.130.131"'
;;
esac
cat > /etc/openvpn/server.conf <<EOF
server 10.8.0.0 255.255.255.0
verb 3
duplicate-cn
key client-key.pem
ca ca.pem
cert client-cert.pem
dh dh.pem
keepalive 10 120
persist-key
persist-tun
comp-lzo
float
push "redirect-gateway def1 bypass-dhcp"
${dns[0]}
${dns[1]}

user nobody
group nogroup

${CIPHER}
proto ${PROTOCOL}
port $PORT
dev tun
status openvpn-status.log
EOF
PLUGIN=$(find / | grep openvpn-plugin-auth-pam.so | head -1) && [[ $(echo ${PLUGIN}) != "" ]] && {
echo "client-to-client
client-cert-not-required
username-as-common-name
plugin $PLUGIN login" >> /etc/openvpn/server.conf
}
) && echo -e "\033[1;32m [OK]"

# Generate Client Config
echo -ne "\033[1;31m [ ! ] Generating Client Config"
(
openssl genrsa -out /etc/openvpn/client-key.pem 2048 > /dev/null 2>&1
chmod 600 /etc/openvpn/client-key.pem
openssl req -new -key /etc/openvpn/client-key.pem -out /etc/openvpn/client-csr.pem -subj /CN=OpenVPN-Client/ > /dev/null 2>&1
openssl x509 -req -in /etc/openvpn/client-csr.pem -out /etc/openvpn/client-cert.pem -CA /etc/openvpn/ca.pem -CAkey /etc/openvpn/ca-key.pem -days 36525 > /dev/null 2>&1
) && echo -e "\033[1;32m [OK]"
teste_porta () {
  echo -ne " \033[1;31m$(source trans -b es:${id} "Verificando: ")"
  sleep 1s
  [[ ! $(mportas | grep $1) ]] && {
    echo -e " \033[1;33m$(source trans -b es:${id} "Abriendo un Puerto en Python")"
    cd /etc/adm-lite
    [[ $(screen -h|wc -l) -lt '30' ]] && apt-get install screen -y
    screen -dmS screen python ./openproxy.py "$1"
    } || {
    echo -e "\033[1;32m [Pass]"
    return 1
    }
   }
echo -e "$barra\n \033[1;33m$(source trans -b es:${id} "Ahora se necesita el puerto de su Proxy Squid (Socks)")"
echo -e " \033[1;33m$(source trans -b pt:${id} "Se nao Existir Proxy na Porta um Proxy Python sera Aberto!")\n$barra"
while [[ $? != "1" ]]; do
read -p " Confirme un Puerto(Proxy): " -e -i 80 PPROXY
teste_porta $PPROXY
done
cat > /etc/openvpn/client-common.txt <<EOF
client
nobind
dev tun
redirect-gateway def1 bypass-dhcp
remote ${SERVER_IP} ${PORT} ${PROTOCOL}
http-proxy ${SERVER_IP} ${PPROXY}
$CIPHER
comp-lzo yes
keepalive 10 20
float
auth-user-pass
EOF
# Iptables
if [[ ! -f /proc/user_beancounters ]]; then
    N_INT=$(ip a |awk -v sip="$SERVER_IP" '$0 ~ sip { print $7}')
    iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o $N_INT -j MASQUERADE
else
    iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source $SERVER_IP
fi
iptables-save > /etc/iptables.conf
cat > /etc/network/if-up.d/iptables <<EOF
#!/bin/sh
iptables-restore < /etc/iptables.conf
EOF
chmod +x /etc/network/if-up.d/iptables
# Enable net.ipv4.ip_forward
sed -i 's|#net.ipv4.ip_forward=1|net.ipv4.ip_forward=1|' /etc/sysctl.conf
echo 1 > /proc/sys/net/ipv4/ip_forward
#Liberando DNS
DDNS=S
agrega_dns () {
echo -e "\033[1;33m $(source trans -b pt:${id} "Digite o DNS que deseja Adicionar")"
read -p " [NewDNS]: " NEWDNS
dns_var=$(cat /etc/hosts|grep -v "$NEWDNS")
echo "127.0.0.1 $NEWDNS" > /etc/hosts
echo "$dns_var" >> /etc/hosts
unset NEWDNS
}
echo -e "$barra\n \033[1;33m$(source trans -b pt:${id} "Ultima Etapa, Configuracoes DNS")\n$barra"
while [[ $DDNS = @(s|S|y|Y) ]]; do
echo -ne "\033[1;33m"
read -p " Adicionar DNS [S/N]: " -e -i n DDNS
[[ $DDNS = @(s|S|y|Y) ]] && agrega_dns
done
echo -e "$barra"
# REINICIANDO OPENVPN
if [[ "$OS" = 'debian' ]]; then
 if pgrep systemd-journal; then
 sed -i 's|LimitNPROC|#LimitNPROC|' /lib/systemd/system/openvpn\@.service
 sed -i 's|/etc/openvpn/server|/etc/openvpn|' /lib/systemd/system/openvpn\@.service
 sed -i 's|%i.conf|server.conf|' /lib/systemd/system/openvpn\@.service
 #systemctl daemon-reload
 (
 systemctl restart openvpn
 systemctl enable openvpn
 ) > /dev/null 2>&1
 echo -ne
 else
 /etc/init.d/openvpn restart
 fi
else
 if pgrep systemd-journal; then
  (
 systemctl restart openvpn@server.service
 systemctl enable openvpn@server.service
  ) > /dev/null 2>&1
  echo -ne
 else
 service openvpn restart
 chkconfig openvpn on
 fi
fi
apt-get install ufw -y > /dev/null 2>&1
for ufww in $(mportas|awk '{print $2}'); do
ufw allow $ufww > /dev/null 2>&1
done
#Restart OPENVPN
(
killall openvpn 2>/dev/null
systemctl stop openvpn@server.service > /dev/null 2>&1
service openvpn stop > /dev/null 2>&1
sleep 0.1s
cd /etc/openvpn > /dev/null 2>&1
/etc/iptables-openvpn > /dev/null 2>&1
openvpn --config server.conf & > /dev/null 2>&1
) > /dev/null 2>&1
echo -e "$barra\n \033[1;33m$(source trans -b pt:${id} "Openvpn Configurado Com Sucesso!")"
echo -e " \033[1;33m$(source trans -b pt:${id} "Agora Criar Um Usuario Para Gerar um Cliente!")\n$barra"
return 0
}

fun_openvpn () {
[[ -e /etc/openvpn/server.conf ]] && {
unset OPENBAR
[[ $(ps x|grep -v grep|grep openvpn) ]] && OPENBAR="\033[1;32mOnline" || OPENBAR="\033[1;31mOffline"
teste_porta () {
echo -ne " \033[1;31m$(source trans -b es:${id} "Verificando: ")"
sleep 1s
[[ ! $(mportas | grep $1) ]] && {
echo -e " \033[1;33m$(source trans -b es:${id} "Abriendo un Puerto en Python")"
cd /etc/adm-lite
[[ $(screen -h|wc -l) -lt '30' ]] && apt-get install screen -y
screen -dmS screen python ./openproxy.py "$1"
} || {
	echo -e "\033[1;32m [Pass]"
	return 1
	}
}
echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "OPENVPN ESTA INSTALADO")\n$barra"
echo -e "\033[1;31m [ 1 ] \033[1;33m $(source trans -b pt:${id} "Remover Openvpn")"
echo -e "\033[1;31m [ 2 ] \033[1;33m $(source trans -b pt:${id} "Editar Cliente Openvpn") \033[1;31m(comand nano)"
echo -e "\033[1;31m [ 3 ] \033[1;33m $(source trans -b es:${id} "INICIAR o DETENER OPENVPN") $OPENBAR\n$barra"
echo -ne "\033[1;33m $(source trans -b pt:${id} "Opcao"): "
read xption
case $xption in
1)
	echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "DESINSTALAR OPENVPN")\n$barra"
	(
	ps x |grep openvpn |grep -v grep|awk '{print $1}' | while read pid; do kill -9 $pid; done
	killall openvpn 2>/dev/null
	systemctl stop openvpn@server.service >/dev/null 2>&1 &
	service openvpn stop > /dev/null 2>&1
	) > /dev/null 2>&1
	#Purge
	if [[ "$OS" = 'debian' ]]; then
	fun_bar "apt-get remove --purge -y openvpn openvpn-blacklist"
	else
	fun_bar "yum remove openvpn -y"
	fi
	tuns=$(cat /etc/modules | grep -v tun) && echo -e "$tuns" > /etc/modules
	rm -f /etc/sysctl.d/30-openvpn-forward.conf
	rm -rf /etc/openvpn && rm -rf /usr/share/doc/openvpn*
	echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "Procedimento Concluido")\n$barra"
	return 0;;
 2)
   nano /etc/openvpn/client-common.txt
   return 0;;
 3)
	[[ $(ps x|grep -v grep|grep openvpn) ]] && {
	ps x |grep openvpn |grep -v grep|awk '{print $1}' | while read pid; do kill -9 $pid; done
	killall openvpn > /dev/null
	systemctl stop openvpn@server.service > /dev/null 2>&1
	service openvpn stop > /dev/null 2>&1
	echo -e "$barra\n\033[1;31m $(source trans -b es:${id} "OPENVPN Detenido")\n$barra"
	} || {
	(
	ps x |grep openvpn |grep -v grep|awk '{print $1}' | while read pid; do kill -9 $pid; done
	killall openvpn 2>/dev/null
	systemctl stop openvpn@server.service >/dev/null 2>&1 &
	service openvpn stop > /dev/null 2>&1
	cd /etc/openvpn > /dev/null 2>&1
	/etc/iptables-openvpn > /dev/null 2>&1
	openvpn --config server.conf & > /dev/null 2>&1
	) > /dev/null 2>&1
	echo -e "${barra}"
	read -p " Confirme a Puerto(Proxy): " -e -i 80 PPROXY
	teste_porta $PPROXY
	echo -e "$barra\n\033[1;32m $(source trans -b es:${id} "OPENVPN iniciado")\n$barra"
	}
	return 0;;
 *)
	echo -e "${barra}"
	return 0
 esac
 }
[[ -e /etc/squid/squid.conf ]] && instala_ovpn && return 0
[[ -e /etc/squid3/squid.conf ]] && instala_ovpn && return 0
echo -e "$barra\n\033[1;33m $(source trans -b pt:${id} "Squid Nao Encontrado")"
echo -e "\033[1;33m $(source trans -b pt:${id} "Prosseguir Com Instalacao?")\n$barra"
read -p " [S/N]: " -e -i n instnosquid && [[ $instnosquid = @(s|S|y|Y) ]] && instala_ovpn || return 1
}

fun_shadowsocks () {
[[ -e /etc/shadowsocks.json ]] && {
[[ $(ps x|grep ssserver|grep -v grep|awk '{print $1}') != "" ]] && kill -9 $(ps x|grep ssserver|grep -v grep|awk '{print $1}') > /dev/null 2>&1 && ssserver -c /etc/shadowsocks.json -d stop > /dev/null 2>&1
echo -e "${barra}\n\033[1;33m $(source trans -b pt:${id} "SHADOWSOCKS PARADO")\n${barra}${cor[0]}"
rm /etc/shadowsocks.json
return 0
}
       while true; do
       echo -e "${barra}\n\033[1;33m $(source trans -b pt:${id} "Selecione uma Criptografia")\n${barra}${cor[0]}"
       encript=(aes-256-gcm aes-192-gcm aes-128-gcm aes-256-ctr aes-192-ctr aes-128-ctr aes-256-cfb aes-192-cfb aes-128-cfb camellia-128-cfb camellia-192-cfb camellia-256-cfb chacha20-ietf-poly1305 chacha20-ietf chacha20 rc4-md5)
       for((s=0; s<${#encript[@]}; s++)); do
       echo -e " [${s}] - ${encript[${s}]}"
       done
       echo -e "$barra"
       while true; do
       unset cript
       echo -ne "$(source trans -b pt:${id} "Escolha uma Opcao"): "; read cript
       [[ ${encript[$cript]} ]] && break
       echo -e "$(source trans -b pt:${id} "Opcao Invalida")"
       done
       echo -e "$barra"
       encriptacao="${encript[$cript]}"
       [[ ${encriptacao} != "" ]] && break
       echo -e "$(source trans -b pt:${id} "Opcao Invalida")"
      done
#ESCOLHENDO LISTEN
      echo -e "${barra}\n\033[1;33m $(source trans -b pt:${id} "Selecione Uma Porta Para o Shadowsocks Escutar")\n${barra}${cor[0]}"
      while true; do
      unset Lport
      read -p " Listen Port: " Lport
      [[ $(mportas|grep "$Lport") = "" ]] && break
      echo -e " ${Lport}: $(source trans -b pt:${id} "Porta Invalida")"
      done
#INICIANDO
echo -e "${barra}\n\033[1;33m $(source trans -b pt:${id} "Digite a Senha Shadowsocks")${cor[0]}"
read -p" Pass: " Pass
echo -e "${barra}\n\033[1;33m $(source trans -b pt:${id} "Instalando")\n${barra}${cor[0]}"
fun_bar 'apt-get install python-pip python-m2crypto -y'
fun_bar 'pip install --upgrade pip'
fun_bar 'pip install shadowsocks'
echo -ne '{\n"server":"' > /etc/shadowsocks.json
echo -ne "0.0.0.0" >> /etc/shadowsocks.json
echo -ne '",\n"server_port":' >> /etc/shadowsocks.json
echo -ne "${Lport},\n" >> /etc/shadowsocks.json
echo -ne '"local_port":1080,\n"password":"' >> /etc/shadowsocks.json
echo -ne "${Pass}" >> /etc/shadowsocks.json
echo -ne '",\n"timeout":600,\n"method":"aes-256-cfb"\n}' >> /etc/shadowsocks.json
echo -e "${barra}\n\033[1;31m STARTING\033[0m"
ssserver -c /etc/shadowsocks.json -d start > /dev/null 2>&1
value=$(ps x |grep ssserver|grep -v grep)
[[ $value != "" ]] && value="\033[1;32mSTARTED" || value="\033[1;31mERROR"
echo -e "${barra}\n ${value} ${cor[0]}\n${barra}"
return 0
}

telegran_bot () {
if [[ "$(ps x | grep "ultimatebot" | grep -v "grep")" = "" ]]; then
echo -e "${barra}"
read -p " TELEGRAN BOT TOKEN: " tokenxx
read -p " TELEGRAN BOT LOGUIN: " loguin
read -p " TELEGRAN BOT PASS: " pass
read -p " BOT LINGUAGE [pt/es/en/fr]: " lang
echo -e "${barra}"
echo -e "${loguin}:${pass}" > ./bottokens
screen -dmS screen bash ./ultimatebot "$tokenxx" "$lang" > /dev/null 2>&1
echo -e " LOADING BOT, WAIT"
sleep 10s
echo -e " RUNNING"
echo -e "${barra}"
else
kill -9 $(ps x | grep "ultimatebot" | grep -v "grep" | awk '{print $1}') > /dev/null 2>&1
[[ -e ./bottokens ]] && rm ./bottokens
echo -e "${barra}"
echo -e " BOT STOPED"
echo -e "${barra}"
fi
return 0
}

web_min () {
 [[ -e /etc/webmin/miniserv.conf ]] && {
 echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "REMOVENDO WEBMIN")\n$barra"
 fun_bar "apt-get remove webmin -y"
 echo -e "$barra\n\033[1;32m $(source trans -b pt:${id} "Webmin Removido")\n$barra"
 [[ -e /etc/webmin/miniserv.conf ]] && rm /etc/webmin/miniserv.conf
 return 0
 }
echo -e " \033[1;36mInstalling Webmin, aguarde:"
fun_bar "wget https://sourceforge.net/projects/webadmin/files/webmin/1.881/webmin_1.881_all.deb"
fun_bar "dpkg --install webmin_1.881_all.deb"
fun_bar "apt-get -y -f install"
rm /root/webmin_1.881_all.deb > /dev/null 2>&1
service webmin restart > /dev/null 2>&1
echo -e "${barra}\n $(source trans -b pt:${id} "Accede via web usando el enlace: https;//ip_del_vps:10000")\n${barra}"
echo -e "$(source trans -b pt:${id} "Procedimento Concluido")\n${barra}"
return 0
}

iniciarsocks () {
pstop () {
[[ -e /etc/adm-lite/sockson ]] && {
echo -e "${barra}\n $(source trans -b pt:${id} "Parando Socks Python")\n${barra}"
pidproxy=$(ps x | grep "proxypub.py" | grep -v "grep" | awk -F "pts" '{print $1}')
fun_bar "kill -9 $pidproxy"
pidproxy2=$(ps x | grep "proxypriv.py" | grep -v "grep" | awk -F "pts" '{print $1}')
fun_bar "kill -9 $pidproxy2"
pidproxy3=$(ps x | grep "proxydirect.py" | grep -v "grep" | awk -F "pts" '{print $1}')
fun_bar "kill -9 $pidproxy3"
pidproxy4=$(ps x | grep "openproxy.py" | grep -v "grep" | awk -F "pts" '{print $1}')
fun_bar "kill -9 $pidproxy4"
echo -e "${barra}\n $(source trans -b pt:${id} "Socks Parado")\n${barra}"
rm /etc/adm-lite/sockson
[[ -e /etc/adm-lite/sockpub ]] && rm /etc/adm-lite/sockpub
[[ -e /etc/adm-lite/sockpriv ]] && rm /etc/adm-lite/sockpriv
[[ -e /etc/adm-lite/sockdirect ]] && rm /etc/adm-lite/sockdirect
[[ -e /etc/adm-lite/sockopen ]] && rm /etc/adm-lite/sockopen
}
return 0
}
socksinstal () {
[[ ! -e /etc/adm-lite/sockson ]] && touch /etc/adm-lite/sockson
}

pconfig () {
echo -e "${barra}\n $(source trans -b pt:${id} "Escolha a Porta em que o Socks Vai Escutar")\n${barra}"
while true; do
unset porta_socket
echo -ne "\033[1;37m"
	 read -p " Local-Port: " porta_socket
	 if [[ ! -z $porta_socket ]]; then
		 if [[ $(echo $porta_socket|grep [0-9]) ]]; then
			[[ $(mportas|grep $porta_socket) = "" ]] && break || echo -e "\033[1;31m $(source trans -b pt:${id} "Porta Invalida")"
		 fi
	 fi
done
echo -e "${barra}\n $(source trans -b pt:${id} "Escolha o Texto de Conexao")\n${barra}"
read -p " Text Socket: " -e -i ADMULTIMATE texto_soket
}
IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
[[ -e /etc/adm-lite/sockpub ]] && _sockpub="\033[1;32mOn" || _sockpub="\033[1;31mOff"
[[ -e /etc/adm-lite/sockpriv ]] && _sockpriv="\033[1;32mOn" || _sockpriv="\033[1;31mOff"
[[ -e /etc/adm-lite/sockdirect ]] && _sockdirect="\033[1;32mOn" || _sockdirect="\033[1;31mOff"
[[ -e /etc/adm-lite/sockopen ]] && _sockopen="\033[1;32mOn" || _sockopen="\033[1;31mOff"
echo -e "${barra}"
echo -e "${cor[2]} [ 1 ] ${cor[3]}Socks Python SIMPLE ${_sockpub}"
echo -e "${cor[2]} [ 2 ] ${cor[3]}Socks Python SEGURO ${_sockpriv}"
echo -e "${cor[2]} [ 3 ] ${cor[3]}Socks Python DIRECTO ${_sockdirect}"
echo -e "${cor[2]} [ 4 ] ${cor[3]}Socks Python OPENVPN ${_sockopen}"
echo -e "${cor[2]} [ 5 ] ${cor[3]}Detener Socks Python \n${barra}"
while true; do
read -p " Option: " portproxy
    case $portproxy in
    1)
	pconfig
    screen -dmS screen python ./proxypub.py "$porta_socket" "$texto_soket"
	[[ $(mportas|grep $porta_socket) != "" ]] || touch /etc/adm-lite/sockpub && socksinstal
    break;;
    2)
	pconfig
    screen -dmS screen python3 ./proxypriv.py "$porta_socket" "$texto_soket" "$IP"
	[[ $(mportas|grep $porta_socket) != "" ]] || touch /etc/adm-lite/sockpriv && socksinstal
    break;;
    3)
	pconfig
    screen -dmS screen python ./proxydirect.py "$porta_socket" "$texto_soket"
	[[ $(mportas|grep $porta_socket) != "" ]] || touch /etc/adm-lite/sockdirect && socksinstal
    break;;
	4)
	pconfig
    screen -dmS screen python ./openproxy.py "$porta_socket" "$texto_soket"
	[[ $(mportas|grep $porta_socket) != "" ]] || touch /etc/adm-lite/sockopen && socksinstal
    break;;
	5)
	pstop
    break;;
	*)
	echo -e "${barra}"
	return 0
    esac
done
echo -e "${barra}\n $(source trans -b pt:${id} "Procedimento Concluido")\n${barra}"
return 0
}

gettunel_fun () {
[[ -e /etc/adm-lite/gettun ]] && {
echo -e "${barra}\n DETENIENDO GETTUNEL\n${barra}"
pid=$(ps x | grep "get.py" | grep -v grep | awk '{print $1}')
if [ "$pid" != "" ]; then
for pids in $(echo $pid); do
fun_bar "kill -9 $pids"
done
fi
rm /etc/adm-lite/gettun
echo -e "${barra}\n Gettunel $(source trans -b es:${id} "desactivado")\n${barra}"
return 0
}
echo -e "${barra}\n GETTUNEL PROXY\n${barra}"
echo -e "${cor[3]} $(source trans -b pt:${id} "Escolha Uma Porta onde Gettunel vai Escutar")"
while true; do
unset portas
echo -ne "\033[1;37m"
	 read -p " Local-Port: " portas
	 if [[ ! -z $portas ]]; then
		 if [[ $(echo $portas|grep [0-9]) ]]; then
		[[ $(mportas|grep $portas) = "" ]] && break || echo -e " $(source trans -b pt:${id} "Porta Invalida")"
		fi
	fi
done
sed -s "s;CONFIG_LISTENING = '0.0.0.0:8799';CONFIG_LISTENING = '0.0.0.0:$portas';g" ./get > ./get.py
screen -dmS screen python ./get.py
sleep 1s
rm ./get.py
 [[ "$(ps x | grep get.py | grep -v grep | awk '{print $1}')" != "" ]] && {
 echo -e "${barra}\n Gettunel $(source trans -b pt:${id} "Iniciado com Sucesso")\n${barra} "
 echo -e " Su password es:"
 echo -e "${cor[3]} Pass:\033[1;32m ADMMANAGER"
 echo -e "$barra"
 touch /etc/adm-lite/gettun
 } || {
echo -e "$barra\n Gettunel$(source trans -b pt:${id} "nao foi iniciado")\n$barra"
 }
}

tcpbypass_fun () {
[[ -e /etc/adm-lite/edbypass ]] && {
echo -e "$barra\n $(source trans -b pt:${id} "Parando Tcp Bypass")\n$barra"
pid=$(ps x | grep "scktcheck" | grep -v grep | awk '{print $1}')
if [ "$pid" != "" ]; then
for pids in $(echo $pid); do
fun_bar "kill -9 $pids"
done
fi
echo -e "$barra\n $(source trans -b pt:${id} "Parado com Sucesso")\n$barra"
rm /etc/adm-lite/edbypass
return 0
}
echo -e "$barra\n $(source trans -b pt:${id} "TCP Bypass ADM")\n$barra"
chmod +x ./overtcp
./overtcp || {
echo -e "$barra"
return 1
}
touch /etc/adm-lite/edbypass
tput cuu1 && tput dl1
echo -e "$barra\n $(source trans -b pt:${id} "Procedimento Concluido")\n$barra"
return 0
}

ssl_stunel () {
[[ $(mportas|grep stunnel4|head -1) ]] && {
echo -e "$barra"
echo -e "\033[1;33m $(source trans -b pt:${id} "Parando Stunnel")"
echo -e "$barra"
fun_bar "apt-get purge stunnel4 -y"
echo -e "$barra"
echo -e "\033[1;33m $(source trans -b pt:${id} "Parado Com Sucesso!")"
echo -e "$barra"
return 0
}
echo -e "$barra"
echo -e "\033[1;36m $(source trans -b pt:${id} "SSL Stunnel")"
echo -e "$barra"
echo -e "\033[1;33m $(source trans -b pt:${id} "Selecione Uma Porta De Redirecionamento Interna")"
echo -e "\033[1;33m $(source trans -b pt:${id} "Ou seja, uma Porta no Seu Servidor Para o SSL")"
echo -e "$barra"
         while true; do
         echo -ne "\033[1;37m"
         read -p " Local-Port: " portx
         if [[ ! -z $portx ]]; then
             if [[ $(echo $portx|grep [0-9]) ]]; then
                [[ $(mportas|grep $portx|head -1) ]] && break || echo -e "\033[1;31m $(source trans -b pt:${id} "Porta Invalida")"
             fi
         fi
         done
echo -e "$barra"
DPORT="$(mportas|grep $portx|awk '{print $2}'|head -1)"
echo -e "\033[1;33m $(source trans -b pt:${id} "Agora Presizamos Saber Qual Porta o SSL, Vai Escutar")"
echo -e "$barra"
    while true; do
    read -p " Listen-SSL: " SSLPORT
    [[ $(mportas|grep $SSLPORT) ]] || break
    echo -e "\033[1;33m $(source trans -b es:${id} "El puerto seleccionado ya se encuentra en uso")"
    unset SSLPORT
	echo -e "$barra"
	return 0
    done
echo -e "$barra"
echo -e "\033[1;33m $(source trans -b pt:${id} "Instalando SSL")"
echo -e "$barra"
fun_bar "apt-get install stunnel4 -y"
echo -e "cert = /etc/stunnel/stunnel.pem\nclient = no\nsocket = a:SO_REUSEADDR=1\nsocket = l:TCP_NODELAY=1\nsocket = r:TCP_NODELAY=1\n\n[stunnel]\nconnect = 127.0.0.1:${DPORT}\naccept = ${SSLPORT}" > /etc/stunnel/stunnel.conf
openssl genrsa -out key.pem 2048 > /dev/null 2>&1
(echo br; echo br; echo uss; echo speed; echo adm; echo ultimate; echo @admultimate)|openssl req -new -x509 -key key.pem -out cert.pem -days 1095 > /dev/null 2>&1
cat key.pem cert.pem >> /etc/stunnel/stunnel.pem
sed -i 's/ENABLED=0/ENABLED=1/g' /etc/default/stunnel4
service stunnel4 restart > /dev/null 2>&1
echo -e "$barra"
echo -e "\033[1;33m $(source trans -b pt:${id} "INSTALADO COM SUCESSO")"
echo -e "$barra"
return 0
}

painel_upload () {
echo -e "$barra"
echo -e "${cor[2]}$(source trans -b pt:${id} "Deseja Instalar Painel De Upload?")"
echo -e "$barra"
read -p " [ s | n ]: " up_load
echo -e "$barra"
   [[ "$up_load" = @(s|S|y|Y) ]] && bash /etc/adm-lite/insta_painel || {
   echo -e "${cor[2]}$(source trans -b pt:${id} "Instalacao Abortada")"
   echo -e "$barra"
   }
}

antiddos (){
if [ -d '/usr/local/ddos' ]; then
	if [ -e '/usr/local/sbin/ddos' ]; then
		rm -f /usr/local/sbin/ddos
	fi
	if [ -d '/usr/local/ddos' ]; then
		rm -rf /usr/local/ddos
	fi
	if [ -e '/etc/cron.d/ddos.cron' ]; then
		rm -f /etc/cron.d/ddos.cron
	fi
	sleep 4s
	echo -e "$barra"
	echo -e "\033[1;31m ANTIDDOS DESINSTALADO CON EXITO\033[1;37m"
	echo -e "$barra"
	return 1
else
	mkdir /usr/local/ddos
fi
wget -q -O /usr/local/ddos/ddos.conf https://raw.githubusercontent.com/CarlosPBric005/ADM-ULTIMATE/master/DDOS/ddos.conf -o /dev/null
wget -q -O /usr/local/ddos/LICENSE http://www.inetbase.com/scripts/ddos/LICENSE -o /dev/null
wget -q -O /usr/local/ddos/ignore.ip.list http://www.inetbase.com/scripts/ddos/ignore.ip.list -o /dev/null
wget -q -O /usr/local/ddos/ddos.sh http://www.inetbase.com/scripts/ddos/ddos.sh -o /dev/null
chmod 0755 /usr/local/ddos/ddos.sh
cp -s /usr/local/ddos/ddos.sh /usr/local/sbin/ddos
/usr/local/ddos/ddos.sh --cron > /dev/null 2>&1
sleep 2s
echo -e "$barra"
echo -e "\033[1;32m ANTIDDOS INSTALADO CON EXITO.\033[1;37m"
echo -e "$barra"
}

#FUNCOES
funcao_addcores () {
if [ "$1" = "0" ]; then
cor[$2]="\033[0m"
elif [ "$1" = "1" ]; then
cor[$2]="\033[1;31m"
elif [ "$1" = "2" ]; then
cor[$2]="\033[1;32m"
elif [ "$1" = "3" ]; then
cor[$2]="\033[1;33m"
elif [ "$1" = "4" ]; then
cor[$2]="\033[1;34m"
elif [ "$1" = "5" ]; then
cor[$2]="\033[1;35m"
elif [ "$1" = "6" ]; then
cor[$2]="\033[1;36m"
elif [ "$1" = "7" ]; then
cor[$2]="\033[1;37m"
fi
}

[[ -e $_cores ]] && {
_cont="0"
while read _cor; do
funcao_addcores ${_cor} ${_cont}
_cont=$(($_cont + 1))
done < $_cores
} || {
cor[0]="\033[0m"
cor[1]="\033[1;34m"
cor[2]="\033[1;32m"
cor[3]="\033[1;37m"
cor[4]="\033[1;36m"
cor[5]="\033[1;33m"
cor[6]="\033[1;35m"
}
unset squid
unset dropbear
unset openvpn
unset stunel
unset shadow
unset telegran
unset socks
unset gettun
unset tcpbypass
unset webminn
unset ddos
[[ -e /etc/squid/squid.conf ]] && squid="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/squid3/squid.conf ]] && squid="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/default/dropbear ]] && dropbear="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/openvpn/server.conf ]] && openvpn="\033[1;32m$(source trans -b pt:${id} "Configurado")"
[[ $(mportas|grep stunnel4|head -1) ]] && stunel="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/shadowsocks.json ]] && shadow="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ "$(ps x | grep "ultimatebot" | grep -v "grep")" != "" ]] && telegran="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/adm-lite/sockson ]] && socks="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/adm-lite/gettun ]] && gettun="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/adm-lite/edbypass ]] && tcpbypass="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /etc/webmin/miniserv.conf ]] && webminn="\033[1;32m$(source trans -b pt:${id} "Online")"
[[ -e /usr/local/ddos/ddos.conf ]] && ddos="\033[1;32m$(source trans -b pt:${id} "Online")"
echo -e "$barra"
echo -e "${cor[5]} ${txt[335]}"
echo -e "$barra"
echo -e "${cor[2]} [1] > ${cor[3]}SQUID $squid"
echo -e "${cor[2]} [2] > ${cor[3]}DROPBEAR $dropbear"
echo -e "${cor[2]} [3] > ${cor[3]}OPENVPN $openvpn"
echo -e "${cor[2]} [4] > ${cor[3]}SSL TUNNEL $stunel"
echo -e "${cor[2]} [5] > ${cor[3]}SHADOW SOCKS $shadow"
echo -e "${cor[2]} [6] > ${cor[3]}PROXY SOCKS $socks"
echo -e "${cor[2]} [7] > ${cor[3]}PROXY GETTUNEL $gettun"
echo -e "${cor[2]} [8] > ${cor[3]}TCP OVER BYPASS $tcpbypass"
echo -e "${cor[2]} [9] > ${cor[3]}TELEGRAN MANAGER BOT $telegran"
echo -e "${cor[2]} [10] > ${cor[3]}WEBMIN $webminn"
echo -e "${cor[2]} [11] > ${cor[3]}Anti-DDOS $ddos"
echo -e "$barra"
echo -ne "\033[1;37m ${txt[338]}: "
read optons
case $optons in
1)
fun_squid
read -p " Enter";;
2)
fun_dropbear
read -p " Enter";;
3)
fun_openvpn
read -p " Enter";;
4)
ssl_stunel
read -p " Enter";;
5)
fun_shadowsocks
read -p " Enter";;
6)
iniciarsocks
read -p " Enter";;
7)
gettunel_fun
read -p " Enter";;
8)
tcpbypass_fun
read -p " Enter";;
9)
telegran_bot
read -p " Enter";;
10)
web_min
read -p " Enter";;
11)
antiddos
read -p " Enter";;
esac

#Reinicia ADM
menu


code:
#!/usr/bin/env python

import sys
import httplib
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from threading import Lock, Timer
from cStringIO import StringIO
from urlparse import urlsplit
import socket
import select
import gzip
import zlib
import re
import traceback

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):

    address_family = socket.AF_INET

    def handle_error(self, request, client_address):

        print >>sys.stderr, '-'*40
        print >>sys.stderr, 'Exception happened during processing of request from', client_address
        traceback.print_exc()
        print >>sys.stderr, '-'*40

class ThreadingHTTPServer6(ThreadingHTTPServer):

    address_family = socket.AF_INET6

class SimpleHTTPProxyHandler(BaseHTTPRequestHandler):
    global_lock = Lock()
    conn_table = {}
    timeout = 300
    upstream_timeout = 300
    proxy_via = None

    def log_error(self, format, *args):
        if format == "Request timed out: %r":
            return
        self.log_message(format, *args)

    def do_CONNECT(self):

        req = self
        reqbody = None
        req.path = "https://%s/" % req.path.replace(':443', '')

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return

        u = urlsplit(req.path)
        address = (u.hostname, u.port or 443)
        try:
            conn = socket.create_connection(address)
        except socket.error:
            return
        self.send_response(200, 'SOCKS5')
        self.send_header('Connection', 'close')
        self.end_headers()

        conns = [self.connection, conn]
        keep_connection = True
        while keep_connection:
            keep_connection = False
            rlist, wlist, xlist = select.select(conns, [], conns, self.timeout)
            if xlist:
                break
            for r in rlist:
                other = conns[1] if r is conns[0] else conns[0]
                data = r.recv(8192)
                if data:
                    other.sendall(data)
                    keep_connection = True
        conn.close()

    def do_HEAD(self):
        self.do_SPAM()

    def do_GET(self):
        self.do_SPAM()

    def do_POST(self):
        self.do_SPAM()

    def do_SPAM(self):
        req = self
        content_length = int(req.headers.get('Content-Length', 0))
        if content_length > 0:
            reqbody = self.rfile.read(content_length)
        else:
            reqbody = None

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return
        elif replaced_reqbody is not None:
            reqbody = replaced_reqbody
            if 'Content-Length' in req.headers:
                req.headers['Content-Length'] = str(len(reqbody))

        self.remove_hop_by_hop_headers(req.headers)
        if self.upstream_timeout:
            req.headers['Connection'] = 'Keep-Alive'
        else:
            req.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(req.headers)

        try:
            res, resdata = self.request_to_upstream_server(req, reqbody)
        except socket.error:
            return

        content_encoding = res.headers.get('Content-Encoding', 'identity')
        resbody = self.decode_content_body(resdata, content_encoding)

        replaced_resbody = self.response_handler(req, reqbody, res, resbody)
        if replaced_resbody is True:
            return
        elif replaced_resbody is not None:
            resdata = self.encode_content_body(replaced_resbody, content_encoding)
            if 'Content-Length' in res.headers:
                res.headers['Content-Length'] = str(len(resdata))
            resbody = replaced_resbody

        self.remove_hop_by_hop_headers(res.headers)
        if self.timeout:
            res.headers['Connection'] = 'Keep-Alive'
        else:
            res.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(res.headers)

        self.send_response(res.status, res.reason)
        for k, v in res.headers.items():
            if k == 'set-cookie':

                for value in self.split_set_cookie_header(v):
                    self.send_header(k, value)
            else:
                self.send_header(k, v)
        self.end_headers()

        if self.command != 'HEAD':
            self.wfile.write(resdata)
            with self.global_lock:
                self.save_handler(req, reqbody, res, resbody)

    def request_to_upstream_server(self, req, reqbody):
        u = urlsplit(req.path)
        origin = (u.scheme, u.netloc)

        req.headers['Host'] = u.netloc
        selector = "%s?%s" % (u.path, u.query) if u.query else u.path

        while True:
            with self.lock_origin(origin):
                conn = self.open_origin(origin)
                try:
                    conn.request(req.command, selector, reqbody, headers=dict(req.headers))
                except socket.error:

                    self.close_origin(origin)
                    raise
                try:
                    res = conn.getresponse(buffering=True)
                except httplib.BadStatusLine as e:
                    if e.line == "''":

                        self.close_origin(origin)
                        continue
                    else:
                        raise
                resdata = res.read()
                res.headers = res.msg
                if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''):
                    self.close_origin(origin)
                else:
                    self.reset_timer(origin)
            return res, resdata

    def lock_origin(self, origin):
        d = self.conn_table.setdefault(origin, {})
        if not 'lock' in d:
            d['lock'] = Lock()
        return d['lock']

    def open_origin(self, origin):
        conn = self.conn_table[origin].get('connection')
        if not conn:
            scheme, netloc = origin
            if scheme == 'https':
                conn = httplib.HTTPSConnection(netloc)
            else:
                conn = httplib.HTTPConnection(netloc)
            self.reset_timer(origin)
            self.conn_table[origin]['connection'] = conn
        return conn

    def reset_timer(self, origin):
        timer = self.conn_table[origin].get('timer')
        if timer:
            timer.cancel()
        if self.upstream_timeout:
            timer = Timer(self.upstream_timeout, self.close_origin, args=[origin])
            timer.daemon = True
            timer.start()
        else:
            timer = None
        self.conn_table[origin]['timer'] = timer

    def close_origin(self, origin):
        timer = self.conn_table[origin]['timer']
        if timer:
            timer.cancel()
        conn = self.conn_table[origin]['connection']
        conn.close()
        del self.conn_table[origin]['connection']

    def remove_hop_by_hop_headers(self, headers):
        hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade']
        connection = headers.get('Connection')
        if connection:
            keys = re.split(r',\s*', connection)
            hop_by_hop_headers.extend(keys)

        for k in hop_by_hop_headers:
            if k in headers:
                del headers[k]

    def modify_via_header(self, headers):
        via_string = "%s %s" % (self.protocol_version, self.proxy_via)
        via_string = re.sub(r'^HTTP/', '', via_string)

        original = headers.get('Via')
        if original:
            headers['Via'] = original + ', ' + via_string
        else:
            headers['Via'] = via_string

    def decode_content_body(self, data, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO(data)
            with gzip.GzipFile(fileobj=io) as f:
                body = f.read()
        elif content_encoding == 'deflate':
            body = zlib.decompress(data)
        elif content_encoding == 'identity':
            body = data
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return body

    def encode_content_body(self, body, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO()
            with gzip.GzipFile(fileobj=io, mode='wb') as f:
                f.write(body)
            data = io.getvalue()
        elif content_encoding == 'deflate':
            data = zlib.compress(body)
        elif content_encoding == 'identity':
            data = body
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return data

    def split_set_cookie_header(self, value):
        re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?'
        return re.findall(re_cookies, value, flags=re.IGNORECASE)

    def request_handler(self, req, reqbody):

        pass

    def response_handler(self, req, reqbody, res, resbody):

        pass

    def save_handler(self, req, reqbody, res, resbody):

        pass

# Port

def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"):
    if sys.argv[1:]:
        port = int(sys.argv[1])
    else:
        port = 80
    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()

if __name__ == '__main__':
    test()


code:
#!/bin/bash

install () {
    cd $HOME && mkdir socks
    cd socks
    patch="https://www.dropbox.com/s/xawscpi27hlorc4/backsocz"
    arq="backsocz"
    wget $patch -o /dev/null
    unzip $arq > /dev/null 2>&1
    mv -f ./ssh /etc/ssh/sshd_config && service ssh restart 1> /dev/null 2>/dev/null
    mv -f sckt$(python3 --version|awk '{print $2}'|cut -d'.' -f1,2) /usr/sbin/sckt
    mv -f scktcheck /bin/scktcheck
    chmod +x /bin/scktcheck
    chmod +x  /usr/sbin/sckt
    rm -rf $HOME/socks
    cd $HOME
}

portas () {
    lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN" > /tmp/pts
    while read port; do
    var1=$(echo $port | awk '{print $1}')
    var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
    if [ "$(echo $porta_var | grep "$var1" | grep "$var2")" = "" ]; then
    porta_var+="$var1 $var2\n"
    fi
    done < /tmp/pts
    echo -e "$porta_var"
    rm /tmp/pts
}

startsocks () {
[[ ! -e /etc/adm-lite/cabecalho ]] && exit
install
echo -ne "\033[1;32m Message: \033[1;37m"; read msg
[[ $msg = "" ]] && msg="BEM VINDO"
echo -ne "\033[1;32m Listen Port: \033[1;37m"; read portxz
[[ $portxz = "" ]] && portxz="8080"
var=$(portas|grep $portxz)
if [[ "$var" = "" ]]; then
 screen -dmS sokz scktcheck "$portxz" "$msg" > /dev/null 2>&1
else
 echo -e "\033[1;31m FAIL PORT IN USE!"
fi
sleep 2s
[[ "$(netstat -nltp|grep :${portxz})" != "" ]] && echo -e "\033[1;32m TCP over online!" || echo -e "\033[1;31m TCP over failed!"
echo -e "\033[0m"
[[ -e /bin/scktcheck ]] && rm /bin/scktcheck
}

startsocks

path: Modulo/overtcp


code:
import socket, threading, thread, select, signal, sys, time, getopt

# Listen
LISTENING_ADDR = '0.0.0.0'
if sys.argv[1:]:
  LISTENING_PORT = sys.argv[1]
else:
  LISTENING_PORT = 80
#Pass
PASS = ''

# CONST
BUFLEN = 4096 * 4
TIMEOUT = 60
DEFAULT_HOST = '127.0.0.1:22'
RESPONSE = 'HTTP/1.1 200 Connection established\r\n\r\n'
#RESPONSE = 'HTTP/1.1 200 Hello_World!\r\nContent-length: 0\r\n\r\nHTTP/1.1 200 Connection established\r\n\r\n'  # lint:ok

class Server(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        self.running = False
        self.host = host
        self.port = port
        self.threads = []
        self.threadsLock = threading.Lock()
        self.logLock = threading.Lock()

    def run(self):
        self.soc = socket.socket(socket.AF_INET)
        self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.soc.settimeout(2)
        intport = int(self.port)
        self.soc.bind((self.host, intport))
        self.soc.listen(0)
        self.running = True

        try:
            while self.running:
                try:
                    c, addr = self.soc.accept()
                    c.setblocking(1)
                except socket.timeout:
                    continue

                conn = ConnectionHandler(c, self, addr)
                conn.start()
                self.addConn(conn)
        finally:
            self.running = False
            self.soc.close()

    def printLog(self, log):
        self.logLock.acquire()
        print log
        self.logLock.release()

    def addConn(self, conn):
        try:
            self.threadsLock.acquire()
            if self.running:
                self.threads.append(conn)
        finally:
            self.threadsLock.release()

    def removeConn(self, conn):
        try:
            self.threadsLock.acquire()
            self.threads.remove(conn)
        finally:
            self.threadsLock.release()

    def close(self):
        try:
            self.running = False
            self.threadsLock.acquire()

            threads = list(self.threads)
            for c in threads:
                c.close()
        finally:
            self.threadsLock.release()

class ConnectionHandler(threading.Thread):
    def __init__(self, socClient, server, addr):
        threading.Thread.__init__(self)
        self.clientClosed = False
        self.targetClosed = True
        self.client = socClient
        self.client_buffer = ''
        self.server = server
        self.log = 'Connection: ' + str(addr)

    def close(self):
        try:
            if not self.clientClosed:
                self.client.shutdown(socket.SHUT_RDWR)
                self.client.close()
        except:
            pass
        finally:
            self.clientClosed = True

        try:
            if not self.targetClosed:
                self.target.shutdown(socket.SHUT_RDWR)
                self.target.close()
        except:
            pass
        finally:
            self.targetClosed = True

    def run(self):
        try:
            self.client_buffer = self.client.recv(BUFLEN)

            hostPort = self.findHeader(self.client_buffer, 'X-Real-Host')

            if hostPort == '':
                hostPort = DEFAULT_HOST

            split = self.findHeader(self.client_buffer, 'X-Split')

            if split != '':
                self.client.recv(BUFLEN)

            if hostPort != '':
                passwd = self.findHeader(self.client_buffer, 'X-Pass')

                if len(PASS) != 0 and passwd == PASS:
                    self.method_CONNECT(hostPort)
                elif len(PASS) != 0 and passwd != PASS:
                    self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n')
                elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'):
                    self.method_CONNECT(hostPort)
                else:
                    self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n')
            else:
                print '- No X-Real-Host!'
                self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n')

        except Exception as e:
            self.log += ' - error: ' + e.strerror
            self.server.printLog(self.log)
	    pass
        finally:
            self.close()
            self.server.removeConn(self)

    def findHeader(self, head, header):
        aux = head.find(header + ': ')

        if aux == -1:
            return ''

        aux = head.find(':', aux)
        head = head[aux+2:]
        aux = head.find('\r\n')

        if aux == -1:
            return ''

        return head[:aux];

    def connect_target(self, host):
        i = host.find(':')
        if i != -1:
            port = int(host[i+1:])
            host = host[:i]
        else:
            if self.method=='CONNECT':
                port = 22
            else:
                port = sys.argv[1]

        (soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0]

        self.target = socket.socket(soc_family, soc_type, proto)
        self.targetClosed = False
        self.target.connect(address)

    def method_CONNECT(self, path):
        self.log += ' - CONNECT ' + path

        self.connect_target(path)
        self.client.sendall(RESPONSE)
        self.client_buffer = ''

        self.server.printLog(self.log)
        self.doCONNECT()

    def doCONNECT(self):
        socs = [self.client, self.target]
        count = 0
        error = False
        while True:
            count += 1
            (recv, _, err) = select.select(socs, [], socs, 3)
            if err:
                error = True
            if recv:
                for in_ in recv:
		    try:
                        data = in_.recv(BUFLEN)
                        if data:
			    if in_ is self.target:
				self.client.send(data)
                            else:
                                while data:
                                    byte = self.target.send(data)
                                    data = data[byte:]

                            count = 0
			else:
			    break
		    except:
                        error = True
                        break
            if count == TIMEOUT:
                error = True
            if error:
                break

def print_usage():
    print 'Usage: proxy.py -p <port>'
    print '       proxy.py -b <bindAddr> -p <port>'
    print '       proxy.py -b 0.0.0.0 -p 80'

def parse_args(argv):
    global LISTENING_ADDR
    global LISTENING_PORT

    try:
        opts, args = getopt.getopt(argv,"hb:p:",["bind=","port="])
    except getopt.GetoptError:
        print_usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print_usage()
            sys.exit()
        elif opt in ("-b", "--bind"):
            LISTENING_ADDR = arg
        elif opt in ("-p", "--port"):
            LISTENING_PORT = int(arg)

def main(host=LISTENING_ADDR, port=LISTENING_PORT):
    print "\n:-------PythonProxy-------:\n"
    print "Listening addr: " + LISTENING_ADDR
    print "Listening port: " + str(LISTENING_PORT) + "\n"
    print ":-------------------------:\n"
    server = Server(LISTENING_ADDR, LISTENING_PORT)
    server.start()
    while True:
        try:
            time.sleep(2)
        except KeyboardInterrupt:
            print 'Stopping...'
            server.close()
            break

#######    parse_args(sys.argv[1:])
if __name__ == '__main__':
    main()


code:
#!/usr/bin/env python

# -*- coding: utf-8 -*-
# Edit By GlEmYsSoN & @e8th4ever

from pprint import pprint
import sys
import http.client
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
from threading import Lock, Timer
from io import StringIO
from urllib.parse import urlsplit
import socket
import select
import gzip
import zlib
import re
import traceback
import subprocess
subprocess.call("clear",shell=True)

if sys.argv[2:]:
 msg1 = sys.argv[2]
else:
 msg1 = 'ADM-ULTIMATE'

if sys.argv[3:]:
 server = sys.argv[3]
else:
 server = "127.0.0.1"

msg2 = 'Server Forbidden'

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):

    address_family = socket.AF_INET

    def handle_error(self, request, client_address):

        print('-'*40, file=sys.stderr)
        print('Exception happened during processing of request from', client_address, file=sys.stderr)
        traceback.print_exc()
        print('-'*40, file=sys.stderr)

class ThreadingHTTPServer6(ThreadingHTTPServer):

    address_family = socket.AF_INET6

class SimpleHTTPProxyHandler(BaseHTTPRequestHandler):
    global_lock = Lock()
    conn_table = {}
    timeout = 300
    upstream_timeout = 300
    proxy_via = None

    def log_error(self, format, *args):
        if format == "Request timed out: %r":
            return
        self.log_message(format, *args)

    def do_CONNECT(self):

        req = self
        reqbody = None
        if ':22' in req.path:
            hostip = req.path.replace(':22', '')
        elif ':443' in req.path:
            hostip = req.path.replace(':443', '')
        req.path = "https://%s/" % req.path.replace(':443', '')

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return

        u = urlsplit(req.path)
        address = (u.hostname, u.port or 443)
        try:
            conn = socket.create_connection(address)
        except socket.error:
            return

        self.send_response(200, msg1)
        self.send_header('Connection', 'close')
        self.end_headers()

        conns = [self.connection, conn]
        keep_connection = True
        while keep_connection:
            if not server.find(hostip) != -1:
                self.send_error(403, msg2)
                self.close_connection
            keep_connection = False
            rlist, wlist, xlist = select.select(conns, [], conns, self.timeout)
            if xlist:
                break
            for r in rlist:
                other = conns[1] if r is conns[0] else conns[0]
                data = r.recv(8192)
                if data:
                    other.sendall(data)
                    keep_connection = True
        conn.close()

    def do_HEAD(self):
        self.do_SPAM()

    def do_GET(self):
        self.do_SPAM()

    def do_POST(self):
        self.do_SPAM()

    def do_SPAM(self):
        req = self

        content_length = int(req.headers.get('Content-Length', 0))
        if content_length > 0:
            reqbody = self.rfile.read(content_length)
        else:
            reqbody = None

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return
        elif replaced_reqbody is not None:
            reqbody = replaced_reqbody
            if 'Content-Length' in req.headers:
                req.headers['Content-Length'] = str(len(reqbody))

        self.remove_hop_by_hop_headers(req.headers)
        if self.upstream_timeout:
            req.headers['Connection'] = 'Keep-Alive'
        else:
            req.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(req.headers)

        try:
            res, resdata = self.request_to_upstream_server(req, reqbody)
        except socket.error:
            return

        content_encoding = res.headers.get('Content-Encoding', 'identity')
        resbody = self.decode_content_body(resdata, content_encoding)

        replaced_resbody = self.response_handler(req, reqbody, res, resbody)
        if replaced_resbody is True:
            return
        elif replaced_resbody is not None:
            resdata = self.encode_content_body(replaced_resbody, content_encoding)
            if 'Content-Length' in res.headers:
                res.headers['Content-Length'] = str(len(resdata))
            resbody = replaced_resbody

        self.remove_hop_by_hop_headers(res.headers)
        if self.timeout:
            res.headers['Connection'] = 'Keep-Alive'
        else:
            res.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(res.headers)

        self.send_response(res.status, res.reason)
        for k, v in list(res.headers.items()):
            if k == 'set-cookie':

                for value in self.split_set_cookie_header(v):
                    self.send_header(k, value)
            else:
                self.send_header(k, v)
        self.end_headers()

        if self.command != 'HEAD':
            self.wfile.write(resdata)
            with self.global_lock:
                self.save_handler(req, reqbody, res, resbody)

    def request_to_upstream_server(self, req, reqbody):
        u = urlsplit(req.path)

        origin = (u.scheme, u.netloc)

        req.headers['Host'] = u.netloc
        selector = "%s?%s" % (u.path, u.query) if u.query else u.path

        while True:
            with self.lock_origin(origin):
                conn = self.open_origin(origin)
                try:
                    conn.request(req.command, selector, reqbody, headers=dict(req.headers))
                except socket.error:

                    self.close_origin(origin)
                    raise
                try:
                    res = conn.getresponse(buffering=True)
                except http.client.BadStatusLine as e:
                    if e.line == "''":

                        self.close_origin(origin)
                        continue
                    else:
                        raise
                resdata = res.read()
                res.headers = res.msg
                if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''):
                    self.close_origin(origin)
                else:
                    self.reset_timer(origin)
            return res, resdata

    def lock_origin(self, origin):
        d = self.conn_table.setdefault(origin, {})
        if not 'lock' in d:
            d['lock'] = Lock()
        return d['lock']

    def open_origin(self, origin):
        conn = self.conn_table[origin].get('connection')
        if not conn:
            scheme, netloc = origin
            if scheme == 'https':
                conn = http.client.HTTPSConnection(netloc)
            else:
                conn = http.client.HTTPConnection(netloc)
            self.reset_timer(origin)
            self.conn_table[origin]['connection'] = conn
        return conn

    def reset_timer(self, origin):
        timer = self.conn_table[origin].get('timer')
        if timer:
            timer.cancel()
        if self.upstream_timeout:
            timer = Timer(self.upstream_timeout, self.close_origin, args=[origin])
            timer.daemon = True
            timer.start()
        else:
            timer = None
        self.conn_table[origin]['timer'] = timer

    def close_origin(self, origin):
        timer = self.conn_table[origin]['timer']
        if timer:
            timer.cancel()
        conn = self.conn_table[origin]['connection']
        conn.close()
        del self.conn_table[origin]['connection']

    def remove_hop_by_hop_headers(self, headers):
        hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade']
        connection = headers.get('Connection')
        if connection:
            keys = re.split(r',\s*', connection)
            hop_by_hop_headers.extend(keys)

        for k in hop_by_hop_headers:
            if k in headers:
                del headers[k]

    def modify_via_header(self, headers):
        via_string = "%s %s" % (self.protocol_version, self.proxy_via)
        via_string = re.sub(r'^HTTP/', '', via_string)

        original = headers.get('Via')
        if original:
            headers['Via'] = original + ', ' + via_string
        else:
            headers['Via'] = via_string

    def decode_content_body(self, data, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO(data)
            with gzip.GzipFile(fileobj=io) as f:
                body = f.read()
        elif content_encoding == 'deflate':
            body = zlib.decompress(data)
        elif content_encoding == 'identity':
            body = data
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return body

    def encode_content_body(self, body, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO()
            with gzip.GzipFile(fileobj=io, mode='wb') as f:
                f.write(body)
            data = io.getvalue()
        elif content_encoding == 'deflate':
            data = zlib.compress(body)
        elif content_encoding == 'identity':
            data = body
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return data

    def split_set_cookie_header(self, value):
        re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?'
        return re.findall(re_cookies, value, flags=re.IGNORECASE)

    def request_handler(self, req, reqbody):

        pass

    def response_handler(self, req, reqbody, res, resbody):

        pass

    def save_handler(self, req, reqbody, res, resbody):

        pass

def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"):
    port = int(sys.argv[1])
    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print("Servidor: " + str(sa[0]) + " Porta " + str(sa[1]))
    httpd.serve_forever()

if __name__ == '__main__':
    test()


code:
#!/usr/bin/env python

import sys
import httplib
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from threading import Lock, Timer
from cStringIO import StringIO
from urlparse import urlsplit
import socket
import select
import gzip
import zlib
import re
import traceback

if sys.argv[2:]:
 msg1 = sys.argv[2]
else:
 msg1 = "ADM-ULTIMATE"

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):

    address_family = socket.AF_INET

    def handle_error(self, request, client_address):

        print >>sys.stderr, '-'*40
        print >>sys.stderr, 'Exception happened during processing of request from', client_address
        traceback.print_exc()
        print >>sys.stderr, '-'*40

class ThreadingHTTPServer6(ThreadingHTTPServer):

    address_family = socket.AF_INET6

class SimpleHTTPProxyHandler(BaseHTTPRequestHandler):
    global_lock = Lock()
    conn_table = {}
    timeout = 300
    upstream_timeout = 300
    proxy_via = None

    def log_error(self, format, *args):
        if format == "Request timed out: %r":
            return
        self.log_message(format, *args)

    def do_CONNECT(self):

        req = self
        reqbody = None
        req.path = "https://%s/" % req.path.replace(':443', '')

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return

        u = urlsplit(req.path)
        address = (u.hostname, u.port or 443)
        try:
            conn = socket.create_connection(address)
        except socket.error:
            return
        self.send_response(200, msg1)
        self.send_header('Connection', 'close')
        self.end_headers()

        conns = [self.connection, conn]
        keep_connection = True
        while keep_connection:
            keep_connection = False
            rlist, wlist, xlist = select.select(conns, [], conns, self.timeout)
            if xlist:
                break
            for r in rlist:
                other = conns[1] if r is conns[0] else conns[0]
                data = r.recv(8192)
                if data:
                    other.sendall(data)
                    keep_connection = True
        conn.close()

    def do_HEAD(self):
        self.do_SPAM()

    def do_GET(self):
        self.do_SPAM()

    def do_POST(self):
        self.do_SPAM()

    def do_SPAM(self):
        req = self
        content_length = int(req.headers.get('Content-Length', 0))
        if content_length > 0:
            reqbody = self.rfile.read(content_length)
        else:
            reqbody = None

        replaced_reqbody = self.request_handler(req, reqbody)
        if replaced_reqbody is True:
            return
        elif replaced_reqbody is not None:
            reqbody = replaced_reqbody
            if 'Content-Length' in req.headers:
                req.headers['Content-Length'] = str(len(reqbody))

        self.remove_hop_by_hop_headers(req.headers)
        if self.upstream_timeout:
            req.headers['Connection'] = 'Keep-Alive'
        else:
            req.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(req.headers)

        try:
            res, resdata = self.request_to_upstream_server(req, reqbody)
        except socket.error:
            return

        content_encoding = res.headers.get('Content-Encoding', 'identity')
        resbody = self.decode_content_body(resdata, content_encoding)

        replaced_resbody = self.response_handler(req, reqbody, res, resbody)
        if replaced_resbody is True:
            return
        elif replaced_resbody is not None:
            resdata = self.encode_content_body(replaced_resbody, content_encoding)
            if 'Content-Length' in res.headers:
                res.headers['Content-Length'] = str(len(resdata))
            resbody = replaced_resbody

        self.remove_hop_by_hop_headers(res.headers)
        if self.timeout:
            res.headers['Connection'] = 'Keep-Alive'
        else:
            res.headers['Connection'] = 'close'
        if self.proxy_via:
            self.modify_via_header(res.headers)

        self.send_response(res.status, res.reason)
        for k, v in res.headers.items():
            if k == 'set-cookie':

                for value in self.split_set_cookie_header(v):
                    self.send_header(k, value)
            else:
                self.send_header(k, v)
        self.end_headers()

        if self.command != 'HEAD':
            self.wfile.write(resdata)
            with self.global_lock:
                self.save_handler(req, reqbody, res, resbody)

    def request_to_upstream_server(self, req, reqbody):
        u = urlsplit(req.path)
        origin = (u.scheme, u.netloc)

        req.headers['Host'] = u.netloc
        selector = "%s?%s" % (u.path, u.query) if u.query else u.path

        while True:
            with self.lock_origin(origin):
                conn = self.open_origin(origin)
                try:
                    conn.request(req.command, selector, reqbody, headers=dict(req.headers))
                except socket.error:

                    self.close_origin(origin)
                    raise
                try:
                    res = conn.getresponse(buffering=True)
                except httplib.BadStatusLine as e:
                    if e.line == "''":

                        self.close_origin(origin)
                        continue
                    else:
                        raise
                resdata = res.read()
                res.headers = res.msg
                if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''):
                    self.close_origin(origin)
                else:
                    self.reset_timer(origin)
            return res, resdata

    def lock_origin(self, origin):
        d = self.conn_table.setdefault(origin, {})
        if not 'lock' in d:
            d['lock'] = Lock()
        return d['lock']

    def open_origin(self, origin):
        conn = self.conn_table[origin].get('connection')
        if not conn:
            scheme, netloc = origin
            if scheme == 'https':
                conn = httplib.HTTPSConnection(netloc)
            else:
                conn = httplib.HTTPConnection(netloc)
            self.reset_timer(origin)
            self.conn_table[origin]['connection'] = conn
        return conn

    def reset_timer(self, origin):
        timer = self.conn_table[origin].get('timer')
        if timer:
            timer.cancel()
        if self.upstream_timeout:
            timer = Timer(self.upstream_timeout, self.close_origin, args=[origin])
            timer.daemon = True
            timer.start()
        else:
            timer = None
        self.conn_table[origin]['timer'] = timer

    def close_origin(self, origin):
        timer = self.conn_table[origin]['timer']
        if timer:
            timer.cancel()
        conn = self.conn_table[origin]['connection']
        conn.close()
        del self.conn_table[origin]['connection']

    def remove_hop_by_hop_headers(self, headers):
        hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade']
        connection = headers.get('Connection')
        if connection:
            keys = re.split(r',\s*', connection)
            hop_by_hop_headers.extend(keys)

        for k in hop_by_hop_headers:
            if k in headers:
                del headers[k]

    def modify_via_header(self, headers):
        via_string = "%s %s" % (self.protocol_version, self.proxy_via)
        via_string = re.sub(r'^HTTP/', '', via_string)

        original = headers.get('Via')
        if original:
            headers['Via'] = original + ', ' + via_string
        else:
            headers['Via'] = via_string

    def decode_content_body(self, data, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO(data)
            with gzip.GzipFile(fileobj=io) as f:
                body = f.read()
        elif content_encoding == 'deflate':
            body = zlib.decompress(data)
        elif content_encoding == 'identity':
            body = data
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return body

    def encode_content_body(self, body, content_encoding):
        if content_encoding in ('gzip', 'x-gzip'):
            io = StringIO()
            with gzip.GzipFile(fileobj=io, mode='wb') as f:
                f.write(body)
            data = io.getvalue()
        elif content_encoding == 'deflate':
            data = zlib.compress(body)
        elif content_encoding == 'identity':
            data = body
        else:
            raise Exception("Unknown Content-Encoding: %s" % content_encoding)
        return data

    def split_set_cookie_header(self, value):
        re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?'
        return re.findall(re_cookies, value, flags=re.IGNORECASE)

    def request_handler(self, req, reqbody):

        pass

    def response_handler(self, req, reqbody, res, resbody):

        pass

    def save_handler(self, req, reqbody, res, resbody):

        pass

def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"):
    if sys.argv[1:]:
        port = int(sys.argv[1])
    else:
        port = 8799
    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()

if __name__ == '__main__':
    test()