[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

[RFR] ddp://manuals.sgml/securing-howto/pt-br/developer.sgml



Olá pessoal,

Envio em anexo o arquivo para revisão, juntamente com o original em inglês.

Abraço,

-- 
Marcelo G. Santana(darkstar)      GNU/Linux User number #208778
JID:marcelo.santana@jabber.org   GNU Privacy Guard ID: 5BECD54C
Blog:Tempestade de Idéias - http://marcelosantana.wordpress.com
      Projeto Debian Brasil - http://www.debianbrasil.org      
<!-- CVS revision of this document "$Revision: 1.4 $"  -->

<chapt>Developer's Best Practices for OS Security

<!-- This chapter is based on the patch I submitted to the Developer's
     Reference, see #337086: [BPP] Best practices for security design and review -->

<p>This chapter introduces some best secure coding practices for developers writing
Debian packages. If you are really interested in secure coding I recommend
you read David Wheeler's <url id="http://www.dwheeler.com/secure-programs/";
name="Secure Programming for Linux and Unix HOWTO"> and 
<url id="http://www.securecoding.org"; name="Secure Coding: Principles and Practices">
by Mark G. Graff and Kenneth R. van Wyk (O'Reilly, 2003).

<sect id="bpp-devel-design">
   <heading>Best practices for security review and design</heading>

<p>Developers that are packaging software should make a best effort to ensure
that the installation of the software, or its use, does not introduce security
risks to either the system it is installed on or its users.</p>

<p>In order to do so, they should make their best to review the source code of
the package and detect any flaws that might introduce security bugs before 
releasing the software or distributing a new version. It is acknowledged
that the cost of fixing bugs grows for different stages of its development, so
it is easier (and cheaper) to fix bugs when designing than when the software
has been deployed and is in maintenance mode (some studies say that the cost in
this later phase is <strong>sixty</strong> times higher). Although there
are some tools that try to automatically detect these flaws, developers
should strive to learn about the different kind of security flaws in
order to understand them and be able to spot them in the code they (or others)
have written.

<p>The programming bugs
which lead to security bugs typically include: <url
id="http://en.wikipedia.org/wiki/Buffer_overflow"; name="buffer
overflows">,
format string overflows,
heap overflows and
integer overflows (in C/C++ programs), temporary <url
id="http://en.wikipedia.org/wiki/Symlink_race"; name="symlink race
conditions"> (in scripts), <url
id="http://en.wikipedia.org/wiki/Directory_traversal"; name="directory
traversal"> and command injection (in servers) and <url
id="http://en.wikipedia.org/wiki/Cross_site_scripting";
name="cross-site scripting">, and <url
id="http://en.wikipedia.org/wiki/SQL_injection"; name="SQL
injection bugs"> (in the case of web-oriented applications).
For a more complete information on security bugs review
Fortify's <url id="http://vulncat.fortifysoftware.com/"; name="Taxonomy of 
Software Security Errors">.
</p>

<p>Some of these issues might not be easy to spot unless you are an
expert in the programming language the software uses, but some security
problems are easy to detect and fix. For example, finding temporary
race conditions due to misuse of temporary directories can easily be done just by running
<tt>grep -r "/tmp/" .</tt>. Those calls can be reviewed and replace
the hardcoded filenames using temporary directories to calls to either
<prgn>mktemp</prgn> or <prgn>tempfile</prgn> in shell
scripts, <manref name="File::Temp" section="3perl"> in Perl scripts,
or <manref name="tmpfile" section="3"> in C/C++.</p>

<p>There are a set of tools available to assist to the security code review phase.
These include <package>rats</package>, <package>flawfinder</package> and
<package>pscan</package>. For more information, read the 
<url id="http://www.debian.org/security/audit/tools"; name="list of tools used
by the Debian Security Audit Team">.

<p>When packaging software developers have to make sure that they follow
common security principles, including:

<list>

<item>The software runs with the minimum privileges it needs:

<list>
<item>The package does install binaries setuid or setgid.
<prgn>Lintian</prgn> will warn of <url id="
http://lintian.debian.org/reports/Tsetuid-binary.html"; name="setuid">,
<url id="http://lintian.debian.org/reports/Tsetgid-binary.html";
name="setgid"> and <url
id="http://lintian.debian.org/reports/Tsetuid-gid-binary.html";
name="setuid and setgid"> binaries.

<item>The daemons the package provide run with a 
low privilege user (see <ref id="bpp-lower-privs">)

</list>

<item>Programmed (i.e., <prgn>cron</prgn>) tasks running in the
system do NOT run as root or, if they do, do not implement complex
tasks.

</list>

<p>If you have to do any of the above make sure the programs that
might run with higher privileges have been audited for security
bugs. If you are unsure, or need help, contact the <url
id="http://www.debian.org/security/audit/"; name="Debian Security Audit
team">. In the case of setuid/setgid binaries, follow the Debian
policy section regarding 
<url id="http://www.debian.org/doc/debian-policy/ch-files.html#s10.9";
name="permissions and owners">
</p>

<p>For more information, specific to secure programming, make sure you
read (or point your upstream to) <url
id="http://www.dwheeler.com/secure-programs/"; name="Secure Programming
for Linux and Unix HOWTO"> and the <url
id="https://buildsecurityin.us-cert.gov/portal/"; name="Build Security
In"> portal. 
</p>
</sect>

<!-- This should be explained here until #291177 gets fixed and this is
	added to poliy -->
<sect id="bpp-lower-privs">
  <heading>Creating users and groups for software daemons

<p>If your software runs a daemon that does not need root privileges,
you need to create a user for it. There are two kind of Debian users
that can be used by packages: static uids (assigned by
<package>base-passwd</package>, for a list of static users in Debian
see <ref id="faq-os-users">) and dynamic uids in the range assigned
to system users.

<p>In the first case, you need to ask for a user or group id to the
<package>base-passwd</package>. Once the user is available there
the package needs to be distributed including a proper versioned depends to the
<package>base-passwd</package> package.

<p>In the second case, you need to create the system user either in
the <em>preinst</em> or in the <em>postinst</em> and make the package
depend on <tt>adduser (>= 3.11)</tt>.

<p>The following example code creates the user and group the daemon
will run as when the package is installed or upgraded:

<example>
[...]
case "$1" in
  install|upgrade)

  # If the package has default file it could be sourced, so that
  # the local admin can overwrite the defaults

  [ -f "/etc/default/<var>packagename</var>" ] && . /etc/default/<var>packagename</var>

  # Sane defaults:

  [ -z "$SERVER_HOME" ] && SERVER_HOME=<var>server_dir</var>
  [ -z "$SERVER_USER" ] && SERVER_USER=<var>server_user</var>
  [ -z "$SERVER_NAME" ] && SERVER_NAME="<var>Server description</var>"
  [ -z "$SERVER_GROUP" ] && SERVER_GROUP=<var>server_group</var>

  # Groups that the user will be added to, if undefined, then none.
  ADDGROUP=""

  # create user to avoid running server as root
  # 1. create group if not existing
  if ! getent group | grep -q "^$SERVER_GROUP:" ; then
     echo -n "Adding group $SERVER_GROUP.."
     addgroup --quiet --system $SERVER_GROUP 2>/dev/null ||true
     echo "..done"
  fi
  # 2. create homedir if not existing
  test -d $SERVER_HOME || mkdir $SERVER_HOME
  # 3. create user if not existing
  if ! getent passwd | grep -q "^$SERVER_USER:"; then
    echo -n "Adding system user $SERVER_USER.."
    adduser --quiet \
            --system \
            --ingroup $SERVER_GROUP \
            --no-create-home \
            --disabled-password \
            $SERVER_USER 2>/dev/null || true
    echo "..done"
  fi
  # 4. adjust passwd entry
  usermod -c "$SERVER_NAME" \
          -d $SERVER_HOME   \
          -g $SERVER_GROUP  \
             $SERVER_USER
  # 5. adjust file and directory permissions
  if ! dpkg-statoverride --list $SERVER_HOME >/dev/null
  then
      chown -R $SERVER_USER:adm $SERVER_HOME
      chmod u=rwx,g=rxs,o= $SERVER_HOME
  fi
  # 6. Add the user to the ADDGROUP group
  if test -n $ADDGROUP
  then
      if ! groups $SERVER_USER | cut -d: -f2 | \
         grep -qw $ADDGROUP; then
           adduser $SERVER_USER $ADDGROUP
      fi
  fi
  ;;
  configure)

[...]
</example>

<p>You have to make sure that the init.d script file:

<list>
<item>Starts the daemon dropping privileges: if the software does not
do the <manref name="setuid" section="2"> or <manref name="seteuid"
section="2"> call itself, you can use the <tt>--chuid</tt>
call of <prgn>start-stop-daemon</prgn>.

<item>Stops the daemon only if the user id matches, you can use the 
<prgn>start-stop-daemon</prgn> <tt>--user</tt> option
for this.

<item>Does not run if either the user or the group do not exist:
<example>
  if ! getent passwd | grep -q "^<var>server_user</var>:"; then
     echo "Server user does not exist. Aborting" >&2
     exit 1
  fi
  if ! getent group | grep -q "^<var>server_group</var>:" ; then
     echo "Server group does not exist. Aborting" >&2
     exit 1
  fi
</example>

</list>

<p>If the package creates the system user it can remove it when it is
purged in its <em>postrm</em>. This has some drawbacks, however.
For example, files created by it will be orphaned
and might be taken over by a new system user in the future if it is assigned
the same uid<footnote>Some relevant threads discussing these drawbacks
include <url id="http://lists.debian.org/debian-mentors/2004/10/msg00338.html";>
and <url id="http://lists.debian.org/debian-devel/2004/05/msg01156.html";>
</footnote>. Consequently, removing system users on purge is
not yet mandatory and depends on the package needs. If unsure, this
action could be handled by asking the administrator for the prefered action
when the package is installed (i.e. through <prgn>debconf</prgn>).

<p>The following example code<footnote><p>This might eventually 
be introduced as a <prgn>dh_adduser</prgn> in debhelper. See
<url id="http://bugs.debian.org/81697"; name="#81967">,
<url id="http://bugs.debian.org/291177"; name="#291177"> and
<url id="http://bugs.debian.org/118787"; name="#118787">.</p></footnote>
removes the user and groups created before only, and only if, the uid is in the
range of dynamic assigned system uids and the gid is belongs to a system group:

<example>
case "$1" in
 purge)
[...]
   # find first and last SYSTEM_UID numbers
   for LINE in `grep SYSTEM_UID /etc/adduser.conf | grep -v "^#"`; do
      case $LINE in
         FIRST_SYSTEM_UID*)
           FIST_SYSTEM_UID=`echo $LINE | cut -f2 -d '='`
           ;;
         LAST_SYSTEM_UID*)
           LAST_SYSTEM_UID=`echo $LINE | cut -f2 -d '='`
           ;;
         *)
           ;;
         esac
   done
   # Remove system account if necessary
   CREATEDUSER="<var>server_user</var>"
   if [ -n "$FIST_SYSTEM_UID" ] && [ -n "$LAST_SYSTEM_UID" ]; then
    if USERID=`getent passwd $CREATEDUSER | cut -f 3 -d ':'`; then
      if [ -n "$USERID" ]; then
        if [ "$FIST_SYSTEM_UID" -le "$USERID" ] && \
           [ "$USERID" -le "$LAST_SYSTEM_UID" ]; then
              echo -n "Removing $CREATEDUSER system user.."
              deluser --quiet $CREATEDUSER || true
              echo "..done"
        fi
      fi
    fi
  fi
  # Remove system group if necessary
  CREATEDGROUP=<var>server_group</var>
  FIRST_USER_GID=`grep ^USERS_GID /etc/adduser.conf | cut -f2 -d '='`
  if [ -n "$FIST_USER_GID" ] then
    if GROUPGID=`getent group $CREATEDGROUP | cut -f 3 -d ':'`; then
      if [ -n "$GROUPGID" ]; then
        if [ "$FIST_USER_GID" -gt "$GROUPGID" ]; then
          echo -n "Removing $CREATEDGROUP group.."
          delgroup --only-if-empty $CREATEDGROUP || true
          echo "..done"
        fi
      fi
    fi
  fi
[...]
</example>

<p>Running programs with a user with limited privileges makes sure
that any security issue will not be able to damage the full system.
It also follows the principle of <em>least privilege</em>. Also consider you can
limit privileges in programs through other mechanisms besides running as
non-root<footnote><p>You can even provide a SELinux policy for
it</p></footnote>. For more information, read the <url
id="http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/minimize-privileges.html";
name="Minimize Privileges"> chapter of the <em>Secure Programming for
Linux and Unix HOWTO</em> book.

</sect>

</chapt>
<!-- CVS revision of original english document "1.4" -->
<!-- original version: 1.4 -->
<!-- last translator: Marcelo Santana <marcgsantana@yahoo.com.br> -->

<chapt>Melhores Práticas do Desenvolvedor para Segurança do SO

<!-- This chapter is based on the patch I submitted to the Developer's
     Reference, see #337086: [BPP] Best practices for security design and review -->

<p>Este capítulo introduz algumas das melhores práticas de programação para
desenvolvedores escreverem pacotes Debian.  Se você estiver realmente interessado
em programação segura eu recomendo que você leia
<url id="http://www.dwheeler.com/secure-programs/";
name="HOWTO Programação Segura para Linux e Unix"> de David Wheeler e <url
id="http://www.securecoding.org"; name="Codificação Segura: Princípios e Práticas">
de Mark G. Graff e Kenneth R. van Wyk (O'Reilly, 2003).

<sect id="bpp-devel-design">
   <heading>Melhores práticas para o projeto e revisão de segurança</heading>

<p>Desenvolvedores que estão empacotando software devem fazer um esforço
para garantir que a instalação do software, ou seu uso, não introduza riscos
de segurança quer ao sistema onde esteja instalado ou aos seus usuários.</p>

<p>Para isso, eles devem fazer o melhor esforço para revisar o código fonte do
pacote e detectar eventuais falhas que possam introduzir erros de segurança antes
do lançamento do software ou distribuição de uma nova versão. Sabe-se que o
custo de correção de erros cresce em diferentes fases do seu desenvolvimento,
por isso é mais fácil (e barato) corrigir erros no momento do projeto do que
quando o software foi implantado e está em modo de manutenção (alguns estudos
dizem que o custo nesta fase posterior é <strong>sessenta</strong> vezes maior).
Apesar de existirem algumas ferramentas que tentam detectar automaticamente
estas falhas, os programadores deveriam se esforçar para aprender sobre os
diferentes tipos de falhas de segurança a fim de entendê-las e ser capazes de
identificá-las no código que eles (ou outros) tenham escrito.

<p>Os erros de programação
levam a erros de segurança que normalmente incluem: <url
id="http://en.wikipedia.org/wiki/Buffer_overflow"; name="buffer
overflows">,
"format string overflow",
"heap overflows" e
"integer overflows" (em programas C/C++), provisório <url
id="http://en.wikipedia.org/wiki/Symlink_race"; name="symlink race
conditions"> (em scripts), <url
id="http://en.wikipedia.org/wiki/Directory_traversal"; name="diretório
de transferência"> e injeção de comando (em servidores) e <url
id="http://en.wikipedia.org/wiki/Cross_site_scripting";
name="cross-site scripting">, e <url
id="http://en.wikipedia.org/wiki/SQL_injection"; name="erros
de SQL injection"> (no caso de aplicações orientadas à web).
Para informações mais completas sobre revisão de erros de segurança
<url id="http://vulncat.fortifysoftware.com/"; name="Taxonomia dos 
Erros de Segurança de Software"> do Fortify.
</p>

<p>Algumas destas questões poderão não ser fáceis de identificar a menos que
você seja um perito na linguagem de programação que o software utiliza,
mas alguns problemas de segurança são fáceis de detectar e corrigir. Por
exemplo, encontrar "race conditions" temporárias devido ao mau uso de diretórios
temporários pode facilmente ser feito apenas executando <tt>grep -r "/tmp/" .</tt>.
Estas chamadas podem ser revistas e substituídos
os nomes dos arquivos codificados usando diretórios temporários para chamadas
a qualquer <prgn>mktemp</prgn> ou <prgn>tempfile</prgn> em scripts shell,
<manref name="File::Temp" section="3perl"> em scripts Perl,
ou <manref name="tmpfile" section="3"> em C/C++.</p>

<p>Existe um conjunto de ferramentas disponíveis para auxiliar na fase de
revisão da segurança do código.
Estas incluem <package>rats</package>, <package>flawfinder</package> e
<package>pscan</package>. Para maiores informações, leia a 
<url id="http://www.debian.org/security/audit/tools"; name="lista de ferramentas
usadas pelo Time de Auditoria de Segurança Debian">.

<p>Quando empacotam software os desenvolvedores têm que se certificar que
eles sigam princípios de segurança comuns, incluindo:

<list>

<item>O software é executado com os privilégios mínimos que necessita:

<list>
<item>O pacote faz instalar binários setuid ou setgid.
<prgn>Lintian</prgn> avisará sobre <url id="
http://lintian.debian.org/reports/Tsetuid-binary.html"; name="setuid">,
<url id="http://lintian.debian.org/reports/Tsetgid-binary.html";
name="setgid"> e <url
id="http://lintian.debian.org/reports/Tsetuid-gid-binary.html";
name="setuid and setgid"> binários.

<item>Os daemons que o pacote fornece executam com um 
usuário de baixo privilégio (veja <ref id="bpp-lower-privs">)

</list>

<item>Tarefas (ex., <prgn>cron</prgn>) programadas executando no
sistema N�O executam como root ou, se elas executam, não implementam
tarefas complexas.

</list>

<p>Se você tiver que fazer alguma das situações acima certifique-se
que os programas que possam executar com privilégios mais elevados
foram auditados com relação a erros de segurança. Se você está
inseguro, ou necessita de ajuda, entre em contato com o <url
id="http://www.debian.org/security/audit/"; name="time de Auditoria
de Segurança Debian">. No caso de binários setuid/setgid ,
siga a seção do política Debian relativa a 
<url id="http://www.debian.org/doc/debian-policy/ch-files.html#s10.9";
name="permissões e proprietários">
</p>

<p>Para maiores informações, específicas sobre programação segura,
certifique-se de ler (ou indique ao desenvolvedor original) <url
id="http://www.dwheeler.com/secure-programs/"; name="HOWTO Programação
Segura para Linux e Unix"> e o portal <url
id="https://buildsecurityin.us-cert.gov/portal/"; name="Build Security
In">. 
</p>
</sect>

<!-- This should be explained here until #291177 gets fixed and this is
	added to poliy -->
<sect id="bpp-lower-privs">
  <heading>Criando usuários e grupos para deamons de software

<p>Se seu programa executa um deamon que não precisa de privilégios de
root, você precisa criar um usuário para isto. Existem dois tipos de
usuários Debian que podem ser usados por pacotes: uids estáticas
(atribuídas pelo <package>base-passwd</package>, para uma lista de
usuários estáticos no Debian veja <ref id="faq-os-users">) e
uids dinâmicas ao alcance atribuídas para usuários de sistema.

<p>No primeiro caso, você deve pedir uma id ao <package>base-passwd</package>.
Uma vez que o usuário esteja disponível o pacote precisa ser distribuído,
incluindo as versões corretas das dependências para o pacote
<package>base-passwd</package>.

<p>No segundo caso, você precisa criar o usuário de sistema quer no
<em>preinst</em> ou no <em>postinst</em> e fazer o pacote
depender do <tt>adduser (>= 3.11)</tt>.

<p>O seguinte código exemplo cria o usuário e grupo, o deamon
executará assim que o pacote for instalado ou atualizado:

<example>
[...]
case "$1" in
  install|upgrade)

  # Se o pacote tiver arquivo padrão ele será fornecido, de modo que
  # o admin local possa sobrescrever os padrões

  [ -f "/etc/default/<var>packagename</var>" ] && . /etc/default/<var>packagename</var>

  # Padrões sane:

  [ -z "$SERVER_HOME" ] && SERVER_HOME=<var>server_dir</var>
  [ -z "$SERVER_USER" ] && SERVER_USER=<var>server_user</var>
  [ -z "$SERVER_NAME" ] && SERVER_NAME="<var>Server description</var>"
  [ -z "$SERVER_GROUP" ] && SERVER_GROUP=<var>server_group</var>

  # Grupos ao qual o usuário será adicionado, se não definido, então none.
  ADDGROUP=""

  # criar usuário para evitar o uso de servidor como root
  # 1. cria grupo se não existente
  if ! getent group | grep -q "^$SERVER_GROUP:" ; then
     echo -n "Adicionando grupo $SERVER_GROUP.."
     addgroup --quiet --system $SERVER_GROUP 2>/dev/null ||true
     echo "..feito"
  fi
  # 2. cria homedir se não existente
  test -d $SERVER_HOME || mkdir $SERVER_HOME
  # 3. cria usuário se não existente
  if ! getent passwd | grep -q "^$SERVER_USER:"; then
    echo -n "Adicionando usuário de sistema $SERVER_USER.."
    adduser --quiet \
            --system \
            --ingroup $SERVER_GROUP \
            --no-create-home \
            --disabled-password \
            $SERVER_USER 2>/dev/null || true
    echo "..feito"
  fi
  # 4. ajusta entrada passwd
  usermod -c "$SERVER_NAME" \
          -d $SERVER_HOME   \
          -g $SERVER_GROUP  \
             $SERVER_USER
  # 5. ajusta premissões de arquivo e diretório
  if ! dpkg-statoverride --list $SERVER_HOME >/dev/null
  then
      chown -R $SERVER_USER:adm $SERVER_HOME
      chmod u=rwx,g=rxs,o= $SERVER_HOME
  fi
  # 6. Adiciona o usuário ao grupo ADDGROUP
  if test -n $ADDGROUP
  then
      if ! groups $SERVER_USER | cut -d: -f2 | \
         grep -qw $ADDGROUP; then
           adduser $SERVER_USER $ADDGROUP
      fi
  fi
  ;;
  configure)

[...]
</example>

<p>Você tem que se certificar que o arquivo script do init.d:

<list>
<item>Inicia o daemon bloqueando privilégios: se o programa não
faz o <manref name="setuid" section="2"> ou <manref name="seteuid"
section="2"> chama ele mesmo, você pode usar a <tt>--chuid</tt>
chamada de <prgn>start-stop-daemon</prgn>.

<item>Pára o deamon apenas se o id do usuário for igual, você
pode usar a opção <prgn>start-stop-daemon</prgn> <tt>--user</tt>
para isso.

<item>Não executa caso não exista nem usuário nem grupo:
<example>
  if ! getent passwd | grep -q "^<var>server_user</var>:"; then
     echo "Usuário do servidor não existe. Abortando" >&2
     exit 1
  fi
  if ! getent group | grep -q "^<var>server_group</var>:" ; then
     echo "Grupo do servidor não existe. Abortando" >&2
     exit 1
  fi
</example>

</list>

<p>Se o pacote cria o usuário de sistema ele pode removê-lo quando
for feito o purge do mesmo no <em>postrm</em>. Isso tem algumas
desvantagens, entretanto. Por exemplo, arquivos criados por ele
ficarão órfãos e poderão ser assumidos por um novo usuário de sistema
no futuro caso ele seja atribuído com a mesma uid 
<footnote>Algumas threads relevantes discutem essas desvantagens
incluindo <url id="http://lists.debian.org/debian-mentors/2004/10/msg00338.html";>
e <url id="http://lists.debian.org/debian-devel/2004/05/msg01156.html";>
</footnote>. Conseqüentemente, a remoção de usuários de sistema com purge
ainda não é obrigatória e depende das necessidades do pacote. Se estiver
inseguro, esta ação poderia ser tratada perguntando ao administrador qual
a ação preferida quando o pacote for instalado
(ex. através do <prgn>debconf</prgn>).

<p>O seguinte código exemplo<footnote><p>Esse poderia eventualmente
ser introduzido como um <prgn>dh_adduser</prgn> no debhelper. Veja
<url id="http://bugs.debian.org/81697"; name="#81967">,
<url id="http://bugs.debian.org/291177"; name="#291177"> e
<url id="http://bugs.debian.org/118787"; name="#118787">.</p></footnote>
remove o usuário e grupos criados antes apenas, e apenas se, a uid estiver
na faixa das uids do sistema de atribuição dinâmico e a gid pertencer a
um grupo de sistema:

<example>
case "$1" in
 purge)
[...]
   # encontra os primeiros e últimos números SYSTEM_ID
   for LINE in `grep SYSTEM_UID /etc/adduser.conf | grep -v "^#"`; do
      case $LINE in
         FIRST_SYSTEM_UID*)
           FIST_SYSTEM_UID=`echo $LINE | cut -f2 -d '='`
           ;;
         LAST_SYSTEM_UID*)
           LAST_SYSTEM_UID=`echo $LINE | cut -f2 -d '='`
           ;;
         *)
           ;;
         esac
   done
   # Remove conta de sistema se necessário
   CREATEDUSER="<var>server_user</var>"
   if [ -n "$FIST_SYSTEM_UID" ] && [ -n "$LAST_SYSTEM_UID" ]; then
    if USERID=`getent passwd $CREATEDUSER | cut -f 3 -d ':'`; then
      if [ -n "$USERID" ]; then
        if [ "$FIST_SYSTEM_UID" -le "$USERID" ] && \
           [ "$USERID" -le "$LAST_SYSTEM_UID" ]; then
              echo -n "Removendo usuário de sistema $CREATEDUSER.."
              deluser --quiet $CREATEDUSER || true
              echo "..feito"
        fi
      fi
    fi
  fi
  # Remove grupo de sistema se necessário
  CREATEDGROUP=<var>server_group</var>
  FIRST_USER_GID=`grep ^USERS_GID /etc/adduser.conf | cut -f2 -d '='`
  if [ -n "$FIST_USER_GID" ] then
    if GROUPGID=`getent group $CREATEDGROUP | cut -f 3 -d ':'`; then
      if [ -n "$GROUPGID" ]; then
        if [ "$FIST_USER_GID" -gt "$GROUPGID" ]; then
          echo -n "Removendo grupo $CREATEDGROUP.."
          delgroup --only-if-empty $CREATEDGROUP || true
          echo "..feito"
        fi
      fi
    fi
  fi
[...]
</example>

<p>Executando programas como um usuário com privilégios limitados
asseguramos que qualquer problema de segurança não será capaz de danificar
o sistema todo. Isso segue o princípio do <em>menor privilégio</em>. Também
considere que você pode limitar privilégios em programas através de outros
mecanismos além da execução como não root<footnote><p>Você pode até proporcionar
uma política SELinux para eles</p></footnote>. Para mais informações, leia o
<url id="http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/minimize-privileges.html";
name="Minimize Privilégios"> capítulo do livro <em>HOWTO Programação Segura
para Linux e Unix</em>.

</sect>

</chapt>

Reply to: