Académique Documents
Professionnel Documents
Culture Documents
Sombrio
2013
Sombrio
2013
______________________________________________________
Professor e orientador Jferson Mendona de Limas, Msc.
Instituto Federal de Educao, Cincia e Tecnologia Catarinense Campus Sombrio
Orientador
______________________________________________________
Prof. Lucyene Lopes da Silva Todesco Nunes, Msc.
Instituto Federal de Educao, Cincia e Tecnologia Catarinense Campus Sombrio
Membro
______________________________________________________
Prof. Marco Antonio Silveira de Souza, Msc.
Instituto Federal de Educao, Cincia e Tecnologia Catarinense Campus Sombrio
Membro
AGRADECIMENTOS
Primeiramente agradeo a Deus por ter sade, trabalho e uma famlia muito, mas
muito especial. Agradeo a minha esposa Luciani Q. da Cunha Dal Pont por entender minha
ausncia e por sempre dar uma palavra de incentivo durante esta jornada. Aos professores
pela dedicao em compartilhar seus conhecimentos e pela compreenso dos atrasos no inicio
das aulas. Aos colegas que sempre tivemos uma relao de amizade e companheirismo
compartilhando conhecimentos. E por fim ao professor Orientador Jferson Mendoa de
Limas que no poupou esforos para que eu conclusse este trabalho.
RESUMO
ABSTRACT
This study aims to document the implementation of a management server with authentication
tools and capture data from the other servers in the Santa Catarina Federal Institute Campus
dingy (IFC-dingy). In it the Coovachilli tool will be implemented, making the student user or
server has to put through the browser your login and password to access the internet, which
performed after authentication in FreeRADIUS server, stores it in a MySQL database Along
the this process was placed the ngrep tool to capture data determined by the administrator, the
use of facebook, youtube and twiter, means of access which are not to study or work of IFCCampus dingy. All user access will be placed in text files, and Shell Script language will treat
the data, and through a html page will be shown to the administrator use time spent on social
networks
per
user.
LISTA DE ILUSTRAES
LISTA DE SIGLAS
AAA: (Autenticao, Autorizao e Contabilizao)
ACK: (Acknowledgment)
ASC: (Access Control Server)
ASCII: (American Standard Code for Information Interchange)
BNC: (Bayonet NeillConcelman)
BPF: (BSD Packet Filter)
CHAP: (Challenge-Handshake Authentication Protocol)
EAP: (Extensible Authentication Protocol)
FDDI: (Fiber Distributed Data Interface)
GB: (Gigabyte)
GBPS: (Gigabits Por Segundo)
GPL: (General Public License)
HTML: (HyperText Markup Language)
HTTP: (Hypertext Transfer Protocol)
HTTPS: (HyperText Transfer Protocol Secure)
IAS: (Internet Authentication Service)
ICMP: (Internet Control Message Protocol)
IFC: (Instituto Federal Catarinense)
IGMP: (Internet Group Management Protocol)
IP: (Internet Protocol)
LAN: (Local Area Network)
MAN: (Metropolitan Area Network)
MBPS: (Megabits Por Segundo)
NAK: (Not Acknowledgment)
NAS: (Network Attached Storage)
PAP: (Password Authentication Protocol)
PPP: (Point-to-Point Protocol)
RFC: (Request For Coments)
SLIP: (Serial Line Internet Protocol)
SNMP: (Simple Network Management Protocol)
SO: (Sistema Operacional)
SUMRIO
1 INTRODUO................................................................................................................. 11
2 OBJETIVOS ..................................................................................................................... 13
2.1 OBJETIVO GERAL ........................................................................................................ 13
2.2 OBJETIVOS ESPECFICOS........................................................................................... 13
3 REFERENCIAL TERICO ........................................................................................... 14
3.1 REDES DE COMPUTADORES ..................................................................................... 14
3.1.1 Redes Locais (LANs) ................................................................................................... 14
3.1.2 Redes Geograficamente Distribudas (WANs) ......................................................... 17
3.2 GERNCIA DE REDES ................................................................................................. 18
3.2.1 Requisitos de Gerenciamento ..................................................................................... 19
3.3 AUTENTICAO DE USURIOS ............................................................................... 20
3.3.1 RADIUS........................................................................................................................ 21
3.3.1.1 Mtodos de Autenticao ........................................................................................... 22
3.3.1.2 FreeRADIUS .............................................................................................................. 23
3.4 COOVACHILLI .............................................................................................................. 24
3.5 NGREP ............................................................................................................................ 25
3.6 SHELL SCRIPT............................................................................................................... 26
4 MATERIAL E MTODOS ............................................................................................. 29
4.1 TIPO DE PESQUISA ...................................................................................................... 29
4.2 MATERIAIS .................................................................................................................... 29
4.4 INSTALAO E CONFIGURAO ............................................................................ 31
5 RESULTADOS E DISCUSSO...................................................................................... 42
6 CONSIDERAES FINAIS ........................................................................................... 43
REFERNCIAS ..................................................................................................................... 44
ANEXOS ................................................................................................................................. 46
11
INTRODUO
O estudo das tecnologias est trazendo cada vez mais aplicativos que nos ajudam a
resolver problemas para as redes de computadores e nos diversos outros seguimentos da
informtica. O tema tratado a implantao de uma ferramenta que ajuda a ter controle sobre
os acessos dos usurios a Internet. Aplicar-se- o estudo em autenticar e controlar a rede
atravs de um servidor FreeRADIUS com um portal de autenticao para os usurios se
identificarem antes do acesso a Internet. Nestes aplicativos ser implantado tambm um
monitoramento que ajudar a verificar quais os sites de mais acesso por usurio.
Para Filagrana (2002) a autenticao sinnimo de segurana, pois torna os acessos
restritos a uma permisso, fazendo com que s pessoas autorizadas tenham acesso s
informaes de acesso a Web.
Tendo em vista a dificuldade de alunos e professores na navegao de sites e
contedos da Internet, ter controle sobre o trfego que cada usurio pode utilizar uma
maneira de tornar os servios de rede mais eficientes.
No Instituto Federal Catarinense Campus Sombrio (IFC Sombrio), a rede de
computadores e Internet no possui um controle de acesso de usurios, com identificao e
controle de velocidade, muitas vezes deixando o servio de navegao Web prejudicado. Que
ferramentas implantar na infraestrutura de rede para autenticar e monitorar os acessos dos
usurios? Durante os estudos foi possvel identificar uma variedade muito grande de
ferramentas teis para realizar as tarefas de autenticao e monitoramento de acessos de
usurios, escolheu-se as seguintes devido a grande documentao e facilidade de
implementao: Coovachilli, FreeRADIUS, Apache2, Ngrep e Shell Script.
Estes aplicativos instalados dentro do sistema operacional Ubuntu Server 12.04 tero
tarefas de proteger, controlar e mostrar os sites que passam na rede de computadores do IFC
Campus Sombrio.
Com um banco de dados juntam-se os controles de usurio e senha feitos atravs do
FreeRADIUS, alm dos dados da captura do Ngrep. Com o uso de shell script foi gerado uma
pagna html com resultado do tempo de uso destes sites por usurio.
A estrutura deste Trabalho de Concluso de Curso est explanada da seguinte forma: o
capitulo 2 com os objetivos alcanados, captulo 3 com a fundamentao terica trazendo o
bsico de redes de computadores e a base das ferramentas usadas. O captulo 4 traz o tipo de
12
13
OBJETIVOS
2.1
OBJETIVO GERAL
2.2
OBJETIVOS ESPECFICOS
a)
b)
c)
d)
14
REFERENCIAL TERICO
3.1
REDES DE COMPUTADORES
15
16
Barramento uma topologia cuja conexo feita atravs de cabo coaxial, com
conector BNC inserindo os hosts ao longo do cabo e por fim conectores de terminao,
mostrado na figura 4. Nesta topologia de rede, o rompimento do cabo em qualquer parte da
rede para todo funcionamento da mesma (MORAES, 2010).
Figura 4 - Redes em Barramento
17
As redes WAN ou mais conhecida como rede de longas distncias, tem abrangncia de
grandes regies geogrficas, pontos entre cidades, estados, pases e continentes, atravs dos
cabos de cobre, satlite, micro-ondas e fibras como meios de transmisso mais comuns
(MORAES, 2010).
Dentro de WAN existem as redes metropolitanas (MANs) como um subitem. todo e
qualquer tipo de conexo distribuindo Internet ou dados por uma rede abrangendo uma cidade
pode ser chamada de MAN, podendo ser por cabos coaxiais, fibras ou por ondas
eletromagnticas atravs de antenas sem fio (TANENBAUM, 2003).
Toda rede WAN contm numerosas linhas de transmisso, todas conectadas a vrios
roteadores. Quando um host em qualquer rede LAN for se comunicar com outro host em outra
rede LAN, seus dados sero encaminhados atravs de uma linha de transmisso para um
roteador e atravs de outros roteadores conectados a ele que os dados chegaro ao seu destino
na outra rede LAN (TANENBAUM, 2003).
Nas redes WAN usa-se a arquitetura multiponto ou ponto-multiponto, onde uma
informao sai de um ponto principal em um nico meio de transmisso e dividida para
vrios pontos por meios de endereos lgicos diferentes como mostra na figura 6 (SOUZA,
2009). Um bom exemplo desta rede WAN a Internet (TORRES, 2009).
18
3.2
GERNCIA DE REDES
19
Conforme nos coloca Stallings (2005) e proposto pela International Organization for
Standardization (ISO), as principais reas de gerenciamento so:
a)
falha, tomando o cuidado de isolar a mesma de toda a rede para que fique operando
sem causar muito impacto. Tornando o mais rpido possvel a correo e reparo para a
volta da normalidade;
b)
20
3.3
AUTENTICAO DE USURIOS
b)
uma rede, dando a ele permisses, privilgios, restries para o acesso ao recurso
dentro de uma rede. atravs destas regras que podemos limitar quantidade de sesses
por usurio, controle de acesso rede e limitar acesso por tempo determinado;
21
c)
3.3.1 RADIUS
22
a)
b)
23
c)
Autenticao Extensvel que segundo os autores Peres & Weber (2003), prov funes
de negociao a respeito de quais mtodos de autenticao sero utilizados e, alm
disso, oferece suporte a mltiplos mtodos de autenticao, chamados de mtodos
EAP. Dentre estes mtodos, podemos citar o EAP-MD5, EAP-TLS (muito utilizado
em redes sem fio) e EAP-TTLS. O servidor que deseja autenticar o cliente, requisita
informaes adicionais a respeito do mesmo, e um dos mtodos EAP ento
solicitado para prover a autenticao.
3.3.1.2 FreeRADIUS
24
como o ACS Cisco (Access Control Server) e o Microsoft IAS (Internet Authentication
Service), tornando-se uma ferramenta bastante popular.
Segundo a RFC 2865 e RFC 2866 a comunicao do protocolo RADIUS entre o
cliente e o servidor feita atravs do protocolo UDP. Segundo Antunes (2009), o
FreeRADIUS trabalha com a tecnologia cliente e servidor. A comunicao entre cliente e
servidor se d pelo protocolo RADIUS que trabalha a autenticao at o banco de dados NAS
por meio do protocolo UDP na porta 1812 e na porta 1813 para contabilizao-radacct
definido na RFC 2865.
O FreeRADIUS quando instalado em modo completo oferece as seguintes
ferramentas:
3.4
COOVACHILLI
denominado portal de captura (Captive Portal). Foi baseado no seu antecessor, ChilliSpot,
sendo mantido pelos mesmo colaboradores. distribudo sob a GPL (General Public
License), ou seja, cdigo fonte aberto e livre para alteraes. Seu proposito capturar atravs
do navegador, login e senha dos usurios e conduzir atravs do protocolo RADIUS ao
servidor de autenticao escolhido, como mostra a figura 7, tornando a rede mais segura,
permitindo mais controle e com uma abordagem de autenticao por protocolo HTTP para o
25
3.5
NGREP
Segundo Ritter (2011), a ferramenta Ngrep usa o pcap-aware que permite a voc
especificar expresses regulares estendidas ou hexadecimais para comparao das cargas de
dados de pacotes (payload). Identificando o contedo relevante ao que se procura, scaneando
a sada do comando linha por linha, procurando pelos argumentos especificados na sintaxe de
pesquisa deste comando. Atualmente, reconhece IPv4 / 6, TCP, UDP, ICMPv4 / 6, IGMP e
Raw atravs de Ethernet, PPP, SLIP, FDDI, Token Ring e interfaces nulas, e entende lgica
de filtro BPF da mesma forma como ferramentas de deteco de pacotes mais comuns, tais
como tcpdump e snoop.
O NGrep tenta copiar ao mximo todas as funcionalidades presentes no Grep do Unix,
porm as aplica aos pacotes de rede. Ele tem suporte ao Linux, Mac OS X, Solaris, FreeBSD,
OpenBSD, NetBSD, HP-UX, AIX e todas as verses de Windows. Para funcionar
tranquilamente ele precisa da biblioteca PCAP, que no Unix a libpcap e no Windows a
WinPcap. Alguns comandos bsicos:
-l = Cria a linha de sada no buffer1;
1
Memria temporria.
26
-q = Fica esttico, sem mostrar qualquer outra informao dos cabealhos dos pacotes
e sua carga til (s mostra o que for pedido no comando);
-t = Imprime o timestamp no formato YYYY / MM / DD HH: MM: SS.UUUUUU
sempre que um pacote correspondido pesquisa;
-d = forar o ngrep escutar a interface que voc especificar;
eth2 = interface especificada pelo administrador para o ngrep escutar, do contrrio o
ngrep ir escutar a eth0 por padro;
-i = ignorar caso a expresso no possuir o expresso a ser filtrada entre os apstrofos.
Segue exemplificao na figura 8 dos comandos dados pelo Ngrep neste trabalho.
Figura 8 - Captura Ngrep das URLs
3.6
SHELL SCRIPT
execuo, como por exemplos backups automatizados por tempo. O Shell o local que recebe
os comandos, parmetros e funes digitados pelo usurio, e os executa. Cada comando
lido, verificado, interpretado e enviado ao sistema operacional para ser executado, ou seja, a
ligao entre o usurio e o kernel (ligao do Sistema Operacional com o hardware).
Conforme o mesmo autor (2008), a juno do Shell com o Script, foi para facilitar a
automatizao de funes do dia a dia principalmente aos administradores de rede. Nos dias
de hoje scripts so considerados roteiros de comandos desleixados, usados somente para
27
comentados,
b)
c)
d)
e)
f)
propriedades;
g)
linha e espaos;
h)
grep: procura em arquivos ou textos por linhas que contem determinado padro
de pesquisa;
i)
j)
hexadecimal e ASCII;
k)
l)
m)
n)
o)
p)
q)
tac: faz a contagem numrica por linha e mostra a sequencia inversa na tela;
r)
s)
t)
28
u)
v)
w)
uma;
STDIN.
Com base nos comandos citados possvel gerar programas com execuo em modo
oculto liberando o usurio de comandos repetitivos e cansativos. Estes programas podem
servir para realizar consultas, insero, alterao entre outras funes em arquivos de log e de
sistemas.
29
MATERIAL E MTODOS
4.1
TIPO DE PESQUISA
O trabalho proposto caracteriza-se como uma pesquisa aplicada, pois como esta
definida por Lakatos e Marconi (2012), este tipo de pesquisa busca aplicar o conhecimento
adquirido na soluo de um problema. Assim podemos considerar a implantao de um Portal
de Autenticao e Monitoramento de Usurios no IFC Campus Sombrio como uma
pesquisa aplicada.
Ainda conforme as mesmas autoras (2012), temos a pesquisa experimental que trata de
estudos explicativos, avaliativos e interpretativos colocado em implementao para a
mudana do problema proposto ao trabalho, e assim caracteriza-se a implantao do Portal de
Autenticao e Monitoramento de Usurios, pois no decorrer do processo a pesquisa foi sendo
reavaliada e alterada conforme as necessidades surgidas.
4.2
MATERIAIS
30
Uma Mquina Virtual com o SO Linux Ubuntu Server 12.04, com 1gb memria e
com trs placas de rede. Uma placa de entrada para Internet, e uma placa para o range2 dos
usurios e outra placa para o range do administrador;
Duas Mquinas Virtuais com SO Windows XP com uma placa de rede cada para
testes no ranges dos usurios e administrador;
4.3
MTODOS
Na infraestrutura de redes de computadores do IFC props-se implementar um
servidor Ubuntu 12.04 com servios de autenticao e captura de dados. Para autenticao
usou-se o servidor FreeRADIUS com banco de dados MySQL e com gerenciamento do
aplicativo DaloRADIUS. J para o usurio efetuar o login de autenticao usou-se o
CoovaChilli como um Hotspot, fazendo assim a interface entre o usurio e o servidor
FreeRADIUS.
No monitoramento apresentou-se melhor a ferramenta Ngrep que faz a captura de
dados determinados pelo administrador e armazena em arquivos de texto. Como nosso
propsito fazer o monitoramento por usurio logado no servidor FreeRADIUS, usamos a
linguagem Shell Script para filtrar os usurios cadastrados no banco de dados MySQL e
atrelar o ip do arquivo armazenado do Ngrep. Trazendo para o administrador de rede o nome
do usurio e o tempo que ele usou durante o seu expediente. Gerando ao administrador uma
pgina web com os dados e para relatrios para sua anlise.
Para que o FreeRadius, o CoovaChilli e Ngrep ter um funcionamento adequado
necessrio instalar no servidor Ubuntu mais um componente bsico, o Apache2. Ele far com
que o CoovaChilli mostre, atravs do navegador, onde o usurio possa fazer seu login e senha
e as guarde no banco de dados proposto. A topologia lgica da rede esta exemplificada na
figura 9.
31
4.4
INSTALAO E CONFIGURAO
Para que possamos instalar sem nenhum problema faremos a autenticao no Ubuntu
Server como root, para ter todos os privilgios de administrador executando o comando #sudo
su, e preenchendo a senha de super usurio. Como se trata de um servidor que far
autenticao por usurio usando o CoovaChilli tem-se que configurar uma placa de rede em
modo manual, pois quem far o DHCP3 para a rede ser o prprio CoovaChilli. Por padro as
placas de redes esto configuradas por DHCP, no arquivo interfaces, localizado no diretrio
/etc/network/, que ser editado para o modo manual e esttico, como mostra na figura 10. Para
ter efeito estas configuraes nas interfaces aqui modificadas foi executado o comando
32
33
34
35
36
com
comando
#wget
http://ap.coova.org/uam/
#wget
>
/usr/lib/cgi-bin/hotspotlogin.cgi
para
37
dentro
/var/www/hotspot/images.
Com
de
hotspot
os
copia-se
comandos
#chown
imagem
R
coova.jpg
para
www-data.www-data
/usr/lib/cgi-bin/hotspotlogin.cgi
chmod
777
/usr/lib/cgi-
para
baixar este plugin que funcionar na autenticao do usurio pelo CoovaChilli at o banco de
dados. Para instalar, usou-se o comando #tar xzf haserl-0.9.27.tar.gz && cd /tmp/haserl0.9.27 que extrai o arquivo zip, e os comandos #./configure, #make e #make install.
Com o trmino da instalao modificou-se o arquivo wwwsh no diretrio /etc/chilli
seguindo o anexo 6, e o arquivo up.sh adicionando quatro linhas no final do arquivo
especificado no anexo 7. Para terminar esta etapa da autenticao foi atualizado os scripts
com o comando #update-rc.d chilli defaults e feito a reinicializao do SO para que o
navegador abrar pedindo o login e senha como mostra a figura 16 quando for usar a internet.
Dando ao administrador da rede poder de controlar por nome seus usurios.
Figura 16 - Captura login e senha Coovachilli
38
Neste script o ngrep faz a captura atravs dos parmetros e expresso, sendo o l que
cria a linha de sada no buffer, o q que mostra s o que esta no comando, o t que cria a data
e a hora quando encontra a expresso, o d que fora escutar a placa de rede determinada e
por fim o i passa direto se na pesquisa no encontrar a expresso imposta, guardando em um
arquivo texto especificado.
Com os dados capturados e gravados no arquivo texto, trata-se estes dados para
eliminar partes que no necessitam e fica somente o que necessrio para o propsito de
saber quanto tempo o usurio ficou usando uma destas urls4. Na figura 18 mostra o script de
limpeza dos dados.
39
Neste script de filtro usa varia ferramentas, o grep que procura por linha o que contm
entre colchetes, o cut que extrai campos ou trechos de uma linha, o tr que comprimi ou apaga
caracteres que for determinado e o sed que troca ou substitui uma string por outra. Este script
salvo em um arquivo texto para poder ser manipulado.
Usa-se um comando em Shell Script e MySQL para importar do arquivo texto anterior
em uma tabela dentro do banco de dados. Segue a figura 19 dos comandos executados.
Figura 19 Importao arquivo texto para tabela MySQL.
40
Com todos os dados na tabela fez-se uma consulta em linguagem SQL, foram
capturados os dados das tabelas e os comparando para retirar a tabela de dados por nome e
tempo de uso. Como mostra na figura 20.
Figura 20 - Consulta de tabelas MySQL
Para mostrar o resultado atravs de uma pagina web, usou-se um cdigo em html
chamando um cdigo em php descrito na figura 21, por nome de usurio.
Figura 21 - Cdigo HTML para pagina web
41
Com o cdigo em html feito, desenvolveu-se um cdigo em php que consulta o banco de
dados SQL, e compara os dados pela data, hora e usurio, mostrando um relatrio com data e hora de
uso por usurio de quem o fez como mostra a figura 22.
Figura 22 - Cdigo PHP para pagina web.
42
RESULTADOS E DISCUSSO
Com a realizao das pesquisas e testes, foi possvel perceber que os objetivos de
melhorar o uso de Internet atravs do servidor de gerenciamento da rede foi positivo. Levando
em considerao que a autenticao de cada usurio, atravs do servidor FreeRADIUS
garante uma maior segurana rede, dando ao administrador a possibilidade de controle pelo
banco de dados armazenado. A navegao que antes era livre teve um ponto positivo ao
momento que o cadastramento de cada usurio e a captura de dados foi relacionadas tornando
visvel o tempo gasto de cada usurio com acessos indevidos aos parmetros educacionais ou
de trabalho, mostrado atravs de uma pagina html ilustrado na figura 23.
Para a o administrador da rede tornou-se mais fcil o controle de acesso aos alunos,
professores e servidores tendo um relatrio dirio de uso para tomar suas decises em relao
ao consumo excessivo de internet, caso mais crtico no ponto de vista do objetivo deste
trabalho.
43
CONSIDERAES FINAIS
Este trabalho teve por objetivo implementar servios capazes de autenticar e monitorar
os usurios para melhorar a resoluo do problema com segurana do acesso aos alunos e
servidores do Instituto Federal Catarinense Campus Sombrio. Tambm ir proporcionar o
conhecimento dos usurios que mais consomem banda da rede e ter o controle de acesso para
fazer uma diviso igualitria de banda. Propor-se a instalao de um servidor de
gerenciamento e monitoramento da rede do Campus Sombrio. Para que este servidor pudesse
ser implantado a rede, com autenticao pelo servidor FreeRADIUS, com o servio do portal
de captura dos logins e senhas dos usurios bem sucedida.
Para estes servios usou-se as principais reas de gerenciamento colocando na
estrutura a autenticao de login e senha e armazenando em banco de dados para a segurana
e contabilidade dos acessos. Complementando a estrutura da rede capturou-se dados dos
usurios para verificao de possveis erros, nmero de acessos e fluxo para verificar o
desempenho e as falhas contidas na rede.
Para o propsito de monitoramento usou-se a ferramenta Ntop que tinha tudo para dar
certo aps anlises e estudos sobre ela, mas no foi possvel fazer a leitura do banco de dados
em formato .rrd e .db, ambos com criptografia ativa. Neste intuito foi necessrio mudar para a
captura de dados atravs da ferramenta Ngrep que foi muito rpido e fcil de implementao.
Nela aplicamos a captura de dados relacionados a parmetros como palavras, urls, sites,
protocolos, para analisar e relacionar com a autenticao de cada usurio na rede atravs da
linguagem de programao Shell Script, filtrando os dados e comparando o IP da captura com
o IP do usurio. Nesta programao foi encontrado um pouco de dificuldade, pois envolve
muitos detalhes da linguagem para comparao, extrao dos dados ao resultado final.
Para trabalhos futuros propem-se a gerao de grficos com os resultados obtidos e
com a diversificao da captura de dados por outros parmetros.
44
REFERNCIAS
ANTUNES, Vitor Hugo Leite. Frontend web 2.0 para Gesto de RADIUS. Major
Telecomunicaes. Dessertao de mestrado. 2008/2009. Disponvel em:
http://paginas.fe.up.pt/~ee04199/Frontend%20Web%202.0%20para%20Gestao%20de%20
RADIUS.pdf. Acessado em: 23 nov. 2013.
CAMPOS, Juliana C. Moura.et al. Segurana de redes. Pontifcia Universidade Catlica de
Campinas. 2005.
COOVACHILLI, Coova.org. 2008, Disponvel em: http://www.coova.org/CoovaChilli
acessado em 15 nov. 2013.
FILAGRANA, Artur Carlos. Sistema de autenticao de usurios para provedores de
internet baseado no numero telefnico. Universidade para o Desenvolvimento do
Alto Vale do Itaja. INIDAVI. Itaja, SC, 2002.
JARGAS, Aurelio Marinho. Shell Script: Profissional / Aurelio Marinho Jargas. So Paulo:
Novatec Editora, 2008.
MARCONI, Marina de Andrade; LAKATOS, Eva Maria. Tcnicas de pesquisa:
planejamento e execuo de pesquisas, amostragens e tcnicas de pesquisa, elaborao,
anlise e interpretao de dados. 7 ed. 6 Reimpr. So Paulo: Atlas, 2012.
MARTINEZ,
Marina.
Topologias
de
Redes.
2010,
Disponvel
em:http://www.infoescola.com/informatica/topologias-de-redes/ acessado em 14 nov.
2013.
MORAES, Alexandre Fernandes de. Redes de Computadores: fundamentos. 7 ed. So
Paulo: rica, 2010.
NETVOX, Disponvel em:http://www.netvoxdigital.com.br acessado em 18 nov. 2013.
PEREIRA, Marcos Heyse. Segurana de redes sem fio, uma proposta com servios
integrados de autenticao LDAP e RADIUS. Pontifcia Universidade Catlica da
Paran. 2009. P. 9.
PERES, Andr; WEBER, Raul Fernando. Consideraes sobre Segurana em Redes Sem
Fio. ULBRA Universidade Luterana do Brasil; UFRGS Universidade Federal do Rio
Grande do Sul. 2003.
RFC2865. RADIUS Accounting. 2000. Disponvel em: http://tools.ietf.org/html/rfc2866.
Acessado em 22 de nov. 2013.
RFC2866. Remote Authentication Dial In User Service: RADIUS. 2000. Disponvel em:
http://tools.ietf.org/pdf/rfc2865.pdf. Acessado em 22 de nov. 2013.
45
RITTER,
Jordan.
ngrep
network
grep.
2011,
em:http://www.ngrep.sourceforge.net acessado em 15 de nov. 2013.
Disponivel
RUFINO, Nelson Murilo de Oliveira. Segurana em Redes sem Fio: Aprenda a proteger
suas informaes em ambientes Wi-Fi e Bluetooth. Edio 3. Editora Novatec. 2007.
SOUZA, Lindeberg Barros de. Redes de Computadores: guia total 1 ed. So Paulo: rica,
2009.
SOUZA, Lindeberg Barros de. Projetos e implementao de redes: fundamentos, solues,
arquiteturas e planejamento. 2 ed. So Paulo: rica, 2009.
STALLINGS, William. Redes e sistemas de comunicao de dados: teoria e aplicaes
corporativas Rio de Janeiro: Elsevier, 2005 5 Reimpr.
TANENBAUM, Andrew S. Redes de Computadores. 4 ed. Rio de Janeiro: Elsevier, 2003.
TORRES, Gabriel. Redes de Computadores. Rev. e atualiz. So Paulo: Novaterra, 2009.
WALT, Dirk Van Der. FreeRADIUS: Manage your network resources with FreeRADIUS.
Editora: Published by Packt Publishing Ltda. 2011.
46
ANEXOS
#
#
#
#
$Id$
#
#####################################################################
#
#
#
Read "man radiusd" before editing this file. See the section
of this file.
#
#
#
#
The best way to configure the server for your local system
edits to this file will BREAK THE SERVER. Any edits should
47
Once the edits have been verified to work, save a copy of these
#
#
authenticate users.
#
#####################################################################
#
#
#
#
#
#
#
48
#
# If you want to have a log of authentication requests,
# un-comment the following line, and the 'detail auth_log'
# section, above.
#
auth_log
#
# The chap module will set 'Auth-Type := CHAP' if we are
# handling a CHAP request and Auth-Type has not already been set
chap
#
# If the users are logging in with an MS-CHAP-Challenge
# attribute for authentication, the mschap module will find
# the MS-CHAP-Challenge attribute, and add 'Auth-Type := MS-CHAP'
# to the request, which will cause the server to then use
# the mschap module for authentication.
mschap
#
# If you have a Cisco SIP server authenticating against
49
#
# The WiMAX specification says that the Calling-Station-Id
# is 6 octets of the MAC. This definition conflicts with
# RFC 3580, and all common RADIUS practices. Un-commenting
# the "wimax" module here means that it will fix the
# Calling-Station-Id attribute to the normal format as
# specified in RFC 3580 Section 3.21
#
wimax
#
# Look for IPASS style 'realm/', and if not found, look for
# '@realm', and decide whether or not to proxy, based on
# that.
#
IPASS
#
# If you are using multiple kinds of realms, you probably
# want to set "ignore_null = yes" for all of them.
# Otherwise, when the first style of realm doesn't match,
# the other styles won't be checked.
#
suffix
#
ntdomain
#
# This module takes care of EAP-MD5, EAP-TLS, and EAP-LEAP
# authentication.
#
# It also sets the EAP-Type attribute in the request
50
#
# Pull crypt'd passwords from /etc/passwd or /etc/shadow,
# using the system API's to get the password. If you want
# to read /etc/passwd or /etc/shadow directly, see the
# passwd module in radiusd.conf.
#
#
unix
#
# Read the 'users' file
#
files
#
# Look in an SQL database. The schema of the database
# is meant to mirror the "users" file.
#
# See "Authorization Queries" in sql.conf
51
sql
#
# If you are using /etc/smbpasswd, and are also doing
# mschap authentication, the un-comment this line, and
# configure the 'etc_smbpasswd' module, above.
#
etc_smbpasswd
#
# The ldap module will set Auth-Type to LDAP if it has not
# already been set
#
ldap
#
# Enforce daily limits on time spent logged in.
#
daily
#
# Use the checkval module
#
checkval
expiration
logintime
#
# If no other module has claimed responsibility for
# authentication, then try to use PAP. This allows the
# other modules listed above to add a "known good" password
# to the request, and to do nothing else. The PAP module
# will then see that password, and use it to do PAP
# authentication.
#
# This module should be listed last, so that the other modules
52
#
# If "status_server = yes", then Status-Server messages are passed
# through the following section, and ONLY the following section.
# This permits you to do DB queries, for example. If the modules
# listed here return "fail", then NO response is sent.
#
#
Autz-Type Status-Server {
#
#
# Authentication.
#
#
# This section lists which modules are available for authentication.
# Note that it does NOT mean 'try each module in order'. It means
# that a module from the 'authorize' section adds a configuration
# attribute 'Auth-Type := FOO'. That authentication type is then
# used to pick the apropriate module from the list below.
#
# In general, you SHOULD NOT set the Auth-Type attribute. The server
# will figure it out on its own, and will do the right thing. The
# most common side effect of erroneously setting the Auth-Type
# attribute is that one authentication method will work, but the
# others will not.
#
# The common reasons to set the Auth-Type attribute by hand
53
#
# Most people want CHAP authentication
# A back-end database listed in the 'authorize' section
# MUST supply a CLEAR TEXT password. Encrypted passwords
# won't work.
Auth-Type CHAP {
chap
}
#
# MSCHAP authentication.
Auth-Type MS-CHAP {
mschap
}
54
#
# If you have a Cisco SIP server authenticating against
# FreeRADIUS, uncomment the following line, and the 'digest'
# line in the 'authorize' section.
digest
#
# Pluggable Authentication Modules.
#
pam
#
# See 'man getpwent' for information on how the 'unix'
# module checks the users password. Note that packets
# containing CHAP-Password attributes CANNOT be authenticated
# against /etc/passwd! See the FAQ for details.
#
# For normal "crypt" authentication, the "pap" module should
# be used instead of the "unix" module. The "unix" module should
# be used for authentication ONLY for compatibility with legacy
# FreeRADIUS configurations.
#
unix
Auth-Type LDAP {
ldap
55
#
# The older configurations sent a number of attributes in
# Access-Challenge packets, which wasn't strictly correct.
# If you want to filter out these attributes, uncomment
# the following lines.
#
#
Auth-Type eap {
eap {
handled = 1
attr_filter.access_challenge.post-auth
#
#
}
}
#
# Pre-accounting. Decide which accounting type to use.
#
preacct {
preprocess
#
# Session start times are *implied* in RADIUS.
# The NAS never sends a "start time". Instead, it sends
# a start packet, *possibly* with an Acct-Delay-Time.
# The server is supposed to conclude that the start time
# was "Acct-Delay-Time" seconds in the past.
56
#
# The code below creates an explicit start time, which can
# then be used in other modules.
#
# The start time is: NOW - delay - session_length
#
update request {
Session-Time}:-0} - %{%{Acct-Delay-Time}:-0}}"
#
#
# Ensure that we have a semi-unique identifier for every
# request, and many NAS boxes are broken.
acct_unique
#
# Look for IPASS-style 'realm/', and if not found, look for
# '@realm', and decide whether or not to proxy, based on
# that.
#
# Accounting requests are generally proxied to the same
# home server as authentication requests.
#
IPASS
suffix
ntdomain
#
# Read the 'acct_users' file
files
}
57
#
# Accounting. Log the accounting data.
#
accounting {
#
# Create a 'detail'ed log of the packets.
# Note that accounting requests which are proxied
# are also logged in the detail file.
detail
#
daily
#
# For Simultaneous-Use tracking.
#
# Due to packet losses in the network, the data here
# may be incorrect. There is little we can do about it.
radutmp
#
sradutmp
main_pool
#
# Log traffic to an SQL database.
#
# See "Accounting queries" in sql.conf
sql
58
#
# If you receive stop packets with zero session length,
# they will NOT be logged in the database. The SQL module
# will print a message (only in debugging mode), and will
# return "noop".
#
# You can ignore these packets by uncommenting the following
# three lines. Otherwise, the server will not respond to the
# accounting request, and the NAS will retransmit.
#
#
if (noop) {
#
#
ok
}
#
# Instead of sending the query to the SQL server,
# write it into a log file.
#
#
sql_log
pgsql-voip
#
# See "Autz-Type Status-Server" for how this works.
#
59
Acct-Type Status-Server {
#
#
#
# See "Simultaneous Use Checking Queries" in sql.conf
sql
}
# Post-Authentication
# Once we KNOW that the user has been authenticated, there are
# additional steps we can take.
post-auth {
# Get an address from the IP Pool.
#
main_pool
#
# If you want to have a log of authentication replies,
# un-comment the following line, and the 'detail reply_log'
# section, above.
#
reply_log
#
# After authenticating the user, do another SQL query.
60
#
# See "Authentication Logging Queries" in sql.conf
#
sql
#
# Instead of sending the query to the SQL server,
# write it into a log file.
#
#
sql_log
#
# Un-comment the following if you have set
# 'edir_account_policy_check = yes' in the ldap module sub-section of
# the 'modules' section.
#
#
ldap
#
# Calculate the various WiMAX keys. In order for this to work,
# you will need to define the WiMAX NAI, usually via
#
#
update request {
#
#
WiMAX-MN-NAI = "%{User-Name}"
}
#
# If you want various keys to be calculated, you will need to
# update the reply with "template" values. The module will see
# this, and replace the template values with the correct ones
# taken from the cryptographic calculations. e.g.
#
61
update reply {
WiMAX-FA-RK-Key = 0x00
WiMAX-MSK = "%{EAP-MSK}"
#
# You may want to delete the MS-MPPE-*-Keys from the reply,
# as some WiMAX clients behave badly when those attributes
# are included. See "raddb/modules/wimax", configuration
# entry "delete_mppe_keys" for more information.
#
#
wimax
update reply {
Reply-Message += "%{TLS-Cert-Serial}"
Reply-Message += "%{TLS-Cert-Expiration}"
Reply-Message += "%{TLS-Cert-Subject}"
Reply-Message += "%{TLS-Cert-Issuer}"
Reply-Message += "%{TLS-Cert-Common-Name}"
#
#
Reply-Message += "%{TLS-Client-Cert-Serial}"
Reply-Message += "%{TLS-Client-Cert-Expiration}"
Reply-Message += "%{TLS-Client-Cert-Subject}"
62
Reply-Message += "%{TLS-Client-Cert-Issuer}"
Reply-Message += "%{TLS-Client-Cert-Common-Name}"
# If the WiMAX module did it's work, you may want to do more
# things here, like delete the MS-MPPE-*-Key attributes.
#
#
if (updated) {
update reply {
MS-MPPE-Recv-Key !* 0x00
MS-MPPE-Send-Key !* 0x00
#
#
}
}
#
# Access-Reject packets are sent through the REJECT sub-section of the
# post-auth section.
#
# Add the ldap module name (or instance) if you have set
# 'edir_account_policy_check = yes' in the ldap module configuration
#
Post-Auth-Type REJECT {
# log failed authentications in SQL, too.
#
sql
attr_filter.access_reject
}
#
# When the server decides to proxy a request to a home server,
# the proxied request is first passed through the pre-proxy
# stage. This stage can re-write the request, or decide to
63
attr_rewrite
files
attr_filter.pre-proxy
pre_proxy_log
#
# When the server receives a reply to a request it proxied
# to a home server, the request may be massaged here, in the
# post-proxy stage.
#
post-proxy {
post_proxy_log
64
attr_rewrite
attr_filter.post-proxy
#
# If you are proxying LEAP, you MUST configure the EAP
# module, and you MUST list it here, in the post-proxy
# stage.
#
# You MUST also use the 'nostrip' option in the 'realm'
# configuration. Otherwise, the User-Name attribute
# in the proxied request will not match the user name
# hidden inside of the EAP packet, and the end server will
# reject the EAP request.
#
eap
#
# If the server tries to proxy a request and fails, then the
# request is processed through the modules in this section.
#
# The main use of this section is to permit robust proxying
# of accounting packets. The server can be configured to
# proxy accounting packets as part of normal processing.
# Then, if the home server goes down, accounting packets can
# be logged to a local "detail" file, for processing with
# radrelay. When the home server comes back up, radrelay
# will read the detail file, and send the packets to the
# home server.
#
65
Post-Proxy-Type Fail {
#
#
detail
}
}
Anexo 2 Arquivo de configurao radiusd.conf
/**
* ChilliLibrary.js
* V2.0
*
* This library creates four global objects :
*
*
66
- chilliJSON
tag to the HTML DOM (this hack enables cross server requests).
*
*
- chilliClock
implemented)
- chilliLibrary
* TODO :
67
http://pajhome.org.uk/crypt/md5
*/
/**
68
* CONFIGUARION PROPERTIES
* -----------------------
*
*
ident (String)
Hex encoded string (used for client side CHAP-Password calculations)
*
*
interval (Number)
host (String)
port (Number)
*
*
ssl (Boolean)
69
uamService : String
URL to external uamService script (used for external MD5 calculation when
This remote script runs on a SSL enable web server, and knows UAM SECRET.
The chilliController javascript object will send the password over SSL (and
*/
if (!chilliController || !chilliController.host)
70
chilliController.session
= {} ;
chilliController.accounting = {} ;
chilliController.redir
= {} ;
chilliController.challenge
= '' ;
chilliController.message
= '' ;
chilliController.clientState
= chilliController.stateCodes.UNKNOWN ;
chilliController.command
= '' ;
chilliController.autorefreshTimer = 0 ;
chilliController.urlRoot = function () {
71
return urlRoot;
};
log('>> Default onUpdate handler. <<\n>> You should write your own. <<\n>> cmd =
' + cmd + ' <<' );
};
log ( '>> Default Error Handler<<\n>> You should write your own <<\n>> ' + str + '
<<' );
};
if ( typeof(t) == 'undefined' ) {
72
t = parseInt ( t , 10 ) ;
return zeroReturn;
var s = t % 60 ;
73
if
else
};
if ( typeof(b) == 'undefined' ) {
b = 0;
} else {
b = parseInt ( b , 10 ) ;
return zeroReturn;
74
};
/**
* PUBLIC METHODS
* --------------
75
logoff () :
refresh () :
*/
76
log ( 'chilliController.logon( "' + username + '" , "' + password + ' " )' );
chilliController.command = 'logon';
chilliJSON.onError
= chilliController.onError
chilliJSON.onJSONReady = chilliController.logonStep2 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
77
};
log ( 'chilliController.logon2( "' + username + '" , "' + response + ' " )' );
chilliController.command = 'logon2';
chilliJSON.onError
= chilliController.onError
78
chilliJSON.onJSONReady = chilliController.logonStep2 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
chilliJSON.get( chilliController.urlRoot() + 'status' ) ;
};
/**
*/
79
var c ;
if ( chilliController.uamService.indexOf('?') === -1 ) {
c = '?' ;
80
else {
c = '&' ;
= chilliController.onError
chilliJSON.onJSONReady = chilliController.logonStep3 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
chilliJSON.get( url ) ;
}
else {
/* TODO: Should check if challenge has expired and possibly get a new one */
/*
*/
81
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliController.clientState = chilliController.stateCodes.AUTH_PENDING ;
};
/**
* Third part of the logon process invoked after
* getting a uamService response
*/
chilliController.logonStep3 = function ( resp ) {
log('Entering logonStep 3');
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliController.clientState = chilliController.stateCodes.AUTH_PENDING ;
82
chilliController.refresh = function ( ) {
if ( chilliController.autorefreshTimer ) {
chilliController.command = 'autorefresh' ;
}
else {
chilliController.command = 'refresh' ;
}
chilliJSON.onError
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliJSON.get( chilliController.urlRoot() + 'status' ) ;
};
chilliController.logoff = function () {
chilliController.command = 'logoff'
chilliJSON.onError
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliJSON.get( chilliController.urlRoot() + 'logoff' );
};
/* *
83
*
* This functions does some check/type processing on the JSON resp
* and updates the corresponding chilliController members
*
*/
chilliController.processReply = function ( resp ) {
/* The following trick will replace HTML entities with the corresponding
* character. This will not work in Flash (no innerHTML)
*/
84
/* Update the session member only the first time after AUTH */
if ( (typeof ( resp.session ) == 'object') &&
( chilliController.session==null || (
( chilliController.clientState !== chilliController.stateCodes.AUTH ) &&
( resp.clientState === chilliController.stateCodes.AUTH )))) {
chilliController.session = resp.session ;
if ( resp.session.startTime ) {
chilliController.session.startTime = new Date();
chilliController.session.startTime.setTime(resp.session.startTime);
}
}
/* Update clientState */
if ( ( resp.clientState === chilliController.stateCodes.NOT_AUTH
( resp.clientState === chilliController.stateCodes.AUTH
) ||
) ||
chilliController.clientState = resp.clientState ;
}
else {
chilliController.onError("Unknown clientState found in JSON reply");
}
if ( !chilliController.autorefreshTimer ) {
85
chilliController.autorefreshTimer
setInterval
('chilliController.refresh()'
1000*chilliController.interval);
}
}
else if ( chilliController.clientState === chilliController.stateCodes.NOT_AUTH ) {
clearInterval ( chilliController.autorefreshTimer ) ;
chilliController.autorefreshTimer = 0 ;
}
('chilliController.processReply:
Calling
onUpdate.
clienState
chilliController.clientState);
chilliController.onUpdate( chilliController.command );
};
/**
* chilliJSON object
*
* This private objet implements the cross domain hack
* If no answer is received before timeout, then an error is raised.
*
*/
chilliJSON.expired = function () {
if ( chilliJSON.node.text ) {
log ('chilliJSON: reply content \n' + chilliJSON.node.text );
}
else {
'
86
log ('chilliJSON: request timed out (or reply is not valid JS)');
}
clearInterval ( chilliJSON.timer ) ;
chilliJSON.timer = 0 ;
clearInterval ( chilliJSON.timer ) ;
chilliJSON.timer = 0 ;
if ( chilliJSON.timestamp ) {
log ( 'chilliJSON: JSON reply received in ' + ( end - chilliJSON.timestamp ) + ' ms\n'
+ dumpObject(raw) );
}
87
chilliJSON.node = 0;
chilliJSON.onJSONReady( raw ) ;
};
if ( typeof(gUrl) == "string" ) {
chilliJSON.url = gUrl ;
}
else {
log ( "chilliJSON:error:Incorrect url passed to chilliJSON.get():" + gUrl );
chilliJSON.onError ( "Incorrect url passed to chilliJSON.get() " );
return ;
}
if ( chilliJSON.timer ) {
log('logon:
request.');
return ;
}
var c ;
if ( this.url.indexOf('?') === -1 ) {
c = '?' ;
}
else {
88
c = '&' ;
}
/* Adding the node that will trigger the HTTP request to the DOM tree */
chilliJSON.node
document.getElementsByTagName('head')[0].appendChild(scriptElement);
= new Date();
chilliJSON.timestamp = now.getTime() ;
log ('chilliJSON: getting ' + chilliJSON.url + ' . Waiting for reply ...');
/**
* chilliClock object
*
* Can be used by BBSMs to display a count down.
*
* Will sync with chilliController and modulate the delay to call onTick
* This will avoid ugly sequence of short updates in the IO
* (not yet implemented)
*
*/
89
chilliClock.onTick = function () {
log ("You should define your own onTick() handler on this clock object. Clock value
= " + this.value );
};
chilliClock.increment = function () {
chilliClock.value = chilliClock.value + 1 ;
chilliClock.onTick( chilliClock.value ) ;
};
= parseInt( newval , 10 ) ;
chilliClock.stop = function () {
clearInterval ( chilliClock.isStarted ) ;
chilliClock.isStarted = 0 ;
};
90
function getel(e) {
if (document.getElementById) {
return document.getElementById(e);
} else if (document.all){
return document.all[e];
}
}
if ( getel('debugarea') ) {
var e = getel('debugarea') ;
e.value = e.value + '\n' + msg;
e.scrollTop = e.scrollHeight - e.clientHeight;
}
}
91
}
}
}
return str;
}
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*
* added by Y.DELTROO
* - new functions: chap(), hex2binl() and str2hex()
* - modifications to comply with the jslint test, http://www.jslint.com/
*
* Copyright (c) 2007
* Distributed under the BSD License
*
*/
function ChilliMD5() {
*/
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode
*/
92
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
93
var oldb = b;
var oldc = c;
var oldd = d;
94
95
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [ a, b, c, d ];
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
96
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = [] ;
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
97
var val ;
for ( var i=0 ; i<str.length ; i++) {
/* TODO: adapt this if chrz=16 */
val = str.charCodeAt(i);
hex = hex + hex_tab.charAt( val/16 );
hex = hex + hex_tab.charAt( val%16 );
}
return hex;
}
<html>
<head>
<!--
98
A purely HTML based captive portal using the JSON interface of CoovaChilli
-->
<title>coova hotspot</title>
<style><!-body,td,a,p,h{
font-family:arial,sans-serif;
}
body {
text-align: center;
padding-top: 30px;
margin: auto;
width: 50%;
}
#MyChilli {
background: url("/images/coova.jpg") right top no-repeat;
margin: auto;
text-align: left;
padding: 10px 0 30px 0;
}
#locationName {
height: 50px;
font-size: 120%;
font-weight: bold;
}
#chilliPage {
border: 1px solid orange;
padding: 20px 20px 20px 20px;
margin-top: 20px;
}
#signUpRow {
display: inline;
}
-->
99
</style>
</head>
<body>
<div id="MyChilli">
<div id="noLocation" style="display:none;">
<p style="padding-top: 100px;"><strong>You are not at a hotspot.</strong> If you
want to see a a sample login page using the <a href="http://www.coova.org/Coova
Chilli/JSON">JSON
interface</a>
href="http://www.coova.org/CoovaChilli">CoovaChilli</a>,
of
then
<a
<a
href="javascript:
*
*
*
- chilliJSON
100
tag to the HTML DOM (this hack enables cross server requests).
*
*
- chilliClock
implemented)
*
*
- chilliLibrary
*
* For more information http://www.coova.org/CoovaChilli/JSON
*
* TODO :
* - Fine tune level of debug messages
* - Define error code when invoking onError
* - Retry mechanism after a JSON request fails
* - Delay clock tick when there is already an ongoing request
* - Use a true JSON parser to validate what we received
* - Use idleTime and idleTimeout to re-schedule autofresh after
*
*
* Copyright (C) Y.Deltroo 2007
* Distributed under the BSD License
*
* This file also contains third party code :
* - MD5, distributed under the BSD license
*
http://pajhome.org.uk/crypt/md5
*
*/
101
/**
* Global chilliController object
*
* CONFIGUARION PROPERTIES
* ----------------------*
*
ident (String)
Hex encoded string (used for client side CHAP-Password calculations)
*
*
*
interval (Number)
Poll the gateway every interval, in seconds
*
*
*
host (String)
IP address of the controller (String)
*
*
*
port (Number)
UAM port to direct request to on the gateway
*
*
*
ssl (Boolean)
Shall we use HTTP or HTTPS to communicate with the chilli controller
*
*
*
*
uamService : String
!!! EXPERIMENTAL FEATURE !!!
URL to external uamService script (used for external MD5 calculation when
This remote script runs on a SSL enable web server, and knows UAM
SECRET.
*
The chilliController javascript object will send the password over SSL (and
*
* For more information http://www.coova.org/CoovaChilli/JSON
102
*
*/
if (!chilliController || !chilliController.host)
var chilliController = { interval:30 , host:"10.1.0.1" , port:3990 , ident:'00' , ssl:false ,
uamService: };
= {} ;
chilliController.accounting = {} ;
chilliController.redir
= {} ;
= '' ;
chilliController.message
= '' ;
chilliController.clientState
= chilliController.stateCodes.UNKNOWN ;
chilliController.command
= '' ;
chilliController.autorefreshTimer = 0 ;
103
log('>> Default onUpdate handler. <<\n>> You should write your own. <<\n>>
cmd = ' + cmd + ' <<' );
};
if ( typeof(t) == 'undefined' ) {
return "Not available";
}
t = parseInt ( t , 10 ) ;
if ( (typeof (zeroReturn) !='undefined') && ( t === 0 ) ) {
return zeroReturn;
}
104
if
};
if ( typeof(b) == 'undefined' ) {
b = 0;
} else {
b = parseInt ( b , 10 ) ;
}
105
/**
* Global chilliController object
*
* PUBLIC METHODS
* -------------*
*
*
*
*
logoff () :
*
*
refresh () :
*
*/
106
log ( 'chilliController.logon( "' + username + '" , "' + password + ' " )' );
= chilliController.onError
chilliJSON.onJSONReady = chilliController.logonStep2 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
chilliJSON.get( chilliController.urlRoot() + 'status' ) ;
};
log ( 'chilliController.logon2( "' + username + '" , "' + response + ' " )' );
= chilliController.onError
chilliJSON.onJSONReady = chilliController.logonStep2 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
chilliJSON.get( chilliController.urlRoot() + 'status' ) ;
};
107
/**
* Second part of the logon process invoked after
* the just requested challenge has been received
*/
chilliController.logonStep2 = function ( resp ) {
108
var c ;
if ( chilliController.uamService.indexOf('?') === -1 ) {
c = '?' ;
}
else {
c = '&' ;
}
= chilliController.uamService + c
+ 'username=' +
= chilliController.onError
chilliJSON.onJSONReady = chilliController.logonStep3 ;
chilliController.clientState = chilliController.AUTH_PENDING ;
chilliJSON.get( url ) ;
}
else {
/* TODO: Should check if challenge has expired and possibly get a new
one */
/*
*/
109
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliController.clientState
chilliController.stateCodes.AUTH_PENDING ;
};
/**
* Third part of the logon process invoked after
* getting a uamService response
*/
chilliController.logonStep3 = function ( resp ) {
log('Entering logonStep 3');
110
chilliJSON.onError
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliController.clientState
chilliController.stateCodes.AUTH_PENDING ;
chilliController.refresh = function ( ) {
if ( chilliController.autorefreshTimer ) {
chilliController.command = 'autorefresh' ;
}
else {
chilliController.command = 'refresh' ;
}
chilliJSON.onError
= chilliController.onError
chilliJSON.onJSONReady = chilliController.processReply ;
chilliJSON.get( chilliController.urlRoot() + 'status' ) ;
};
chilliController.logoff = function () {
chilliController.command = 'logoff'
chilliJSON.onError
= chilliController.onError
111
chilliJSON.onJSONReady = chilliController.processReply ;
chilliJSON.get( chilliController.urlRoot() + 'logoff' );
};
/* *
*
* This functions does some check/type processing on the JSON resp
* and updates the corresponding chilliController members
*
*/
chilliController.processReply = function ( resp ) {
112
chilliController.accounting = resp.accounting ;
}
/* Update the session member only the first time after AUTH */
if ( (typeof ( resp.session ) == 'object') &&
( chilliController.session==null || (
( chilliController.clientState !== chilliController.stateCodes.AUTH
&&
( resp.clientState === chilliController.stateCodes.AUTH )))) {
chilliController.session = resp.session ;
if ( resp.session.startTime ) {
chilliController.session.startTime = new Date();
chilliController.session.startTime.setTime(resp.session.startTime);
}
}
/* Update clientState */
if ( ( resp.clientState === chilliController.stateCodes.NOT_AUTH
( resp.clientState === chilliController.stateCodes.AUTH
) ||
) ||
chilliController.clientState = resp.clientState ;
}
else {
chilliController.onError("Unknown clientState found in JSON reply");
113
if ( !chilliController.autorefreshTimer ) {
chilliController.autorefreshTimer
setInterval
('chilliController.refresh()' , 1000*chilliController.interval);
}
}
else
if
chilliController.clientState
===
chilliController.stateCodes.NOT_AUTH ) {
clearInterval ( chilliController.autorefreshTimer ) ;
chilliController.autorefreshTimer = 0 ;
}
/**
* chilliJSON object
*
* This private objet implements the cross domain hack
* If no answer is received before timeout, then an error is raised.
*
*/
114
chilliJSON.expired = function () {
if ( chilliJSON.node.text ) {
log ('chilliJSON: reply content \n' + chilliJSON.node.text );
}
else {
log ('chilliJSON: request timed out (or reply is not valid JS)');
}
clearInterval ( chilliJSON.timer ) ;
chilliJSON.timer = 0 ;
clearInterval ( chilliJSON.timer ) ;
chilliJSON.timer = 0 ;
115
if ( chilliJSON.timestamp ) {
log ( 'chilliJSON: JSON reply received in ' + ( end chilliJSON.timestamp ) + ' ms\n' + dumpObject(raw) );
}
chilliJSON.node );
}
chilliJSON.node = 0;
chilliJSON.onJSONReady( raw ) ;
};
if ( typeof(gUrl) == "string" ) {
chilliJSON.url = gUrl ;
}
else {
log ( "chilliJSON:error:Incorrect url passed to chilliJSON.get():"
+ gUrl );
chilliJSON.onError ( "Incorrect url passed to chilliJSON.get() "
);
return ;
}
if ( chilliJSON.timer ) {
log('logon: There is already a request running. Return without
launching a new request.');
116
return ;
}
var c ;
if ( this.url.indexOf('?') === -1 ) {
c = '?' ;
}
else {
c = '&' ;
}
/* Adding the node that will trigger the HTTP request to the DOM tree
*/
chilliJSON.node
document.getElementsByTagName('head')[0].appendChild(scriptElement);
= setInterval ( 'chilliJSON.expired()' ,
chilliJSON.timeout ) ;
var now
= new Date();
chilliJSON.timestamp = now.getTime() ;
log ('chilliJSON: getting ' + chilliJSON.url + ' . Waiting for reply ...');
117
/**
* chilliClock object
*
* Can be used by BBSMs to display a count down.
*
* Will sync with chilliController and modulate the delay to call onTick
* This will avoid ugly sequence of short updates in the IO
* (not yet implemented)
*
*/
chilliClock.onTick = function () {
log ("You should define your own onTick() handler on this clock object. Clock
value = " + this.value );
};
chilliClock.increment = function () {
chilliClock.value = chilliClock.value + 1 ;
chilliClock.onTick( chilliClock.value ) ;
};
= parseInt( newval , 10 ) ;
118
chilliClock.stop = function () {
clearInterval ( chilliClock.isStarted ) ;
chilliClock.isStarted = 0 ;
};
function getel(e) {
if (document.getElementById) {
return document.getElementById(e);
} else if (document.all){
return document.all[e];
}
}
119
if ( getel('debugarea') ) {
var e = getel('debugarea') ;
e.value = e.value + '\n' + msg;
e.scrollTop = e.scrollHeight - e.clientHeight;
}
}
}
}
}
return str;
}
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*
* added by Y.DELTROO
120
function ChilliMD5() {
*/
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode
*/
121
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
122
123
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [ a, b, c, d ];
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
124
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = [] ;
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
125
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
hex_tab
hexcase
"0123456789ABCDEF"
"0123456789abcdef";
var hex = '';
var val ;
for ( var i=0 ; i<str.length ; i++) {
/* TODO: adapt this if chrz=16 */
val = str.charCodeAt(i);
hex = hex + hex_tab.charAt( val/16 );
hex = hex + hex_tab.charAt( val%16 );
}
return hex;
}
126
#!/usr/bin/perl
# This code is horrible -- it came that way, and remains that way. A
# real captive portal is demonstrated here: http://drupal.org/project/hotspot
127
# Uncomment the following line if you want to use ordinary user-password (PAP)
# for radius authentication.
# $userpassword=1;
$loginpath = "/cgi-bin/hotspotlogin.cgi";
$debug = 1;
# start program
128
$_ = $query=$ENV{QUERY_STRING};
s/[^$OK_CHARS]/_/go;
$query = $_;
# If she did not use https tell her that it was wrong.
if (!$debug && !($ENV{HTTPS} =~ /^on$/)) {
print "Content-type: text/html\n\n
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>CoovaChilli Login Failed</title>
<meta http-equiv=\"Cache-control\" content=\"no-cache\">
<meta http-equiv=\"Pragma\" content=\"no-cache\">
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>
<center>
Login must use encrypted connection.
</center>
</body>
<!-<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<WISPAccessGatewayParam
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:noNamespaceSchemaLocation=\"http://www.acmewisp.com/WISPAccessGatewayParam.
xsd\">
<AuthenticationReply>
<MessageType>120</MessageType>
<ResponseCode>102</ResponseCode>
<ReplyMessage>Login must use encrypted connection</ReplyMessage>
</AuthenticationReply>
129
</WISPAccessGatewayParam>
-->
</html>
";
exit(0);
}
130
{ $res = $array2[1]; }
{ $uamip = $array2[1]; }
{ $reply = $array2[1]; }
$userurldecode = $userurl;
$userurldecode =~ s/\+/ /g;
$userurldecode =~s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/seg;
$redirurldecode = $redirurl;
$redirurldecode =~ s/\+/ /g;
$redirurldecode =~s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/seg;
# If attempt to login
131
if (defined $uamsecret) {
$newchal = md5($hexchal, $uamsecret);
}
else {
$newchal = $hexchal;
}
if ($ntresponse == 1) {
# Encode plain text into NT-Password
$logonUrl
"http://$uamip:$uamport/logon?username=$username&ntresponse=$response";
} elsif ($userpassword == 1) {
# Encode plain text password with challenge
# (which may or may not be uamsecret encoded)
$pappassword
unpack
"H*",
substr($password
$newchal,
0,
length($password));
$logonUrl
"http://$uamip:$uamport/logon?username=$username&password=$pappassword";
} else {
132
$logonUrl
"http://$uamip:$uamport/logon?username=$username&response=$response&userurl=$userur
l";
}
#sleep 5;
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>CoovaChilli Login</title>
<meta http-equiv=\"Cache-control\" content=\"no-cache\">
<meta http-equiv=\"Pragma\" content=\"no-cache\">
<meta http-equiv=\"refresh\" content=\"0;url=$logonUrl\">
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">Logging in to CoovaChilli</h1>
<center>
Please wait......
</center>
</body>
<!-<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<WISPAccessGatewayParam
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:noNamespaceSchemaLocation=\"http://www.acmewisp.com/WISPAccessGatewayParam.
xsd\">
<AuthenticationReply>
133
<MessageType>120</MessageType>
<ResponseCode>201</ResponseCode>
<LoginResultsURL>$logonUrl</LoginResultsURL>
</AuthenticationReply>
</WISPAccessGatewayParam>
-->
</html>
";
exit(0);
}
# If login successful
if ($res =~ /^success$/) {
$result = 1;
}
# If login failed
if ($res =~ /^failed$/) {
$result = 2;
}
# If logout successful
if ($res =~ /^logoff$/) {
$result = 3;
}
134
135
<html>
<head>
<title>CoovaChilli Login Failed</title>
<meta http-equiv=\"Cache-control\" content=\"no-cache\">
<meta http-equiv=\"Pragma\" content=\"no-cache\">
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>
<center>
Login must be performed through CoovaChilli daemon.
</center>
</body>
</html>
";
exit(0);
}
function doTime() {
136
function popUp(URL) {
if (self.name != \"chillispot_popup\") {
137
chillispot_popup
window.open(URL,
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=375
');
}
}
window.open(URL,
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=375
');
}
if ((result == 2) || result == 5) {
document.form1.UserName.focus()
}
if ((result == 2) && (self.name != \"chillispot_popup\")) {
chillispot_popup
window.open('',
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=200
');
chillispot_popup.close();
}
if ((result == 12) && (self.name == \"chillispot_popup\")) {
doTime();
if (redirurl) {
opener.location = redirurl;
}
else if (opener.home) {
138
opener.home();
}
else {
opener.location = \"about:home\";
}
self.focus();
blur = 0;
}
if ((result == 13) && (self.name == \"chillispot_popup\")) {
self.focus();
blur = 1;
}
}
function doOnBlur(result) {
if ((result == 12) && (self.name == \"chillispot_popup\")) {
if (blur == 0) {
blur = 1;
self.focus();
}
}
}
</script>
</head>
<body
onLoad=\"javascript:doOnLoad($result,
'$loginpath?res=popup2&uamip=$uamip&uamport=$uamport&userurl=$userurl&redirurl=$r
edirurl&timeleft=$timeleft','$userurldecode',
'$redirurldecode',
if (!window.opener) {
#
#
document.bgColor = '#c0d8f4';
}
'$timeleft')\"
onBlur
139
#}
if ($result == 2) {
print "
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>";
if ($reply) {
print "<center> $reply </BR></BR></center>";
}
}
if ($result == 5) {
print "
<h1 style=\"text-align: center;\">CoovaChilli Login</h1>";
}
if ($result == 2 || $result == 5) {
print "
<form name=\"form1\" method=\"post\" action=\"$loginpath\">
<INPUT TYPE=\"hidden\" NAME=\"challenge\" VALUE=\"$challenge\">
<INPUT TYPE=\"hidden\" NAME=\"uamip\" VALUE=\"$uamip\">
<INPUT TYPE=\"hidden\" NAME=\"uamport\" VALUE=\"$uamport\">
<INPUT TYPE=\"hidden\" NAME=\"userurl\" VALUE=\"$userurl\">
<center>
<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width: 217px;\">
<tbody>
<tr>
<td align=\"right\">Username:</td>
<td><input STYLE=\"font-family: Arial\" type=\"text\" name=\"UserName\"
size=\"20\" maxlength=\"128\"></td>
140
</tr>
<tr>
<td align=\"right\">Password:</td>
<td><input STYLE=\"font-family: Arial\" type=\"password\" name=\"Password\"
size=\"20\" maxlength=\"128\"></td>
</tr>
<tr>
<td
align=\"center\"
colspan=\"2\"
height=\"23\"><input
name=\"button\"
type=\"submit\"
value=\"Login\"
onClick=\"javascript:popUp('$loginpath?res=popup1&uamip=$uamip&uamport=$uamport')\
"></td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>";
}
if ($result == 1) {
print "
<h1 style=\"text-align: center;\">Logged in to CoovaChilli</h1>";
if ($reply) {
print "<center> $reply </BR></BR></center>";
}
print "
<center>
<a href=\"http://$uamip:$uamport/logoff\">Logout</a>
</center>
</body>
141
</html>";
}
if ($result == 11) {
print "<h1 style=\"text-align: center;\">Logging in to CoovaChilli</h1>";
print "
<center>
Please wait......
</center>
</body>
</html>";
}
142
exit(0);
Anexo 6 Arquivo de configurao wwwsh
#!/usr/bin/perl
# This code is horrible -- it came that way, and remains that way. A
# real captive portal is demonstrated here: http://drupal.org/project/hotspot
143
# Uncomment the following line if you want to use ordinary user-password (PAP)
# for radius authentication.
# $userpassword=1;
$loginpath = "/cgi-bin/hotspotlogin.cgi";
$debug = 1;
# start program
144
# If she did not use https tell her that it was wrong.
if (!$debug && !($ENV{HTTPS} =~ /^on$/)) {
print "Content-type: text/html\n\n
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>CoovaChilli Login Failed</title>
<meta http-equiv=\"Cache-control\" content=\"no-cache\">
<meta http-equiv=\"Pragma\" content=\"no-cache\">
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>
<center>
Login must use encrypted connection.
</center>
</body>
<!-<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<WISPAccessGatewayParam
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:noNamespaceSchemaLocation=\"http://www.acmewisp.com/WISPAccessGatewayParam.
xsd\">
<AuthenticationReply>
<MessageType>120</MessageType>
<ResponseCode>102</ResponseCode>
<ReplyMessage>Login must use encrypted connection</ReplyMessage>
</AuthenticationReply>
</WISPAccessGatewayParam>
-->
</html>
";
exit(0);
145
{ $res = $array2[1]; }
{ $uamip = $array2[1]; }
146
if ($array2[0] =~ /^reply$/)
{ $reply = $array2[1]; }
$userurldecode = $userurl;
$userurldecode =~ s/\+/ /g;
$userurldecode =~s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/seg;
$redirurldecode = $redirurl;
$redirurldecode =~ s/\+/ /g;
$redirurldecode =~s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/seg;
# If attempt to login
if (defined $uamsecret) {
$newchal = md5($hexchal, $uamsecret);
}
else {
147
$newchal = $hexchal;
}
if ($ntresponse == 1) {
# Encode plain text into NT-Password
$logonUrl
"http://$uamip:$uamport/logon?username=$username&ntresponse=$response";
} elsif ($userpassword == 1) {
# Encode plain text password with challenge
# (which may or may not be uamsecret encoded)
$pappassword
unpack
"H*",
substr($password
$newchal,
0,
length($password));
$logonUrl
"http://$uamip:$uamport/logon?username=$username&password=$pappassword";
} else {
# Generate a CHAP response with the password and the
# challenge (which may have been uamsecret encoded)
148
$logonUrl
"http://$uamip:$uamport/logon?username=$username&response=$response&userurl=$userur
l";
}
#sleep 5;
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>CoovaChilli Login</title>
<meta http-equiv=\"Cache-control\" content=\"no-cache\">
<meta http-equiv=\"Pragma\" content=\"no-cache\">
<meta http-equiv=\"refresh\" content=\"0;url=$logonUrl\">
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">Logging in to CoovaChilli</h1>
<center>
Please wait......
</center>
</body>
<!-<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<WISPAccessGatewayParam
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:noNamespaceSchemaLocation=\"http://www.acmewisp.com/WISPAccessGatewayParam.
xsd\">
<AuthenticationReply>
<MessageType>120</MessageType>
<ResponseCode>201</ResponseCode>
<LoginResultsURL>$logonUrl</LoginResultsURL>
</AuthenticationReply>
</WISPAccessGatewayParam>
149
-->
</html>
";
exit(0);
}
# If login successful
if ($res =~ /^success$/) {
$result = 1;
}
# If login failed
if ($res =~ /^failed$/) {
$result = 2;
}
# If logout successful
if ($res =~ /^logoff$/) {
$result = 3;
}
150
151
</head>
<body bgColor = '#c0d8f4'>
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>
<center>
Login must be performed through CoovaChilli daemon.
</center>
</body>
</html>
";
exit(0);
}
function doTime() {
window.setTimeout( \"doTime()\", 1000 );
t = new Date();
time = Math.round((t.getTime() - starttime.getTime())/1000);
if (mytimeleft) {
time = mytimeleft - time;
152
if (time <= 0) {
window.location
\"$loginpath?res=popup3&uamip=$uamip&uamport=$uamport\";
}
}
if (time < 0) time = 0;
hours = (time - (time % 3600)) / 3600;
time = time - (hours * 3600);
mins = (time - (time % 60)) / 60;
secs = time - (mins * 60);
if (hours < 10) hours = \"0\" + hours;
if (mins < 10) mins = \"0\" + mins;
if (secs < 10) secs = \"0\" + secs;
title = \"Online time: \" + hours + \":\" + mins + \":\" + secs;
if (mytimeleft) {
title = \"Remaining time: \" + hours + \":\" + mins + \":\" + secs;
}
if(document.all || document.getElementById){
document.title = title;
}
else {
self.status = title;
}
}
function popUp(URL) {
if (self.name != \"chillispot_popup\") {
chillispot_popup
window.open(URL,
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=375
');
}
}
153
window.open(URL,
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=375
');
}
if ((result == 2) || result == 5) {
document.form1.UserName.focus()
}
if ((result == 2) && (self.name != \"chillispot_popup\")) {
chillispot_popup
window.open('',
'chillispot_popup',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=200
');
chillispot_popup.close();
}
if ((result == 12) && (self.name == \"chillispot_popup\")) {
doTime();
if (redirurl) {
opener.location = redirurl;
}
else if (opener.home) {
opener.home();
}
else {
opener.location = \"about:home\";
}
self.focus();
154
blur = 0;
}
if ((result == 13) && (self.name == \"chillispot_popup\")) {
self.focus();
blur = 1;
}
}
function doOnBlur(result) {
if ((result == 12) && (self.name == \"chillispot_popup\")) {
if (blur == 0) {
blur = 1;
self.focus();
}
}
}
</script>
</head>
<body
onLoad=\"javascript:doOnLoad($result,
'$loginpath?res=popup2&uamip=$uamip&uamport=$uamport&userurl=$userurl&redirurl=$r
edirurl&timeleft=$timeleft','$userurldecode',
'$redirurldecode',
if (!window.opener) {
#
#
document.bgColor = '#c0d8f4';
}
'$timeleft')\"
onBlur
155
if ($result == 2) {
print "
<h1 style=\"text-align: center;\">CoovaChilli Login Failed</h1>";
if ($reply) {
print "<center> $reply </BR></BR></center>";
}
}
if ($result == 5) {
print "
<h1 style=\"text-align: center;\">CoovaChilli Login</h1>";
}
if ($result == 2 || $result == 5) {
print "
<form name=\"form1\" method=\"post\" action=\"$loginpath\">
<INPUT TYPE=\"hidden\" NAME=\"challenge\" VALUE=\"$challenge\">
<INPUT TYPE=\"hidden\" NAME=\"uamip\" VALUE=\"$uamip\">
<INPUT TYPE=\"hidden\" NAME=\"uamport\" VALUE=\"$uamport\">
<INPUT TYPE=\"hidden\" NAME=\"userurl\" VALUE=\"$userurl\">
<center>
<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width: 217px;\">
<tbody>
<tr>
<td align=\"right\">Username:</td>
<td><input STYLE=\"font-family: Arial\" type=\"text\" name=\"UserName\"
size=\"20\" maxlength=\"128\"></td>
</tr>
<tr>
<td align=\"right\">Password:</td>
<td><input STYLE=\"font-family: Arial\" type=\"password\" name=\"Password\"
size=\"20\" maxlength=\"128\"></td>
</tr>
156
<tr>
<td
align=\"center\"
colspan=\"2\"
height=\"23\"><input
name=\"button\"
type=\"submit\"
value=\"Login\"
onClick=\"javascript:popUp('$loginpath?res=popup1&uamip=$uamip&uamport=$uamport')\
"></td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>";
}
if ($result == 1) {
print "
<h1 style=\"text-align: center;\">Logged in to CoovaChilli</h1>";
if ($reply) {
print "<center> $reply </BR></BR></center>";
}
print "
<center>
<a href=\"http://$uamip:$uamport/logoff\">Logout</a>
</center>
</body>
</html>";
}
157
<center>
<a href=\"http://$uamip:$uamport/logoff\">Logout</a>
</center>
</body>
</html>";
}
if ($result == 11) {
print "<h1 style=\"text-align: center;\">Logging in to CoovaChilli</h1>";
print "
<center>
Please wait......
</center>
</body>
</html>";
}
if (($result == 3) || ($result == 13)) {
print "
<h1 style=\"text-align: center;\">Logged out from CoovaChilli</h1>
<center>
<a href=\"http://$uamip:$uamport/prelogin\">Login</a>
</center>
</body>
</html>";
}
exit(0);
Anexo 7 Arquivo de Configurao up.sh
#!/bin/sh
TUNTAP=$(basename $DEV)
158
UNDO_FILE=/var/run/chilli.$TUNTAP.sh
. /etc/chilli/functions
ipt() {
opt=$1; shift
echo "iptables -D $*" >> $UNDO_FILE
iptables $opt $*
}
ipt_in() {
ipt -I INPUT -i $TUNTAP $*
}
if [ -n "$TUNTAP" ]
then
# ifconfig $TUNTAP mtu $MTU
if [ "$KNAME" != "" ]
then
ipt -I FORWARD -i $DHCPIF -m coova --name $KNAME -j ACCEPT
ipt -I FORWARD -o $DHCPIF -m coova --name $KNAME --dest -j ACCEPT
ipt -I FORWARD -i $TUNTAP -j ACCEPT
ipt -I FORWARD -o $TUNTAP -j ACCEPT
[ -n "$DHCPLISTEN" ] && ifconfig $DHCPIF $DHCPLISTEN
else
if [ "$LAYER3" != "1" ]
then
[ -n "$UAMPORT" -a "$UAMPORT" != "0" ] && \
ipt_in -p tcp -m tcp --dport $UAMPORT --dst $ADDR -j ACCEPT
159
[ -n "$HS_TCP_PORTS" ] && {
for port in $HS_TCP_PORTS; do
ipt_in -p tcp -m tcp --dport $port --dst $ADDR -j ACCEPT
done
}
if [ "$ONLY8021Q" != "1" ]
then
ipt -I INPUT -i $DHCPIF -j DROP
fi
fi
if [ "$ONLY8021Q" != "1" ]
then
ipt -I FORWARD -i $DHCPIF -j DROP
ipt -I FORWARD -o $DHCPIF -j DROP
fi
160