Post em Destaque

Gravar a Área de Trabalho

  Olá Este é um post simples, mas com uma dica bem útil para quem gosta de fazer tutoriais ou que, por qualquer outro motivo, deseje gravar a área de trabalho enquanto utiliza o seu sistema FreeBSD (deve funcionar com outros unix-like também). Para capturar a área de trabalho não é necessário...

Leia mais...

BSD Magazine – Mês de Novembro.

Posted by gondim | Posted in Dicas, FreeBSD, Segurança, Software Livre, Tecnologia | Posted on 07-11-2012

Tags:, ,

0

BSD Magazine é uma revista mensal de excelente qualidade técnica, visual e gratuita para todo e qualquer profissional que queira ficar bem informado sobre tecnologia e informação utilizando BSD e outros Softwares Livres.

A revista encontra-se em idioma Inglês e para baixá-la basta informar o seu e-mail e clicar para baixar. Todas as outras edições anteriores também podem ser baixadas. Seu formato está em pdf.

Conteúdo:

  • NETGEAR Universal Wifi Adapter (WNCE2001)
  • Automating the Deployment of FreeBSD & PC-BSD Systems
  • Network Concepts, Routing and Firewalls
  • FreeBSD as a NAT Instance in Amazon Cloud
  • FreeBSD Enterprise Search with Apache Solr
  • PostgreSQL: Indexes

 

Bsd_11_2012_

Share Button

BSD Magazine – Mês de Outubro

Posted by gondim | Posted in Dicas, FreeBSD, Segurança, Software Livre, Tecnologia | Posted on 14-10-2012

Tags:,

0

BSD Magazine é uma revista mensal de excelente qualidade técnica, visual e gratuita para todo e qualquer profissional que queira ficar bem informado sobre tecnologia e informação utilizando BSD e outros Softwares Livres.

A revista encontra-se em idioma Inglês e para baixá-la basta informar o seu e-mail e clicar para baixar. Todas as outras edições anteriores também podem ser baixadas. Seu formato está em pdf.

Conteúdo:

  • VX ConnectBot: Open Source SSH Client for Android Devices
  • Installing Xfce Desktop Environment on OpenBSD 5.1
  • Browse the Internet Differently
  • FreeBSD Enterprise Search with Apache Solr (Part 2)
  • PostgreSQL: Indexes
  • Unix IPC with FIFOs
  • Capture Session Data with Argus on FreeBSD
  • Securing your Family with pfSense and IPSec
  • Installation and Setup of the Halon Virtual Security Router

Bsd_10_2012_cover

Share Button

Jail com VIMAGE carregando automaticamente no boot.

Posted by gondim | Posted in FreeBSD, Segurança, Software Livre, Tecnologia | Posted on 09-08-2012

Tags:, ,

0

Pois é pessoal, depois de penar um pouco com jails aqui em meu ambiente de testes consegui fazer uma configuração bem legal usando o VIMAGE. O que matava usando o vimage era que a jail não carregava os serviços e configurações automaticamente no boot porque o script /etc/rc.d/jail não tem ainda um suporte oficial para vnet. Mas futucando na Internet achei um patch para isso e que funciona tanto no FreeBSD 8 quanto no FreeBSD 9. Bem eu testei no FreeBSD 9-PRERELEASE. Abaixo vou dar um exemplo de como fazer essa configuração:

Primeiro você precisa compilar o seu kernel com suporte ao VIMAGE. Adicione a seguinte linha ao seu kernel, compile e instale ele:

options VIMAGE

Vamos agora baixar e aplicar o patch para o /etc/rc.d/jail de acordo com o seu FreeBSD:

# cd /etc/rc.d
# patch < (local_onde_baixou_patch)/jail_rc9.patch

Após aplicar o patch o seu script /etc/rc.d/jail terá suporte ao vnet que precisamos e assim carregar automaticamente nossas jails no /etc/rc.conf.

Depois de iniciar com o seu novo kernel, vamos montar a estrutura de uma nova jail para vermos como isso vai funcionar. Darei o nome da minha jail de “mail”. Vamos dizer que eu quisesse montar um servidor de correio nessa jail.

# mkdir -p /usr/jail/mail

Para cada nova jail a estrutura estaria dentro de /usr/jail. Se você já compilou e instalou seu sistema FreeBSD, a coisa fica mais rápida fazendo assim:

# cd /usr/src
# make installworld DESTDIR=/usr/jail/mail
# make distribution DESTDIR=/usr/jail/mail

Agora vamos preparar o ambiente do servidor:

# mkdir -p /etc/jails/fstabs
# echo “/usr/src              /usr/jail/mail/usr/src            nullfs      rw     0     0” > /etc/jails/fstabs/mail
# echo “/usr/ports            /usr/jail/mail/usr/ports          nullfs      rw     0     0” >> /etc/jails/fstabs/mail

No nosso /etc/rc.conf ficará essa configuração:

hostname=”virtsrv.localdomain.net”
keymap=”br275.iso.acc.kbd”
cloned_interfaces=”bridge0 epair0″
ifconfig_bridge0=”inet 192.168.8.34 netmask 255.255.255.0 addm em0 up”
ifconfig_em0=”up”
ifconfig_epair0a=”up”
defaultrouter=”192.168.8.253″
sshd_enable=”YES”
# Set dumpdev to “AUTO” to enable crash dumps, “NO” to disable
dumpdev=”NO”

jail_enable=”YES”
jail_v2_enable=”YES”
jail_list=””
jail_set_hostname_allow=”YES”
jail_socket_unixiproute_only=”YES”
jail_sysvipc_allow=”YES”
jail_list=”$jail_list mail”
jail_mail_name=”mail”
jail_mail_hostname=”mail.teste.com.br”
jail_mail_devfs_enable=”YES”
jail_mail_rootdir=”/usr/jail/mail”
jail_mail_mount_enable=”YES”
jail_mail_fstab=”/etc/jails/fstabs/mail”
jail_mail_vnet_enable=”YES”

jail_mail_exec_prestart0=”mount -t devfs devfs /usr/jail/mail/dev”
jail_mail_exec_prestart1=”ifconfig bridge0 addm epair0a”
jail_mail_exec_earlypoststart0=”ifconfig epair0b vnet mail”
jail_mail_exec_afterstart0=”ifconfig lo0 127.0.0.1″
jail_mail_exec_afterstart1=”ifconfig epair0b 192.168.8.173 netmask 255.255.255.0 up”
jail_mail_exec_afterstart2=”route add default 192.168.8.253″
jail_mail_exec_afterstart3=”/bin/sh /etc/rc”
jail_mail_exec_poststop0=”ifconfig bridge0 deletem epair0a”

Na nossa configuração acima o IP do servidor das jails será o 192.168.8.34 e o IP que estamos dando para a jail será 192.168.8.173. Use os IPs que melhor atender a sua necessidade. 🙂

Antes de iniciar a nossa jail de exemplo precisamos prepará-la para uso:

Adicione as linhas abaixo em /usr/jail/mail/etc/rc.conf:

hostname=”mail.teste.com.br”
network_interfaces=””
sshd_enable=”YES”

Por último vamos criar um fstab fazio:

# touch /usr/jail/mail/etc/fstab
# mkdir /usr/jail/mail/usr/ports

Agora podemos iniciar nossa jail fazendo:

#/etc/rc.d/jail start mail

Após carregar a jail, podemos entrar nela via jexec e configurar o time zone com tzsetup, colocar senha no root e criar novos users para o sistema. Para fazer isso:

# jls
JID  IP Address      Hostname                      Path
–               mail.teste.com.br             /usr/jail/mail

# jexec 1 sh
# passwd root
# tzsetup
# adduser
# exit

Bem é isso aí pessoal.  :

Muitas coisas desse artigo foram baseadas nesse aqui.

 

Share Button

Bind9 vulnerabilidade – DNSSEC validation Denial of Service

Posted by gondim | Posted in FreeBSD, Segurança, Software Livre | Posted on 06-08-2012

Tags:

9

Para aqueles que tem um servidor de DNS com bind 9.x dêem uma olhada nesse advisory abaixo
e corrijam o quanto antes o problema:

==========================================================================
FreeBSD-SA-12:05.bind                                       Security Advisory
                                                          The FreeBSD Project

Topic:          named(8) DNSSEC validation Denial of Service

Category:       contrib
Module:         bind
Announced:      2012-08-06
Credits:        Einar Lonn of IIS.se
Affects:        All supported versions of FreeBSD
Corrected:      2012-08-06 21:33:11 UTC (RELENG_7, 7.4-STABLE)
                2012-08-06 21:33:11 UTC (RELENG_7_4, 7.4-RELEASE-p10)
                2012-07-24 19:04:35 UTC (RELENG_8, 8.3-STABLE)
                2012-08-06 21:33:11 UTC (RELENG_8_3, 8.3-RELEASE-p4)
                2012-08-06 21:33:11 UTC (RELENG_8_2, 8.2-RELEASE-p10)
                2012-08-06 21:33:11 UTC (RELENG_8_1, 8.1-RELEASE-p13)
                2012-07-24 22:32:03 UTC (RELENG_9, 9.1-PRERELEASE)
                2012-08-06 21:33:11 UTC (RELENG_9_0, 9.0-RELEASE-p4)
CVE Name:       CVE-2012-3817

For general information regarding FreeBSD Security Advisories,
including descriptions of the fields above, security branches, and the
following sections, please visit <URL:http://security.FreeBSD.org/>.

I.   Background

BIND 9 is an implementation of the Domain Name System (DNS) protocols.
The named(8) daemon is an Internet Domain Name Server.

DNS Security Extensions (DNSSEC) provides data integrity, origin
authentication and authenticated denial of existence to resolvers.

II.  Problem Description

BIND 9 stores a cache of query names that are known to be failing due
to misconfigured name servers or a broken chain of trust.  Under high
query loads, when DNSSEC validation is active, it is possible for a
condition to arise in which data from this cache of failing queries
could be used before it was fully initialized, triggering an assertion
failure.

III. Impact

A remote attacker that is able to generate high volume of DNSSEC
validation enabled queries can trigger the assertion failure that causes
it to crash, resulting in a denial of service.

IV.  Workaround

No workaround is available, but systems not running the BIND resolving
name server with dnssec-validation enabled are not affected.

V.   Solution

Perform one of the following:

1) Upgrade your vulnerable system to 7-STABLE, 8-STABLE, or 9-STABLE,
or to the RELENG_7_4, RELENG_8_3, RELENG_8_2, RELENG_8_1, or RELENG_9_0
security branch dated after the correction date.

2) To update your vulnerable system via a source code patch:

The following patches have been verified to apply to FreeBSD 7.4,
8.3, 8.2, 8.1 and 9.0 systems.

a) Download the relevant patch from the location below, and verify the
detached PGP signature using your PGP utility.

# fetch http://security.FreeBSD.org/patches/SA-12:05/bind.patch
# fetch http://security.FreeBSD.org/patches/SA-12:05/bind.patch.asc

b) Execute the following commands as root:

# cd /usr/src
# patch < /path/to/patch
# cd /usr/src/lib/bind/dns
# make obj && make depend && make && make install
# cd /usr/src/usr.sbin/named
# make obj && make depend && make && make install

3) To update your vulnerable system via a binary patch:

Systems running 7.4-RELEASE, 8.3-RELEASE, 8.2-RELEASE, 8.1-RELEASE,
or 9.0-RELEASE on the i386 or amd64 platforms can be updated via the
freebsd-update(8) utility:

# freebsd-update fetch
# freebsd-update install

4) Install and run BIND from the Ports Collection after the correction
date.  The following versions and newer versions of BIND installed from
the Ports Collection are not affected by this vulnerability:

        bind96-9.6.3.1.ESV.R7.2
        bind97-9.7.6.2
        bind98-9.8.3.2
        bind99-9.9.1.2

VI.  Correction details

The following list contains the revision numbers of each file that was
corrected in FreeBSD.

CVS:

Branch                                                           Revision
  Path
- -------------------------------------------------------------------------
RELENG_7
  src/contrib/bind9/lib/dns/resolver.c                       1.1.1.9.2.11
RELENG_7_4
  src/UPDATING                                            1.507.2.36.2.12
  src/sys/conf/newvers.sh                                  1.72.2.18.2.15
  src/contrib/bind9/lib/dns/resolver.c                    1.1.1.9.2.8.2.1
RELENG_8
  src/contrib/bind9/CHANGES                                      1.9.2.15
  src/contrib/bind9/lib/dns/resolver.c                            1.3.2.6
  src/contrib/bind9/lib/dns/zone.c                               1.6.2.10
  src/contrib/bind9/lib/isc/random.c                              1.2.2.4
  src/contrib/bind9/version                                      1.9.2.15
RELENG_8_3
  src/UPDATING                                             1.632.2.26.2.6
  src/sys/conf/newvers.sh                                   1.83.2.15.2.8
  src/contrib/bind9/lib/dns/resolver.c                        1.6.2.7.2.1
RELENG_8_2
  src/UPDATING                                            1.632.2.19.2.12
  src/sys/conf/newvers.sh                                  1.83.2.12.2.15
  src/contrib/bind9/lib/dns/resolver.c                        1.6.2.4.2.1
RELENG_8_1
  src/UPDATING                                            1.632.2.14.2.16
  src/sys/conf/newvers.sh                                  1.83.2.10.2.17
  src/contrib/bind9/lib/dns/resolver.c                        1.6.2.3.2.1
RELENG_9
  src/contrib/bind9/CHANGES                                      1.21.2.5
  src/contrib/bind9/lib/dns/resolver.c                           1.15.2.3
  src/contrib/bind9/lib/dns/zone.c                                1.7.2.3
  src/contrib/bind9/version                                      1.21.2.5
RELENG_9_0
  src/UPDATING                                              1.702.2.4.2.6
  src/sys/conf/newvers.sh                                    1.95.2.4.2.8
  src/contrib/bind9/lib/dns/resolver.c                           1.15.4.1
- -------------------------------------------------------------------------

Subversion:

Branch/path                                                      Revision
- -------------------------------------------------------------------------
stable/7/                                                         r239108
releng/7.4/                                                       r239108
stable/8/                                                         r238749
releng/8.3/                                                       r239108
releng/8.2/                                                       r239108
releng/8.1/                                                       r239108
stable/9/                                                         r238756
releng/9.0/                                                       r239108
- -------------------------------------------------------------------------

VII. References

https://kb.isc.org/article/AA-00729

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-3817

The latest revision of this advisory is available at
http://security.FreeBSD.org/advisories/FreeBSD-SA-12:05.bind.asc
Share Button

Novo padrão de senha SHA512 no FreeBSD 9.1

Posted by gondim | Posted in FreeBSD, Segurança | Posted on 16-07-2012

Tags:, ,

0

É isso mesmo pessoal, MD5 foi durante muito tempo o padrão de hash para as senhas do sistema. Muitos sistemas ainda usam o MD5 mas agora com a versão 9.1-PRERELEASE e provavelmente a 9.1-RELEASE o padrão passará à ser o SHA512 que é muito mais robusto e seguro que seu antecessor.

Para aqueles que atualizarem o sistema para 9-STABLE, terão essa surpresa ao fazer o mergemaster. Se resolverem usar o padrão novo basta aceitar as modificações no /etc/login.conf e no final gerar o db dele com: cap_mkdb /etc/login.conf

Lembrando que para usar o sistema novo nas senhas, é necessário recriar as senhas usando o passwd. Ex:

# passwd <user>

Estava mais que na hora do MD5 ser aposentado. 😀

Share Button

Tuning – uma coisa muito importante e que faz a diferença

Posted by gondim | Posted in Dicas, FreeBSD, Segurança | Posted on 13-07-2012

Tags:

7

Cada Sistema Operacional tem o seu tuning próprio e isso pode realmente fazer a diferença quando você coloca um servidor em produção. Por si só e sem modificações os sistemas tem seus valores padrões de forma que funcionem em qualquer equipamento mas quando necessitamos que o servidor trabalhe com a melhor performance para aquela aplicação, aí sim você começa à quebrar a cabeça.

O problema é que muitos desses parâmetros são obscuros ou tem pouca informação na Internet e quem poderia nos informar mais sobre eles seriam os desenvolvedores que os criaram. No FreeBSD o tuning é feito em 3 lugares:

  • Kernel
  • loader.conf
  • sysctl.conf

O kernel que é instalado é sempre o GENERIC, um kernel suficiente (mínimo) para que o sistema inicie em qualquer hardware para que se tenha uma menor probabilidade de erros com o equipamento. O resultado é um kernel que tem coisas à mais do que necessitamos e ao mesmo tempo faltando outras que precisamos. Um exemplo disso é o firewall que não vem no kernel GENERIC.

Todos os drivers de dispositivos que você não utiliza, deveriam ser removidos do nosso novo kernel mas nunca edite/altere o arquivo GENERIC. Faça uma cópia do GENERIC para outro nome e aí sim edite esse arquivo novo.

Se você instalou um FreeBSD i386 seu kernel GENERIC estará em: /sys/i386/conf/  e se for um amd64 estará em: /sys/amd64/conf/

O NOTES é um cara que possui todas as opções, devices e parâmetros que podemos usar no nosso kernel mas existem 2 NOTES, o NOTES da sua arquitetura e o NOTES genérico que serviria para qualquer arquitetura. Podemos criar um NOTES completo da seguinte forma. Vamos supor que eu esteja em uma arquitetura de 64 bits (amd64):

# cd /sys/amd64/conf
# cat /sys/conf/NOTES NOTES > NOTES-FULL

Agora sim temos um NOTES com todas as opções que podemos usar e servir de referência.

Um exemplo de tuning de Kernel seria o parâmetro HZ que se você tiver um servidor com alto tráfego, um router por exemplo, deveria ser um valor de uns 3000 em máquinas 64 bits SMP.

Então nosso tuning envolve enxugar o kernel e adicionar coisas que usaremos. Abaixo colocarei alguns exemplos de KERNCONF. No final do artigo colocarei o link no qual coletei essas configurações:

=========================================================================

# Just some of them, see also
# cat /sys/{i386,amd64,}/conf/NOTES

# This one useful only on i386
#options         KVA_PAGES=512

# You can play with HZ in environments with high interrupt rate (default is 1000)
# 100 is for my notebook to prolong it’s battery life
#options         HZ=100

# Eliminate datacopy on socket read-write
# To take advantage with zero copy sockets you should have an MTU >= 4k
# This req. is only for receiving data.
# Read more in man zero_copy_sockets
# Also this epic thread on kernel trap:
#    http://kerneltrap.org/node/6506
# Here Linus says that “anybody that does it that way (FreeBSD) is totally incompetent”
#options         ZERO_COPY_SOCKETS

# Support TCP sign. Used for IPSec
options         TCP_SIGNATURE
# There was stackoverflow found in KAME IPSec stack:
# See http://secunia.com/advisories/43995/
# For quick workaround you can use `ipfw add deny proto ipcomp`
options         IPSEC

# This ones can be loaded as modules. They described in loader.conf section
#options         ACCEPT_FILTER_DATA
#options         ACCEPT_FILTER_HTTP

# Adding ipfw, also can be loaded as modules
options         IPFIREWALL
# On 8.1+ you can disable verbose to see blocked packets on ipfw0 interface.
# Also there is no point in compiling verbose into the kernel, because
# now there is net.inet.ip.fw.verbose tunable.
#options         IPFIREWALL_VERBOSE
#options         IPFIREWALL_VERBOSE_LIMIT=10
options         IPFIREWALL_FORWARD
# Adding kernel NAT
options         IPFIREWALL_NAT
options         LIBALIAS
# Traffic shaping
options         DUMMYNET
# Divert, i.e. for userspace NAT
options         IPDIVERT

# This is for OpenBSD’s pf firewall
device          pf
device          pflog
# pf’s QoS – ALTQ
options         ALTQ
options         ALTQ_CBQ        # Class Bases Queuing (CBQ)
options         ALTQ_RED        # Random Early Detection (RED)
options         ALTQ_RIO        # RED In/Out
options         ALTQ_HFSC       # Hierarchical Packet Scheduler (HFSC)
options         ALTQ_PRIQ       # Priority Queuing (PRIQ)
options         ALTQ_NOPCC      # Required for SMP build

# Pretty console
# Manual can be found here http://forums.freebsd.org/showthread.php?t=6134
#options         VESA
#options         SC_PIXEL_MODE

# Disable reboot on Ctrl Alt Del
#options         SC_DISABLE_REBOOT
# Change normal|kernel messages color
options         SC_NORM_ATTR=(FG_GREEN|BG_BLACK)
options         SC_KERNEL_CONS_ATTR=(FG_YELLOW|BG_BLACK)
# More scroll space
options         SC_HISTORY_SIZE=8192

# Adding hardware crypto device
device          crypto
device          cryptodev

# Useful network interfaces
device          vlan
device          tap                     #Virtual Ethernet driver
device          gre                     #IP over IP tunneling
device          if_bridge               #Bridge interface
device          pfsync                  #synchronization interface for PF
device          carp                    #Common Address Redundancy Protocol
device          enc                     #IPsec interface
device          lagg                    #Link aggregation interface
device          stf                     #IPv4-IPv6 port

# Also for my notebook, but may be used with Opteron
device         amdtemp
# Same for Intel processors
device         coretemp

# man 4 cpuctl
device         cpuctl                   # CPU control pseudo-device

# Support for ECMP. More than one route for destination
# Works even with default route so one can use it as LB for two ISP
# For now code is unstable and panics (panic: rtfree 2) on route deletions.
#options         RADIX_MPATH

# Multicast routing
#options         MROUTING
#options         PIM

# Debug & DTrace
options        KDB                     # Kernel debugger related code
options        KDB_TRACE               # Print a stack trace for a panic
options        KDTRACE_FRAME           # amd64-only(?)
options        KDTRACE_HOOKS           # all architectures – enable general DTrace hooks
#options        DDB
#options        DDB_CTF                 # all architectures – kernel ELF linker loads CTF data

# Adaptive spining in lockmgr (8.x+)
# See http://www.mail-archive.com/svn-src-all@freebsd.org/msg10782.html
options         ADAPTIVE_LOCKMGRS

# UTF-8 in console (8.x+)
#options         TEKEN_UTF8

# FreeBSD 8.1+
# Deadlock resolver thread
# For additional information see http://www.mail-archive.com/svn-src-all@freebsd.org/msg18124.html
# (FYI: “resolution” is panic so use with caution)
#options         DEADLKRES

# Increase maximum size of Raw I/O and sendfile(2) readahead
#options MAXPHYS=(1024*1024)
#options MAXBSIZE=(1024*1024)

# For scheduler debug enable following option.
# Debug will be available via `kern.sched.stats` sysctl
# For more information see http://svnweb.freebsd.org/base/head/sys/conf/NOTES?view=markup
#options SCHED_STATS

# A framework for very efficient packet I/O from userspace, capable of
# line rate at 10G (FreeBSD10+)
# See http://svnweb.freebsd.org/base?view=revision&revision=227614
#device netmap

=========================================================================

Agora veremos uns exemplos relacionados ao /boot/loader.conf:

=========================================================================

# Accept filters for data, http and DNS requests
# Useful when your software uses select() instead of kevent/kqueue or when you under DDoS
# Note: DNS accf available on 8.0+
#accf_data_load=”YES”
#accf_http_load=”YES”
#accf_dns_load=”YES”

# Async IO system calls
aio_load=”YES”

# Linux specific devices in /dev
# As for 8.1 it only /dev/full
#lindev_load=”YES”

# Adds NCQ support in FreeBSD
# WARNING! all ad[0-9]+ devices will be renamed to ada[0-9]+
# 8.0+ only
#ahci_load=”YES”
#siis_load=”YES”

# FreeBSD 9+
# New Congestion Control for FreeBSD
# http://caia.swin.edu.au/urp/newtcp/tools/cc_chd-readme-0.1.txt
# http://www.ietf.org/proceedings/78/slides/iccrg-5.pdf
# Initial merge commit message http://www.mail-archive.com/svn-src-all@freebsd.org/msg31410.html
#cc_chd_load=”YES”

# Increase kernel memory size to 3G.
#
# Use ONLY if you have KVA_PAGES in kernel configuration, and you have more than 3G RAM
# Otherwise panic will happen on next reboot!
#
# It’s required for high buffer sizes: kern.ipc.nmbjumbop, kern.ipc.nmbclusters, etc
# Useful on highload stateful firewalls, proxies or ZFS fileservers
# (FreeBSD 7.2+ amd64 users: Check that current value is lower!)
#vm.kmem_size=”3G”

# If your server has lots of swap (>4Gb) you should increase following value
# according to http://lists.freebsd.org/pipermail/freebsd-hackers/2009-October/029616.html
# Otherwise you’ll be getting errors
# “kernel: swap zone exhausted, increase kern.maxswzone”
#kern.maxswzone=”256M”

# Older versions of FreeBSD can’t tune maxfiles on the fly
#kern.maxfiles=”200000″

# Useful for databases
# Sets maximum data size to 1G
# (FreeBSD 7.2+ amd64 users: Check that current value is lower!)
#kern.maxdsiz=”1G”

# Maximum buffer size(vfs.maxbufspace)
# You can check current one via vfs.bufspace
# Should be lowered/upped depending on server’s load-type
# Usually decreased to preserve kmem
# (default is 10% of mem)
#kern.maxbcache=”512M”

# Sendfile buffers
# For i386 only
#kern.ipc.nsfbufs=10240

# FreeBSD 9+
# HPET “legacy route” support. It should allow HPET to work per-CPU
# See http://www.mail-archive.com/svn-src-head@freebsd.org/msg03603.html
#hint.atrtc.0.clock=0
#hint.attimer.0.clock=0
#hint.hpet.0.legacy_route=1

# syncache Hash table tuning
net.inet.tcp.syncache.hashsize=32768
net.inet.tcp.syncache.bucketlimit=32
net.inet.tcp.syncache.cachelimit=1048576

# Increased hostcache
# Later host cache can be viewed via net.inet.tcp.hostcache.list hidden sysctl
# Very useful for it’s RTT RTTVAR
# Must be power of two
net.inet.tcp.hostcache.hashsize=65536
# hashsize * bucketlimit (which is 30 by default)
# It allocates 255Mb (1966080*136) of RAM
net.inet.tcp.hostcache.cachelimit=1966080

# TCP control-block Hash table tuning
net.inet.tcp.tcbhashsize=4096

# Disable ipfw deny all
# Should be uncommented when there is a chance that
# kernel and ipfw binary may be out-of sync on next reboot
#net.inet.ip.fw.default_to_accept=1

#
# SIFTR (Statistical Information For TCP Research) is a kernel module that
# logs a range of statistics on active TCP connections to a log file.
# See prerelease notes http://groups.google.com/group/mailing.freebsd.current/browse_thread/thread/b4c18be6cdce76e4
# and man 4 sitfr
#siftr_load=”YES”

# Enable superpages, for 7.2+ only
# See: http://lists.freebsd.org/pipermail/freebsd-hackers/2009-November/030094.html
vm.pmap.pg_ps_enabled=1

# Usefull if you are using Intel-Gigabit NIC
#hw.em.rxd=4096
#hw.em.txd=4096
#hw.em.rx_process_limit=”-1″
# Also if you have ALOT interrupts on NIC – play with following parameters
# NOTE: You should set them for every NIC
#dev.em.0.rx_int_delay: 250
#dev.em.0.tx_int_delay: 250
#dev.em.0.rx_abs_int_delay: 250
#dev.em.0.tx_abs_int_delay: 250
# There is also multithreaded version of em/igb drivers that can be found here:
# http://people.yandex-team.ru/~wawa/
#
# for additional em monitoring and statistics use
# sysctl dev.em.0.stats=1 ; dmesg
# sysctl dev.em.0.debug=1 ; dmesg
# Also after r209242 (-CURRENT) there is a separate sysctl for each stat variable;
# Same tunings for igb
#hw.igb.rxd=4096
#hw.igb.txd=4096
#hw.igb.rx_process_limit=100

# Some useful netisr tunables. See sysctl net.isr
#net.isr.maxthreads=4
#net.isr.defaultqlimit=10240
#net.isr.maxqlimit=10240
# Bind netisr threads to CPUs
#net.isr.bindthreads=1

#
# FreeBSD 9.x+
# Increase interface send queue length
# See commit message http://svn.freebsd.org/viewvc/base?view=revision&revision=207554
#net.link.ifqmaxlen=1024

# Nicer boot logo =)
loader_logo=”beastie”

=========================================================================

E agora por último mas não tão menos importante um /etc/sysctl.conf:

=========================================================================

# No zero mapping feature
# May break wine
# (There are also reports about broken samba3)
#security.bsd.map_at_zero=0

# If you have really busy webserver with apache13 you may run out of processes
#kern.maxproc=10000
# Same for servers with apache2 / Pound
#kern.threads.max_threads_per_proc=4096

# Max. backlog size
kern.ipc.somaxconn=4096

# Shared memory // 7.2+ can use shared memory > 2Gb
kern.ipc.shmmax=2147483648

# Sockets
kern.ipc.maxsockets=204800

# Mbuf 2k clusters (on amd64 7.2+ 25600 is default)
# Note that defaults for other variables depend on this variable, for example `tcpreass`
# Note for FreeBSD-7 and older: For such high value vm.kmem_size must be increased to 3G
kern.ipc.nmbclusters=262144

# Jumbo pagesize(_SC_PAGESIZE) clusters
# Used as general packet storage for jumbo frames on some network cards
# Can be monitored via `netstat -m`
#kern.ipc.nmbjumbop=262144

# Jumbo 9k/16k clusters
# If you are using them
#kern.ipc.nmbjumbo9=65536
#kern.ipc.nmbjumbo16=32768

# For lower latency you can decrease scheduler’s maximum time slice
# default: stathz/10 (~ 13)
#kern.sched.slice=1

# Increase max command-line length showed in `ps` (e.g for Tomcat/Java)
# Default is PAGE_SIZE / 16 or 256 on x86
# This avoids commands to be presented as [executable] in `ps`
# For more info see: http://www.freebsd.org/cgi/query-pr.cgi?pr=120749
kern.ps_arg_cache_limit=4096

# Every socket is a file, so increase them
kern.maxfiles=204800
kern.maxfilesperproc=200000
kern.maxvnodes=200000

# On some systems HPET is almost 2 times faster than default ACPI-fast
# Useful on systems with lots of clock_gettime / gettimeofday calls
# See http://old.nabble.com/ACPI-fast-default-timecounter,-but-HPET-83–faster-td23248172.html
# After revision 222222 HPET became default: http://svnweb.freebsd.org/base?view=revision&revision=222222
kern.timecounter.hardware=HPET

# Small receive space, only usable on http-server, on file server this
# should be increased to 65535 or even more
#net.inet.tcp.recvspace=8192

# This is useful on Fat-Long-Pipes
#kern.ipc.maxsockbuf=10485760
#net.inet.tcp.recvbuf_max=10485760
#net.inet.tcp.recvbuf_inc=65535

# Small send space is useful for http servers that serve small files
# Autotuned since 7.x
net.inet.tcp.sendspace=16384

# This is useful on Fat-Long-Pipes
#net.inet.tcp.sendbuf_max=10485760
#net.inet.tcp.sendbuf_inc=65535

# Turn off receive autotuning
# You can play with it.
#net.inet.tcp.recvbuf_auto=0
#net.inet.tcp.sendbuf_auto=0

# This should be enabled if you going to use big spaces (>64k)
# Also timestamp field is useful when using syncookies
net.inet.tcp.rfc1323=1
# Turn this off on high-speed, lossless connections (LAN 1Gbit+)
net.inet.tcp.delayed_ack=0

# This feature is useful if you are serving data over modems, Gigabit Ethernet,
# or even high speed WAN links (or any other link with a high bandwidth delay product),
# especially if you are also using window scaling or have configured a large send window.
# Automatically disables on small RTT ( http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/netinet/tcp_subr.c?#rev1.237 )
# This sysctl was removed in 10-CURRENT:
# See: http://www.mail-archive.com/svn-src-head@freebsd.org/msg06178.html
#net.inet.tcp.inflight.enable=0

# TCP slowstart algorithm tunings
# Here we are assuming VERY uncongested network
# Only takes effect if net.inet.tcp.rfc3390 is set to 0
# Otherwise formula teken from http://tools.ietf.org/html/rfc3390
#net.inet.tcp.slowstart_flightsize=10
#net.inet.tcp.local_slowstart_flightsize=100

# Disable randomizing of ports to avoid false RST
# Before usage check SA here www.bsdcan.org/2006/papers/ImprovingTCPIP.pdf
# (it’s also says that port randomization auto-disables at some conn.rates, but I didn’t checked it thou)
#net.inet.ip.portrange.randomized=0

# Increase portrange
# For outgoing connections only. Good for seed-boxes and ftp servers.
net.inet.ip.portrange.first=1024
net.inet.ip.portrange.last=65535

#
# stops route cache degregation during a high-bandwidth flood
# http://www.freebsd.org/doc/en/books/handbook/securing-freebsd.html
#net.inet.ip.rtexpire=2
net.inet.ip.rtminexpire=2
net.inet.ip.rtmaxcache=1024

# Security
net.inet.ip.redirect=0
net.inet.ip.sourceroute=0
net.inet.ip.accept_sourceroute=0
net.inet.icmp.maskrepl=0
net.inet.icmp.log_redirect=0
net.inet.icmp.drop_redirect=1
net.inet.tcp.drop_synfin=1
#
# There is also good example of sysctl.conf with comments:
# http://www.thern.org/projects/sysctl.conf
#
# icmp may NOT rst, helpful for those pesky spoofed
# icmp/udp floods that end up taking up your outgoing
# bandwidth/ifqueue due to all that outgoing RST traffic.
#
#net.inet.tcp.icmp_may_rst=0

# Security
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2

# IPv6 Security
# For more info see http://www.fosslc.org/drupal/content/security-implications-ipv6
# Disable Node info replies
# To see this vulnerability in action run `ping6 -a sglAac ::1` or `ping6 -w ::1` on unprotected node
net.inet6.icmp6.nodeinfo=0
# Turn on IPv6 privacy extensions
# For more info see proposal http://unix.derkeiler.com/Mailing-Lists/FreeBSD/net/2008-06/msg00103.html
net.inet6.ip6.use_tempaddr=1
net.inet6.ip6.prefer_tempaddr=1
# Disable ICMP redirect
net.inet6.icmp6.rediraccept=0
# Disable acceptation of RA and auto linklocal generation if you don’t use them
#net.inet6.ip6.accept_rtadv=0
#net.inet6.ip6.auto_linklocal=0

# Increases default TTL, sometimes useful
# Default is 64
net.inet.ip.ttl=128

# Lessen max segment life to conserve resources
# ACK waiting time in miliseconds
# (default: 30000. RFC from 1979 recommends 120000)
net.inet.tcp.msl=5000

# Max bumber of timewait sockets
net.inet.tcp.maxtcptw=200000
# Don’t use tw on local connections
# As of 15 Apr 2009. Igor Sysoev says that nolocaltimewait has some buggy realization.
# So disable it or now till get fixed
#net.inet.tcp.nolocaltimewait=1

# FIN_WAIT_2 state fast recycle
net.inet.tcp.fast_finwait2_recycle=1

# Time before tcp keepalive probe is sent
# default is 2 hours (7200000)
#net.inet.tcp.keepidle=60000

# Should be increased until net.inet.ip.intr_queue_drops is zero
net.inet.ip.intr_queue_maxlen=4096

# Protocol decoding in interrupt thread.
# If you have NIC that automatically sets flow_id then it’s better to not use direct_force, and use advantages of multithreaded netisr(9)
# If you have Yandex drives you better off with net.isr.direct_force=1 and net.inet.tcp.read_locking=0 otherwise you may run into some TCP related problems
# If you have old NIC that don’t set flow_ids you may need to patch ip_input to manually set FLOW_ID via nh_m2flow
# FreeBSD 8+
#net.isr.direct=1
#net.isr.direct_force=1
# In FreeBSD 9+ it was renamed to
#net.isr.dispatch=direct

# This is for routers only
#net.inet.ip.forwarding=1
#net.inet.ip.fastforwarding=1

# This speed ups dummynet when channel isn’t saturated
net.inet.ip.dummynet.io_fast=1
# Increase dummynet(4) hash
#net.inet.ip.dummynet.hash_size=2048
#net.inet.ip.dummynet.max_chain_len

# Should be increased when you have A LOT of files on server
# (Increase until vfs.ufs.dirhash_mem becomes lower)
vfs.ufs.dirhash_maxmem=67108864

# Note from commit http://svn.freebsd.org/base/head@211031 :
# For systems with RAID volumes and/or virtualization envirnments, where
# read performance is very important, increasing this sysctl tunable to 32
# or even more will demonstratively yield additional performance benefits.
vfs.read_max=32

# Explicit Congestion Notification (see http://en.wikipedia.org/wiki/Explicit_Congestion_Notification)
net.inet.tcp.ecn.enable=1

# Flowtable – flow caching mechanism
# Useful for routers
#net.inet.flowtable.enable=1
#net.inet.flowtable.nmbflows=65535

# IPFW dynamic rules and timeouts tuning
# Increase dyn_buckets till net.inet.ip.fw.curr_dyn_buckets is lower
net.inet.ip.fw.dyn_buckets=65536
net.inet.ip.fw.dyn_max=65536
net.inet.ip.fw.dyn_ack_lifetime=120
net.inet.ip.fw.dyn_syn_lifetime=10
net.inet.ip.fw.dyn_fin_lifetime=2
net.inet.ip.fw.dyn_short_lifetime=10
# Make packets pass firewall only once when using dummynet
# i.e. packets going thru pipe are passing out from firewall with accept
#net.inet.ip.fw.one_pass=1

# shm_use_phys Wires all shared pages, making them unswappable
# Use this to lessen Virtual Memory Manager’s work when using Shared Mem.
# Useful for databases
#kern.ipc.shm_use_phys=1

# ZFS
# Enable prefetch. Useful for sequential load type i.e fileserver.
# FreeBSD sets vfs.zfs.prefetch_disable to 1 on any i386 systems and
# on any amd64 systems with less than 4GB of avaiable memory
# For additional info check this nabble thread http://old.nabble.com/Samba-read-speed-performance-tuning-td27964534.html
#vfs.zfs.prefetch_disable=0

# On highload servers you may notice following message in dmesg:
# “Approaching the limit on PV entries, consider increasing either the
# vm.pmap.shpgperproc or the vm.pmap.pv_entry_max tunable”
vm.pmap.shpgperproc=2048

=========================================================================

Como podem ver existem muitas variáveis que alteradas de forma correta, podem fazer com que o nosso servidor fique mais seguro, mais rápido, mais estável e principalmente atendendo nossas necessidades. O tuning de um servidor é importante porque nos dá o total controle de como o servidor vai responder às solicitações de carga. Algumas pessoas preferem um sistema mais automático e outras preferem moldar nas suas necessidades. Eu acredito mais em sistemas moldáveis, como é o FreeBSD, pois temos o poder de melhorar onde temos que realmente melhorar.

Existe, logicamente, sempre o lado ruim da questão que é a seguinte: se o sysadmin não souber fazer o tuning correto e o sistema não atender às suas necessidades, este logo culpará o sistema dizendo que não suporta ou não serve para o projeto.

Esse artigo foi feito com dados deste artigo que achei muito interessante e extremamente útil para ser estudado e testado.

Share Button

Fim de linha para as versões 8.1 e 8.2 final do mês

Posted by gondim | Posted in FreeBSD, Segurança, Software Livre | Posted on 01-07-2012

Tags:, ,

0

É pessoal segundo o anúncio abaixo, 31/07 é o fim da linha para o FreeBSD 8.1 e 8.2 no quesito segurança. Aconselha-se para quem tiver usando um desses releases, atualizar para a versão 8.3 pelo menos e continuar tendo suporte em segurança.  🙂

Hello Everyone,

On July 31st 2012, FreeBSD 8.1 and FreeBSD 8.2 will reach their End of
Life and will no longer be supported by the FreeBSD Security Team.
Users of FreeBSD 8.1 and 8.2 are strongly encouraged to upgrade to one
of the newer releases before the that date.

The current supported branches and expected EoL dates are:

  +---------------------------------------------------------------------+
  |  Branch   |  Release   |  Type  |   Release date  |  Estimated EoL  |
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_7   |n/a         |n/a     |n/a              |February 28, 2013|
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_7_4 |7.4-RELEASE |Extended|February 24, 2011|February 28, 2013|
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_8 |n/a |n/a |n/a |last release + 2y|
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_8_1 |8.1-RELEASE |Extended|July 23, 2010    |July 31, 2012    |
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_8_2 |8.2-RELEASE |Normal  |February 24, 2011|July 31, 2012    |
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_8_3 |8.3-RELEASE |Extended|April 18, 2012   |April 30, 2014   |
  |-----------+------------+--------+-----------------+-----------------|
  |RELENG_9 |n/a |n/a |n/a |last release + 2y||-----------+------------+--------+-----------------+-----------------|
  |RELENG_9_0 |9.0-RELEASE |Normal  |January 10, 2012 |January 31, 2013 |
  +---------------------------------------------------------------------+
— Simon L. B. Nielsen FreeBSD Security Officer
Share Button

Novas vulnerabilidades – bind 9 e sysret + correção IPv6

Posted by gondim | Posted in Dicas, FreeBSD, Segurança | Posted on 12-06-2012

Tags:

0

Saíram 2 novas vulnerabilidades e um acerto relacionado ao IPv6.

É bom atualizarem os sistemas e sempre se manterem seguros. Abaixo os links com todas as informações necessárias:

http://security.freebsd.org/advisories/FreeBSD-SA-12:04.sysret.asc

http://security.freebsd.org/advisories/FreeBSD-SA-12:03.bind.asc

http://security.freebsd.org/advisories/FreeBSD-EN-12:02.ipv6refcount.asc

O problema do sysret só ocorre em sistemas FreeBSD 64 bits e em  CPU que não seja AMD.

Share Button

OpenVPN interligando empresas

Posted by gondim | Posted in FreeBSD, Segurança, Software Livre | Posted on 11-06-2012

Tags:,

0

Informação sempre foi e sempre será o grande tesouro da humanidade. Algumas delas podem ser públicas e outras extremamente sigilosas. A troca de informação entre filiais de uma mesma empresa, muitas das vezes serão confidenciais e por isso existe a necessidade de recursos para que isso se torne possível.

Para que haja comunicação entre essas filiais é necessário que se tenha um meio físico por onde passará todo o fluxo de informação. A Internet é hoje o maior meio físico em comum para troca de informações e que interliga todo o mundo.

Então se temos o meio físico o que falta para uma comunicação segura e confidencial? Falta uma coisa chamada VPN (Virtual Private Network) que pode ser encriptada ou não. A definição de VPN seria a de se ter um túnel privativo interligado duas ou mais redes e apenas essas redes se enxergariam. Contudo se alguém conseguisse entrar nesse túnel teria acesso a todas as informações trafegando em texto puro. Por existir essa brecha é que utilizamos a criptografia dos dados em uma VPN com a finalidade de impossibilitar que terceiros tenham acesso ao conteúdo da comunicação.

Nesse artigo falarei sobre uma ferramenta que tem crescido muito nesses últimos anos e competindo com outras mais antigas. Seu sucesso tem se dado pela simplicidade, segurança e robustez. Irei falar aqui sobre o OpenVPN um software que nos permite criar VPNs para interligar de forma segura e simples, qualquer empresa e suas filiais. Mostrarei exemplos interligando uma empresa fictícia e suas duas filiais também fictícias.

Existe um ditado que diz: “uma imagem vale mais que 1000 palavras” e por isso vou exemplificar nosso trabalho com um desenho da rede que criaremos.

  • Empresa: BSDInfo matriz
  • Localidade: Brasil / Araruama
  • Bloco IP da Rede: 10.200.200.0/24
  • IP Público fictício: 169.169.169.1/24
  • IP VPN: 172.16.24.1/30

 

  • Empresa: BSDInfo filial
  • Localidade: Brasil / Saquarema
  • Bloco IP da Rede: 10.200.201.0/24
  • IP Público fictício: 169.169.169.2/24
  • IP VPN: 172.16.24.6/30

 

  • Empresa: BSDInfo filial
  • Localidade: Brasil / São Pedro
  • Bloco IP da rede: 10.200.202.0/24
  • IP Público fictício: 169.169.169.3/24
  • IP VPN: 172.16.24.10/30

Baseado nas informações acima o diagrama abaixo será usado como referência para o nosso laboratório:

Conforme o diagrama acima, faremos com que todas as redes 10.200.200.0/24, 10.200.201.0/24 e 10.200.202.0/24 possam trocar dados seguramente entre eles e utilizando a Internet como meio de transporte das informações.

Para a nossa configuração usaremos um servidor FreeBSD em cada localidade com 2 interfaces de rede em cada um deles.

Na BSDInfo Araruama (matriz) será onde configuraremos o OpenVPN como Servidor e nas filiais configuraremos o OpenVPN como Cliente.

Instalando o OpenVPN nos servidores:

Atualizando os ports:

# portsnap fetch update

Instalando o bash porque os scripts do OpenVPN são em bash:

# cd /usr/ports/shells/bash
# make install clean
# rehash

Instalando o OpenVPN:

# cd /usr/ports/security/openvpn
# make install clean
# rehash

Não precisa selecionar qualquer opção na próxima tela, mantenha o default e continue a instalação. Faça os passos acima nos 3 servidores do nosso diagrama.

Começaremos nossa configuração no servidor principal que receberá as conexões das filiais. Após a instalação do OpenVPN criaremos o diretório onde faremos as nossas configurações:

# mkdir /usr/local/etc/openvpn
# chmod 700 /usr/local/etc/openvpn

Todos os procedimentos acima deverão ser feitos em todos os servidores da VPN.

Começaremos então a configuração do servidor principal da VPN.

Para facilitar a criação de VPNs, o OpenVPN vem com uma coleção de scripts para criação dos certificados e chaves que iremos utilizar nas conexões dos clientes com o servidor.

Façamos os procedimentos abaixo para nos facilitar:

# cd /usr/local/etc/openvpn
# cp -rp /usr/local/share/doc/openvpn/easy-rsa/2.0 .
# cd 2.0
# chmod +x build-ca build-dh build-inter build-key build-key-pass build-key-pkcs12 build-key-server build-req build-req-pass clean-all inherit-inter list-crl pkitool revoke-full sign-req whichopensslcnf

Dentro deste diretório 2.0 estão todos os shell scripts que falei. Dentro dele existe um arquivo chamado vars e faremos uma configuração nele antes de gerarmos os certificados. Mudaremos as variáveis abaixo do arquivo vars.

export KEY_COUNTRY=”US”
export KEY_PROVINCE=”CA”
export KEY_CITY=”SanFrancisco”
export KEY_ORG=”Fort-Funston”
export KEY_EMAIL=”me@myhost.mydomain”
export KEY_EMAIL=mail@host.domain
export KEY_CN=changeme
export KEY_NAME=changeme
export KEY_OU=changeme

 Mudaremos o bloco acima para o nosso exemplo:

export KEY_COUNTRY=”BR”
export KEY_PROVINCE=”RJ”
export KEY_CITY=”Araruama”
export KEY_ORG=”BSDInfo”
export KEY_EMAIL=”ti@bsdinfo.com.br”
export KEY_CN=vpnsrv
export KEY_NAME=vpnsrv
export KEY_OU=TI

Após a configuração do arquivo vars com os dados da criação dos nossos certificados, precisamos inicializar a estrutura que acomodará os certificados que os scripts criarão. Executaremos os seguintes passos:

# cd /usr/local/etc/openvpn/2.0
# bash
# source vars
NOTE: If you run ./clean-all, I will be doing a rm -rf on /usr/local/etc/openvpn/2.0/keys

Com os comandos acima armazenaremos os valores das variáveis que configuramos, em memória, para que os scripts possam usar. Importante executar o bash antes de executar qualquer coisa senão os scripts não funcionarão.

O próximo procedimento só deve ser feito apenas uma vez porque este irá criar a estrutura de controle dos certificados e chaves. Se for feito após a criação de qualquer certificado, todos quem foram criados serão apagados e o controle iniciará do zero.

# ./clean-all

Após o comando acima será criado o diretório /usr/local/etc/openvpn/2.0/keys com os arquivos: index.txt e serial que serão usados no controle da criação dos certificados.

Vamos agora criar Diffie-Hellman do nosso servidor de VPN:

# cd /usr/local/etc/openvpn/2.0
# ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
…..+…………………..++*++*++*

A configuração é um pouco trabalhosa mas não é nenhum bicho de 7 cabeças. Após tudo funcionando, configurar outros servidores será muito simples. A única coisa que poderá deixar complexa a sua configuração é quando existirem muitas redes atrás dos servidores e elas precisarem ser acessadas de todos os lugares.

Agora criaremos o certificado da CA do nosso servidor. Muito cuidado com ele porque é o segredo da segurança da nossa VPN. Qualquer certificado assinado por ele será autorizado à conectar em nossa VPN. Esse é o principal motivo de não se usar certificados de CAs conhecidas. Necessitamos de criar nossa própria CA.

# ./build-ca
Generating a 1024 bit RSA private key
………….++++++
……………++++++
writing new private key to ‘ca.key’
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [BR]:
State or Province Name (full name) [RJ]:
Locality Name (eg, city) [Araruama]:
Organization Name (eg, company) [BSDInfo]:
Organizational Unit Name (eg, section) [TI]:
Common Name (eg, your name or your server’s hostname) [vpnsrv]:BSDInfo – CA
Name [vpnsrv]:
Email Address [ti@bsdinfo.com.br]:

Vamos dar uma olhada agora no nosso diretório de keys?

# ls -l /usr/local/etc/openvpn/2.0/keys/
total 16
-rw-r–r–  1 root  wheel  1334 May 28 01:29 ca.crt
-rw——-  1 root  wheel   887 May 28 01:29 ca.key
-rw-r–r–  1 root  wheel   245 May 28 01:24 dh1024.pem
-rw-r–r–  1 root  wheel     0 May 28 01:11 index.txt
-rw-r–r–  1 root  wheel     3 May 28 01:11 serial

Agora já temos o certificado da CA (ca.crt) que usaremos para assinar o certificado do nosso servidor da VPN e dos outros servidores clientes.

Vamos agora criar nosso primeiro certificado do servidor das VPNs:

# cd /usr/local/etc/openvpn/2.0/
# ./build-key-server vpnsrv
Generating a 1024 bit RSA private key
……………..++++++
…….++++++
writing new private key to ‘vpnsrv.key’
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [BR]:
State or Province Name (full name) [RJ]:
Locality Name (eg, city) [Araruama]:
Organization Name (eg, company) [BSDInfo]:
Organizational Unit Name (eg, section) [TI]:
Common Name (eg, your name or your server’s hostname) [vpnsrv]:
Name [vpnsrv]:
Email Address [ti@bsdinfo.com.br]:
Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/etc/openvpn/2.0/openssl-0.9.8.cnf
Check that the request matches the signature
Signature ok
The Subject’s Distinguished Name is as follows
countryName           :PRINTABLE:’BR’
stateOrProvinceName   :PRINTABLE:’RJ’
localityName          :PRINTABLE:’Araruama’
organizationName      :PRINTABLE:’BSDInfo’
organizationalUnitName:PRINTABLE:’TI’
commonName            :PRINTABLE:’vpnsrv’
name                  :PRINTABLE:’vpnsrv’
emailAddress          :IA5STRING:’ti@bsdinfo.com.br’
Certificate is to be certified until May 26 05:20:25 2022 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Aproveitando que estamos criando os certificados, vamos agora criar os certificados das VPNs cliente. Primeiro a da BSDInfo – Saquarema:

# ./build-key vpnsaq
Generating a 1024 bit RSA private key
..++++++
…………++++++
writing new private key to ‘vpnsaq.key’
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [BR]:
State or Province Name (full name) [RJ]:
Locality Name (eg, city) [Araruama]:
Organization Name (eg, company) [BSDInfo]:
Organizational Unit Name (eg, section) [TI]:
Common Name (eg, your name or your server’s hostname) [vpnsaq]:
Name [vpnsrv]:vpnsaq
Email Address [ti@bsdinfo.com.br]:
Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/etc/openvpn/2.0/openssl-0.9.8.cnf
Check that the request matches the signature
Signature ok
The Subject’s Distinguished Name is as follows
countryName           :PRINTABLE:’BR’
stateOrProvinceName   :PRINTABLE:’RJ’
localityName          :PRINTABLE:’Araruama’
organizationName      :PRINTABLE:’BSDInfo’
organizationalUnitName:PRINTABLE:’TI’
commonName            :PRINTABLE:’vpnsaq’
name                  :PRINTABLE:’vpnsaq’
emailAddress          :IA5STRING:’ti@bsdinfo.com.br’
Certificate is to be certified until May 26 06:22:01 2022 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Update

Agora o certificado e chave da BSDInfo – São Pedro:

# ./build-key vpnspa
Generating a 1024 bit RSA private key
….++++++
………………………………………………………………………………..++++++
writing new private key to ‘vpnspa.key’
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [BR]:
State or Province Name (full name) [RJ]:
Locality Name (eg, city) [Araruama]:
Organization Name (eg, company) [BSDInfo]:
Organizational Unit Name (eg, section) [TI]:
Common Name (eg, your name or your server’s hostname) [vpnspa]:
Name [vpnsrv]:vpnspa
Email Address [ti@bsdinfo.com.br]:
Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/etc/openvpn/2.0/openssl-0.9.8.cnf
Check that the request matches the signature
Signature ok
The Subject’s Distinguished Name is as follows
countryName           :PRINTABLE:’BR’
stateOrProvinceName   :PRINTABLE:’RJ’
localityName          :PRINTABLE:’Araruama’
organizationName      :PRINTABLE:’BSDInfo’
organizationalUnitName:PRINTABLE:’TI’
commonName            :PRINTABLE:’vpnspa’
name                  :PRINTABLE:’vpnspa’
emailAddress          :IA5STRING:’ti@bsdinfo.com.br’
Certificate is to be certified until May 26 06:31:52 2022 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Vamos dar uma olhada agora nos certificados e chaves que temos:

# ls -l /usr/local/etc/openvpn/2.0/keys/
total 84
-rw-r–r–  1 root  wheel  4030 May 28 02:21 01.pem
-rw-r–r–  1 root  wheel  3913 May 28 03:23 02.pem
-rw-r–r–  1 root  wheel  3913 May 28 03:31 03.pem
-rw-r–r–  1 root  wheel  1334 May 28 01:29 ca.crt
-rw——-  1 root  wheel   887 May 28 01:29 ca.key
-rw-r–r–  1 root  wheel   245 May 28 01:24 dh1024.pem
-rw-r–r–  1 root  wheel   360 May 28 03:31 index.txt
-rw-r–r–  1 root  wheel    21 May 28 03:31 index.txt.attr
-rw-r–r–  1 root  wheel    21 May 28 03:23 index.txt.attr.old
-rw-r–r–  1 root  wheel   240 May 28 03:23 index.txt.old
-rw-r–r–  1 root  wheel     3 May 28 03:31 serial
-rw-r–r–  1 root  wheel     3 May 28 03:23 serial.old
-rw-r–r–  1 root  wheel  3913 May 28 03:23 vpnsaq.crt
-rw-r–r–  1 root  wheel   708 May 28 03:22 vpnsaq.csr
-rw——-  1 root  wheel   891 May 28 03:22 vpnsaq.key
-rw-r–r–  1 root  wheel  3913 May 28 03:31 vpnspa.crt
-rw-r–r–  1 root  wheel   708 May 28 03:31 vpnspa.csr
-rw——-  1 root  wheel   887 May 28 03:31 vpnspa.key
-rw-r–r–  1 root  wheel  4030 May 28 02:21 vpnsrv.crt
-rw-r–r–  1 root  wheel   708 May 28 02:20 vpnsrv.csr
-rw——-  1 root  wheel   887 May 28 02:20 vpnsrv.key

Agora que temos todos os certificados e chaves que iremos utilizar podemos enfim criar o arquivo de configuração do servidor:

# cd /usr/local/etc/openvpn/
# mkdir /var/log/openvpn
# chmod 750 /var/log/openvpn
# mkdir ccd
# openvpn –genkey –secret ta.key
# cat <<EOF>> vpnsrv.conf
port 1190
proto tcp
dev tun
ca /usr/local/etc/openvpn/2.0/keys/ca.crt
cert /usr/local/etc/openvpn/2.0/keys/vpnsrv.crt
key /usr/local/etc/openvpn/2.0/keys/vpnsrv.key
dh /usr/local/etc/openvpn/2.0/keys/dh1024.pem
server 172.16.24.0 255.255.255.0
ifconfig-pool-persist /usr/local/etc/openvpn/ipp.txt
client-config-dir /usr/local/etc/openvpn/ccd
tls-auth /usr/local/etc/openvpn/ta.key 0
keepalive 10 120
comp-lzo
persist-key
persist-tun
log-append /var/log/openvpn/openvpn.log
status /var/log/openvpn/status.log
client-to-client

# Saquarema Network
route 10.200.201.0 255.255.255.255

# Sao Pedro Network
route 10.200.202.0 255.255.255.255
EOF

O parâmetro cliente-to-client é extremamente importante para que as redes dos clientes possam trocar dados entre si. Caso contrário eles só trocarão dados com a rede do servidor da VPN (10.200.200.0/24).

O diretório ccd é usado para armazenarmos as configurações que forçaremos os clientes à usarem. Nós também criamos e usaremos o ta.key para aumentarmos a segurança e evitarmos um DoS na porta 1190/TCP do nosso servidor OpenVPN. Você pode alterar a porta e o protocolo para UDP como bem quiser, desde que configure também nos clientes.

Adicionamos também as rotas paras as redes 10.200.201.0/24 e 10.200.202.0/24. No parâmetro server definimos a rede usada pelas VPNs entre si que será 172.16.24.0/24.

Estamos quase acabando o servidor. Agora precisamos configurar ele para iniciar no boot do sistema:

# cd /usr/local/etc/rc.d
# ln –sf openvpn vpnsrv
# cat <<EOF>> /etc/rc.conf
vpnsrv_enable=”YES”
vpnsrv_if=”tun”
vpnsrv_configfile=”/usr/local/etc/openvpn/vpnsrv.conf”
vpnsrv_dir=”/usr/local/etc/openvpn”
EOF

Agora sim podemos iniciar nosso servidor de VPN:

 # service vpnsrv start

Se tudo correr bem teremos o serviço rodando e algo já nos logs:

# cat /var/log/openvpn.log
Mon May 28 06:47:48 2012 OpenVPN 2.2.2 amd64-portbld-freebsd9.0 [SSL] [LZO2] [eurephia] built on May 27 2012
Mon May 28 06:47:48 2012 NOTE: OpenVPN 2.1 requires ‘–script-security 2’ or higher to call user-defined scripts or executables
Mon May 28 06:47:48 2012 Control Channel Authentication: using ‘/usr/local/etc/openvpn/ta.key’ as a OpenVPN static key file
Mon May 28 06:47:48 2012 TUN/TAP device /dev/tun0 opened
Mon May 28 06:47:48 2012 /sbin/ifconfig tun0 172.16.24.1 172.16.24.2 mtu 1500 netmask 255.255.255.255 up
add net 10.200.201.0: gateway 172.16.24.2
add net 10.200.202.0: gateway 172.16.24.2
add net 172.16.24.0: gateway 172.16.24.2
Mon May 28 06:47:48 2012 Listening for incoming TCP connection on [undef]:1190
Mon May 28 06:47:48 2012 TCPv4_SERVER link local (bound): [undef]:1190
Mon May 28 06:47:48 2012 TCPv4_SERVER link remote: [undef]
Mon May 28 06:47:48 2012 Initialization Sequence Completed
Mon May 28 06:47:48 2012 Ipv6 in tun mode is not supported in OpenVPN 2.2

Notaremos uma nova interface de rede que será usada nos túneis das VPNs:

# ifconfig tun0
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> metric 0 mtu 1500
options=80000<LINKSTATE>
inet6 fe80::a00:27ff:fed0:bdc3%tun0 prefixlen 64 scopeid 0x4
inet 172.16.24.1 à 172.16.24.2 netmask 0xffffffff
nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>
Opened by PID 42385

Agora precisamos finalizar nosso servidor criando os arquivos de configuração para as outras VPNs naquele diretório /usr/local/etc/openvpn/ccd:

# cd /usr/local/etc/openvpn/ccd/
# cat <<EOF>> vpnsaq
ifconfig-push 172.16.24.6 172.16.24.5
iroute 10.200.201.0 255.255.255.0
EOF

O nome do arquivo, vpnsaq, é muito importante e deve ser o mesmo nome que usamos quando criamos o certificado para BSDInfo Saquarema. Reparem no trecho abaixo:

Organization Name (eg, company) [BSDInfo]:
Organizational Unit Name (eg, section) [TI]:
Common Name (eg, your name or your server’s hostname) [vpnsaq]:

Como podem ver mantive o nome vpnsaq no Common Name e esse deve ser o nome do arquivo de configuração porque quando o cliente se conectar no servidor VPN, o mesmo irá checar o Common Name e tentará abrir o arquivo com aquele nome no /usr/local/etc/openvpn/ccd e aí passará o IP e configurações para o cliente da VPN.

O parâmetro “ifconfig-push 172.16.24.6 172.16.24.5” diz ao cliente VPN de Saquarema que ele usará o IP 172.16.24.6 e seu gateway 172.16.24.5.

Já o parâmetro “eyste 10.200.201.0 255.255.255.0” serve para disponibilizar a rede interna de Saquarema para os demais clientes que no caso do nosso exemplo, seria a VPN de São Pedro. Sem esse parâmetro, a rede de São Pedro (10.200.202.0/24) não conseguiria acessar a rede de Saquarema (10.200.201.0/24).

Agora faremos o mesmo para a VPN da BSDInfo São Pedro:

# cd /usr/local/etc/openvpn/ccd/
# cat <<EOF>> vpnspa
ifconfig-push 172.16.24.10 172.16.24.9
iroute 10.200.202.0 255.255.255.0
EOF

Assim terminamos nossa configuração no servidor da nossa VPN. Passaremos para a configuração dos outros 2 servidores que serão os clientes nesse nosso artigo.

Para configurarmos os clientes precisaremos levar alguns arquivos para esses servidores:

BSDInfo Saquarema:

  • /usr/local/etc/openvpn/ta.key
  • /usr/local/etc/openvpn/2.0/keys/ca.crt
  • /usr/local/etc/openvpn/2.0/keys/vpnsaq.crt
  • /usr/local/etc/openvpn/2.0/eys/vpnsaq.key

BSDInfo São Pedro:

  • /usr/local/etc/openvpn/ta.key
  • /usr/local/etc/openvpn/2.0/eys/ca.crt
  • /usr/local/etc/openvpn/2.0/eys/vpnspa.crt
  • /usr/local/etc/openvpn/2.0/eys/vpnspa.key

No servidor de VPN da BSDInfo Saquarema faremos a instalação do OpenVPN conforme mostrado no início do nosso artigo. Criaremos o diretório /usr/local/etc/openvpn e o /var/log/openvpn. Não precisaremos mexer com a estrutura dos certificados e chaves, uma vez que já fizemos esse trabalho no servidor que atenderá as conexões das VPNs.

Colocaremos os arquivos de certificados e chaves, que trouxemos do servidor, em /usr/local/etc/openvpn. Após isso criaremos nosso arquivo de configuração assim:

# cd /usr/local/etc/openvpn/
# cat <<EOF>> vpnsaq.conf
client
dev tun
proto tcp
remote 169.169.169.1 1190
ns-cert-type server
nobind
persist-key
persist-tun
ca /usr/local/etc/openvpn/ca.crt
cert /usr/local/etc/openvpn/vpnsaq.crt
key /usr/local/etc/openvpn/vpnsaq.key
tls-auth /usr/local/etc/openvpn/ta.key 1
comp-lzo
log-append /var/log/openvpn/openvpn.log
status /var/log/openvpn/status.log

# Araruama Network
route 10.200.200.0 255.255.255.0

# Sao Pedro Network
route 10.200.202.0 255.255.255.0
EOF

Após criarmos esse arquivo de configuração teremos os seguintes arquivos:

# ls -l /usr/local/etc/openvpn/
total 20
-rw-r–r–  1 root  wheel  1334 May 28 08:46 ca.crt
-rw——-  1 root  wheel   636 May 28 08:46 ta.key
-rw-r–r–  1 root  wheel   337 May 28 08:47 vpnsaq.conf
-rw-r–r–  1 root  wheel  3913 May 28 08:46 vpnsaq.crt
-rw——-  1 root  wheel   891 May 28 08:46 vpnsaq.key

Para finalizarmos colocando o OpenVPN na inicialização do sistema:

# cd /usr/local/etc/rc.d
# ln –sf openvpn vpnsaq
# cat <<EOF>> /etc/rc.conf
vpnsaq_enable=”YES”
vpnsaq_if=”tun”
vpnsaq_configfile=”/usr/local/etc/openvpn/vpnsaq.conf”
vpnsaq_dir=”/usr/local/etc/openvpn”
EOF

Para finalizar nosso último cliente da VPN, usaremos os mesmos procedimentos citados no BSDInfo Saquarema mas alterando um pouco a conf e usando os certificados e chaves corretos:

# cd /usr/local/etc/openvpn/
# cat <<EOF>> vpnspa.conf
client
dev tun
proto tcp
remote 169.169.169.1 1190
ns-cert-type server
nobind
persist-key
persist-tun
ca /usr/local/etc/openvpn/ca.crt
cert /usr/local/etc/openvpn/vpnspa.crt
key /usr/local/etc/openvpn/vpnspa.key
tls-auth /usr/local/etc/openvpn/ta.key 1
comp-lzo
log-append /var/log/openvpn/openvpn.log
status /var/log/openvpn/status.log

# Araruama Network
route 10.200.200.0 255.255.255.0

# Saquarema Network
route 10.200.201.0 255.255.255.0
EOF

No final teremos os seguintes arquivos em /usr/local/etc/openvpn/:

# ls -l /usr/local/etc/openvpn/
total 20
-rw-r–r–  1 root  wheel  1334 May 28 08:46 ca.crt
-rw——-  1 root  wheel   636 May 28 08:46 ta.key
-rw-r–r–  1 root  wheel   337 May 28 08:47 vpnspa.conf
-rw-r–r–  1 root  wheel  3913 May 28 08:46 vpnspa.crt
-rw——-  1 root  wheel   891 May 28 08:46 vpnspa.key

Finalizando o artigo com a configuração para a inicialização dessa VPN:

# cd /usr/local/etc/rc.d
# ln -sf openvpn vpnspa
# cat <<EOF>> /etc/rc.conf
vpnspa_enable=”YES”
vpnspa_if=”tun”
vpnspa_configfile=”/usr/local/etc/openvpn/vpnspa.conf”
vpnspa_dir=”/usr/local/etc/openvpn”
EOF

Qualquer problema sempre consultem os logs gerados em /var/log/openvpn, afinal é para isso que os logs servem. Para nos auxiliar em problemas, informações e gerar estatísticas.

Mais informações sobre OpenVPN podem ser consultadas aqui:

Autor: Marcelo Gondim gondim em bsdinfo.com.br

Data: 29/05/2012

Este artigo é livre para ser distribuído, alterado e melhorado desde que respeitando meus créditos e os créditos de todo aquele que vier à contribuir com este documento.

Share Button

Novas vulnerabilidades no FreeBSD – OpenSSL e Crypt

Posted by gondim | Posted in FreeBSD, Segurança | Posted on 30-05-2012

Tags:,

1

As vulnerabilidades encontradas não aparecerão no portaudit e por isso deve ser dada uma atenção melhor. Muitos programas utilizam o openssl e o crypt. Se você compilou algum programa estaticamente com essas libs então precisará recompilá-los após aplicar os patches.
======================================================================
FreeBSD-SA-12:01.openssl                                    Security Advisory                               The FreeBSD Project

Topic:          OpenSSL multiple vulnerabilities

Category:       contrib
Module:         openssl
Announced:      2012-05-03
Credits:        Adam Langley, George Kadianakis, Ben Laurie, Ivan Nestlerode, Tavis Ormandy
Affects:        All supported versions of FreeBSD.
Corrected:      2012-05-30 12:01:28 UTC (RELENG_7, 7.4-STABLE)
2012-05-30 12:01:28 UTC (RELENG_7_4, 7.4-RELEASE-p8)
2012-05-30 12:01:28 UTC (RELENG_8, 8.3-STABLE)
2012-05-30 12:01:28 UTC (RELENG_8_3, 8.3-RELEASE-p2)
2012-05-30 12:01:28 UTC (RELENG_8_2, 8.2-RELEASE-p8)
2012-05-30 12:01:28 UTC (RELENG_8_1, 8.1-RELEASE-p10)
2012-05-30 12:01:28 UTC (RELENG_9, 9.0-STABLE)
2012-05-30 12:01:28 UTC (RELENG_9_0, 9.0-RELEASE-p2)
CVE Name:       CVE-2011-4576, CVE-2011-4619, CVE-2011-4109, CVE-2012-0884, CVE-2012-2110

For general information regarding FreeBSD Security Advisories,
including descriptions of the fields above, security branches, and the
following sections, please visit <URL:http://security.FreeBSD.org/>.

0.   Revision History

v1.0  2012-05-02 Initial release.
v1.1  2012-05-30 Updated patch to add SGC and BUF_MEM_grow_clean(3) bug
fixes.

I.   Background

FreeBSD includes software from the OpenSSL Project.  The OpenSSL Project is
a collaborative effort to develop a robust, commercial-grade, full-featured
Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3)
and Transport Layer Security (TLS v1) protocols as well as a full-strength
general purpose cryptography library.

II.  Problem Description

OpenSSL fails to clear the bytes used as block cipher padding in SSL 3.0
records when operating as a client or a server that accept SSL 3.0
handshakes.  As a result, in each record, up to 15 bytes of uninitialized
memory may be sent, encrypted, to the SSL peer.  This could include
sensitive contents of previously freed memory. [CVE-2011-4576]

OpenSSL support for handshake restarts for server gated cryptography (SGC)
can be used in a denial-of-service attack. [CVE-2011-4619]

If an application uses OpenSSL’s certificate policy checking when
verifying X509 certificates, by enabling the X509_V_FLAG_POLICY_CHECK
flag, a policy check failure can lead to a double-free. [CVE-2011-4109]

A weakness in the OpenSSL PKCS #7 code can be exploited using
Bleichenbacher’s attack on PKCS #1 v1.5 RSA padding also known as the
million message attack (MMA). [CVE-2012-0884]

The asn1_d2i_read_bio() function, used by the d2i_*_bio and d2i_*_fp
functions, in OpenSSL contains multiple integer errors that can cause
memory corruption when parsing encoded ASN.1 data.  This error can occur
on systems that parse untrusted ASN.1 data, such as X.509 certificates
or RSA public keys. [CVE-2012-2110]

III. Impact

Sensitive contents of the previously freed memory can be exposed
when communicating with a SSL 3.0 peer.  However, FreeBSD OpenSSL
version does not support SSL_MODE_RELEASE_BUFFERS SSL mode and
therefore have a single write buffer per connection.  That write buffer
is partially filled with non-sensitive, handshake data at the beginning
of the connection and, thereafter, only records which are longer than
any previously sent record leak any non-encrypted data.  This, combined
with the small number of bytes leaked per record, serves to limit to
severity of this issue. [CVE-2011-4576]

Denial of service can be caused in the OpenSSL server application
supporting server gated cryptography by performing multiple handshake
restarts. [CVE-2011-4619]

The double-free, when an application performs X509 certificate policy
checking, can lead to denial of service in that application.
[CVE-2011-4109]

A weakness in the OpenSSL PKCS #7 code can lead to a successful
Bleichenbacher attack.  Only users of PKCS #7 decryption operations are
affected.  A successful attack needs on average 2

^20

messages. In
practice only automated systems will be affected as humans will not be
willing to process this many messages.  SSL/TLS applications are not
affected. [CVE-2012-0884]

The vulnerability in the asn1_d2i_read_bio() OpenSSL function can lead
to a potentially exploitable attack via buffer overflow.  The SSL/TLS
code in OpenSSL is not affected by this issue, nor are applications
using the memory based ASN.1 functions.  There are no applications in
FreeBSD base system affected by this issue, though some 3rd party
consumers of these functions might be vulnerable when processing
untrusted ASN.1 data.  [CVE-2012-2110]

The patch provided with the initial version of this advisory introduced
bug to the Server Gated Cryptography (SGC) handshake code, that could
cause SGC handshake to fail for a legitimate client.  The updated patch
also fixes the return error code in the BUF_MEM_grow_clean(3) function in the
buffer size check code introduced by the CVE-2012-2110 fix.

IV.  Workaround

No workaround is available.

V.   Solution

Perform one of the following:

1) Upgrade your vulnerable system to 7-STABLE, 8-STABLE or 9-STABLE,
or to the RELENG_7_4, RELENG_8_3, RELENG_8_2, RELENG_8_1, RELENG_9_0
security branch dated after the correction date.

2) To update your vulnerable system via a source code patch:

The following patches have been verified to apply to FreeBSD 7.4, 8.3,
8.2, 8.1, and 9.0 systems.

a) Download the relevant patch from the location below, and verify the
detached PGP signature using your PGP utility.

# fetch http://security.FreeBSD.org/patches/SA-12:01/openssl2.patch
# fetch http://security.FreeBSD.org/patches/SA-12:01/openssl2.patch.asc

NOTE: The patch distributed at the time of the original advisory fixed
the security vulnerability, but introduced a bug to the SGC handshake
code that can cause the SGC handshake to fail for a legitimate client.
Systems to which the original patch was applied should be patched with
the following corrective patch, which contains only the additional
changes required to fix the newly-introduced SGC handshake bug.  The
updated patch also corrects an error code for an error check introduced
in the original patch.

# fetch http://security.FreeBSD.org/patches/SA-12:01/openssl-sgc-fix.patch
# fetch http://security.FreeBSD.org/patches/SA-12:01/openssl-sgc-fix.patch.asc

b) Execute the following commands as root:

# cd /usr/src
# patch < /path/to/patch

c) Recompile the operating system as described in
<URL: http://www.freebsd.org/handbook/makeworld.html> and reboot the
system.

NOTE: Any third-party applications, including those installed from the
FreeBSD ports collection, which are statically linked to libcrypto(3)
should be recompiled in order to use the corrected code.

3) To update your vulnerable system via a binary patch:

Systems running 7.4-RELEASE, 8.3-RELEASE, 8.2-RELEASE, 8.1-RELEASE or
9.0-RELEASE on the i386 or amd64 platforms can be updated via the
freebsd-update(8) utility:

# freebsd-update fetch
# freebsd-update install

VI.  Correction details

The following list contains the revision numbers of each file that was
corrected in FreeBSD.

CVS:

Branch                                                           Revision
Path
– ————————————————————————-
RELENG_7
src/crypto/openssl/crypto/buffer/buffer.c                   1.1.1.4.2.3
src/crypto/openssl/crypto/pkcs7/pk7_doit.c                 1.1.1.13.2.2
src/crypto/openssl/crypto/mem.c                             1.1.1.8.2.2
src/crypto/openssl/crypto/x509v3/pcy_map.c                  1.1.1.1.2.2
src/crypto/openssl/crypto/x509v3/pcy_tree.c                 1.1.1.2.2.2
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                   1.1.1.3.2.1
src/crypto/openssl/ssl/ssl.h                               1.1.1.16.2.3
src/crypto/openssl/ssl/ssl_err.c                           1.1.1.11.2.3
src/crypto/openssl/ssl/s3_enc.c                            1.1.1.13.2.2
src/crypto/openssl/ssl/s3_srvr.c                           1.1.1.17.2.8
src/crypto/openssl/ssl/ssl3.h                               1.1.1.6.2.2
RELENG_7_4
src/UPDATING                                            1.507.2.36.2.10
src/sys/conf/newvers.sh                                  1.72.2.18.2.13
src/crypto/openssl/crypto/buffer/buffer.c               1.1.1.4.2.1.2.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c             1.1.1.13.2.1.2.1
src/crypto/openssl/crypto/mem.c                         1.1.1.8.2.1.2.1
src/crypto/openssl/crypto/x509v3/pcy_map.c              1.1.1.1.2.1.2.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c             1.1.1.2.2.1.2.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.20.1
src/crypto/openssl/ssl/ssl.h                           1.1.1.16.2.2.2.1
src/crypto/openssl/ssl/ssl_err.c                       1.1.1.11.2.2.2.1
src/crypto/openssl/ssl/s3_enc.c                        1.1.1.13.2.1.2.1
src/crypto/openssl/ssl/s3_srvr.c                       1.1.1.17.2.5.2.2
src/crypto/openssl/ssl/ssl3.h                           1.1.1.6.2.1.2.1
RELENG_8
src/crypto/openssl/crypto/buffer/buffer.c                       1.2.2.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c                1.1.1.13.10.2
src/crypto/openssl/crypto/mem.c                                 1.2.2.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                      1.2.2.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                     1.2.2.2
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.10.1
src/crypto/openssl/ssl/ssl.h                                    1.2.2.2
src/crypto/openssl/ssl/ssl_err.c                                1.2.2.2
src/crypto/openssl/ssl/s3_enc.c                                 1.2.2.2
src/crypto/openssl/ssl/s3_srvr.c                                1.3.2.6
src/crypto/openssl/ssl/ssl3.h                                   1.2.2.2
RELENG_8_3
src/UPDATING                                             1.632.2.26.2.4
src/sys/conf/newvers.sh                                   1.83.2.15.2.6
src/crypto/openssl/crypto/buffer/buffer.c                      1.2.14.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c            1.1.1.13.10.1.4.1
src/crypto/openssl/crypto/mem.c                                1.2.14.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                     1.2.14.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                 1.2.2.1.6.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.26.1
src/crypto/openssl/ssl/ssl.h                                1.2.2.1.6.1
src/crypto/openssl/ssl/ssl_err.c                            1.2.2.1.6.1
src/crypto/openssl/ssl/s3_enc.c                             1.2.2.1.4.1
src/crypto/openssl/ssl/s3_srvr.c                            1.3.2.4.2.2
src/crypto/openssl/ssl/ssl3.h                               1.2.2.1.6.1
RELENG_8_2
src/UPDATING                                            1.632.2.19.2.10
src/sys/conf/newvers.sh                                  1.83.2.12.2.13
src/crypto/openssl/crypto/buffer/buffer.c                       1.2.8.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c            1.1.1.13.10.1.2.1
src/crypto/openssl/crypto/mem.c                                 1.2.8.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                      1.2.8.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                 1.2.2.1.4.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.18.1
src/crypto/openssl/ssl/ssl.h                                1.2.2.1.4.1
src/crypto/openssl/ssl/ssl_err.c                            1.2.2.1.4.1
src/crypto/openssl/ssl/s3_enc.c                             1.2.2.1.2.1
src/crypto/openssl/ssl/s3_srvr.c                            1.3.2.3.2.2
src/crypto/openssl/ssl/ssl3.h                               1.2.2.1.4.1
RELENG_8_1
src/UPDATING                                            1.632.2.14.2.13
src/sys/conf/newvers.sh                                  1.83.2.10.2.14
src/crypto/openssl/crypto/buffer/buffer.c                       1.2.6.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c                1.1.1.13.16.1
src/crypto/openssl/crypto/mem.c                                 1.2.6.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                      1.2.6.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                 1.2.2.1.2.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.16.1
src/crypto/openssl/ssl/ssl.h                                1.2.2.1.2.1
src/crypto/openssl/ssl/ssl_err.c                            1.2.2.1.2.1
src/crypto/openssl/ssl/s3_enc.c                                 1.2.6.1
src/crypto/openssl/ssl/s3_srvr.c                            1.3.2.2.2.2
src/crypto/openssl/ssl/ssl3.h                               1.2.2.1.2.1
RELENG_9
src/crypto/openssl/crypto/buffer/buffer.c                      1.2.10.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c                      1.2.2.1
src/crypto/openssl/crypto/mem.c                                1.2.10.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                     1.2.10.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                     1.3.2.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.22.1
src/crypto/openssl/ssl/ssl.h                                    1.3.2.1
src/crypto/openssl/ssl/ssl_err.c                                1.3.2.1
src/crypto/openssl/ssl/s3_enc.c                                 1.3.2.1
src/crypto/openssl/ssl/s3_srvr.c                                1.7.2.2
src/crypto/openssl/ssl/ssl3.h                                   1.3.2.1
RELENG_9_0
src/UPDATING                                              1.702.2.4.2.4
src/sys/conf/newvers.sh                                    1.95.2.4.2.6
src/crypto/openssl/crypto/buffer/buffer.c                      1.2.12.2
src/crypto/openssl/crypto/pkcs7/pk7_doit.c                      1.2.4.1
src/crypto/openssl/crypto/mem.c                                1.2.12.1
src/crypto/openssl/crypto/x509v3/pcy_map.c                     1.2.12.1
src/crypto/openssl/crypto/x509v3/pcy_tree.c                     1.3.4.1
src/crypto/openssl/crypto/asn1/a_d2i_fp.c                  1.1.1.3.24.1
src/crypto/openssl/ssl/ssl.h                                    1.3.4.1
src/crypto/openssl/ssl/ssl_err.c                                1.3.4.1
src/crypto/openssl/ssl/s3_enc.c                                 1.3.4.1
src/crypto/openssl/ssl/s3_srvr.c                                1.7.4.2
src/crypto/openssl/ssl/ssl3.h                                   1.3.4.1
– ————————————————————————-

Subversion:

Branch/path                                                      Revision
– ————————————————————————-
stable/7/                                                         r236304
releng/7.4/                                                       r236304
stable/8/                                                         r236304
releng/8.3/                                                       r236304
releng/8.2/                                                       r236304
releng/8.1/                                                       r236304
stable/9/                                                         r236304
releng/9.0/                                                       r236304
– ————————————————————————-

VII. References

http://www.openssl.org/news/secadv_20120419.txt
http://www.openssl.org/news/secadv_20120312.txt
http://www.openssl.org/news/secadv_20120104.txt
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-4576
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-4619
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-4109
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0884
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2110
http://lists.openwall.net/full-disclosure/2012/04/19/4

The latest revision of this advisory is available at
http://security.FreeBSD.org/advisories/FreeBSD-SA-12:01.openssl.asc

======================================================================
FreeBSD-SA-12:02.crypt                                      Security Advisory                                The FreeBSD Project

Topic:          Incorrect crypt() hashing

Category:       core
Module:         libcrypt
Announced:      2012-05-30
Credits:        Rubin Xu, Joseph Bonneau, Donting Yu
Affects:        All supported versions of FreeBSD.
Corrected:      2012-05-30 12:01:28 UTC (RELENG_7, 7.4-STABLE)
2012-05-30 12:01:28 UTC (RELENG_7_4, 7.4-RELEASE-p8)
2012-05-30 12:01:28 UTC (RELENG_8, 8.3-STABLE)
2012-05-30 12:01:28 UTC (RELENG_8_3, 8.3-RELEASE-p2)
2012-05-30 12:01:28 UTC (RELENG_8_2, 8.2-RELEASE-p8)
2012-05-30 12:01:28 UTC (RELENG_8_1, 8.1-RELEASE-p10)
2012-05-30 12:01:28 UTC (RELENG_9, 9.0-STABLE)
2012-05-30 12:01:28 UTC (RELENG_9_0, 9.0-RELEASE-p2)
CVE Name:       CVE-2012-2143

For general information regarding FreeBSD Security Advisories,
including descriptions of the fields above, security branches, and the
following sections, please visit <URL:http://security.FreeBSD.org/>.

I.   Background

The crypt(3) function performs password hashing with additional code added
to deter key search attempts.

II.  Problem Description

There is a programming error in the DES implementation used in crypt()
when handling input which contains characters that can not be represented
with 7-bit ASCII.

III. Impact

When the input contains characters with only the most significant bit set
(0x80), that character and all characters after it will be ignored.

IV.  Workaround

No workaround is available, but systems not using crypt(), or which only
use it to handle 7-bit ASCII are not vulnerable.  Note that, because
DES does not have the computational complexity to defeat brute force
search on modern computers, it is not recommended for new applications.

V.   Solution

Perform one of the following:

1) Upgrade your vulnerable system to 7-STABLE, 8-STABLE, or 9-STABLE,
or to the RELENG_7_4, RELENG_8_3, RELENG_8_2, RELENG_8_1, or RELENG_9_0
security branch dated after the correction date.

2) To update your vulnerable system via a source code patch:

The following patches have been verified to apply to FreeBSD 7.4,
8.3, 8.2, 8.1 and 9.0 systems.

a) Download the relevant patch from the location below, and verify the
detached PGP signature using your PGP utility.

# fetch http://security.FreeBSD.org/patches/SA-12:02/crypt.patch
# fetch http://security.FreeBSD.org/patches/SA-12:02/crypt.patch.asc

# cd /usr/src
# patch < /path/to/patch
# cd /usr/src/lib/libcrypt
# make obj && make depend && make && make install

NOTE: On the amd64 platform, the above procedure will not update the
lib32 (i386 compatibility) libraries.  On amd64 systems where the i386
compatibility libraries are used, the operating system should instead
be recompiled as described in
<URL:http://www.FreeBSD.org/handbook/makeworld.html>

3) To update your vulnerable system via a binary patch:

Systems running 7.4-RELEASE, 8.3-RELEASE, 8.2-RELEASE, 8.1-RELEASE,
or 9.0-RELEASE on the i386 or amd64 platforms can be updated via the
freebsd-update(8) utility:

# freebsd-update fetch
# freebsd-update install

VI.  Correction details

The following list contains the revision numbers of each file that was
corrected in FreeBSD.

CVS:

Branch                                                           Revision
Path
– ————————————————————————-
RELENG_7
src/secure/lib/libcrypt/crypt-des.c                           1.16.24.1
RELENG_7_4
src/UPDATING                                            1.507.2.36.2.10
src/sys/conf/newvers.sh                                  1.72.2.18.2.13
src/secure/lib/libcrypt/crypt-des.c                           1.16.40.2
RELENG_8
src/secure/lib/libcrypt/crypt-des.c                           1.16.36.2
RELENG_8_3
src/UPDATING                                             1.632.2.26.2.4
src/sys/conf/newvers.sh                                   1.83.2.15.2.6
src/secure/lib/libcrypt/crypt-des.c                       1.16.36.1.8.2
RELENG_8_2
src/UPDATING                                            1.632.2.19.2.10
src/sys/conf/newvers.sh                                  1.83.2.12.2.13
src/secure/lib/libcrypt/crypt-des.c                       1.16.36.1.6.2
RELENG_8_1
src/UPDATING                                            1.632.2.14.2.13
src/sys/conf/newvers.sh                                  1.83.2.10.2.14
src/secure/lib/libcrypt/crypt-des.c                       1.16.36.1.4.2
RELENG_9
src/secure/lib/libcrypt/crypt-des.c                           1.16.42.2
RELENG_9_0
src/UPDATING                                              1.702.2.4.2.4
src/sys/conf/newvers.sh                                    1.95.2.4.2.6
src/secure/lib/libcrypt/crypt-des.c                       1.16.42.1.2.2
– ————————————————————————-

Subversion:

Branch/path                                                      Revision
– ————————————————————————-
stable/7/                                                         r236304
releng/7.4/                                                       r236304
stable/8/                                                         r236304
releng/8.3/                                                       r236304
releng/8.2/                                                       r236304
releng/8.1/                                                       r236304
stable/9/                                                         r236304
releng/9.0/                                                       r236304
– ————————————————————————-

VII. References

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2143

The latest revision of this advisory is available at
http://security.FreeBSD.org/advisories/FreeBSD-SA-12:02.crypt.asc

Share Button