Rss

  • youtube
  • linkedin
  • google

Set up mail server on Ubuntu Server

RedHat discontinued the Centos and left a lot of people like me accustomed to the line derived from the RHEL orphaned from a stable, RPM-based Linux server.

And what does that have to do with this tutorial? Direct response: ;Para mim tudo”;.

I was forced to migrate my CentOS server 8 for another distrô available in VPSs da OVH e consequentemente reconfigurar tudo o que já estava em “;cruise flight; and that includes the mail server that I even wrote a tutorial. To maintain tradition, according to I'm going to I've been running the steps of the configuration I write the tutorial.



Continue Reading >>

Chrome freezing on Ubuntu 22.02 Jammy Jellyfish

I’ve updated recently my Laptop with Ubuntu from 20.02 to 22.02 through apt in command line and after did it, my Chrome installed has a annoyng behavior. Every time that a download modal appears to save attachments or even to upload a file, Chrome stops working, freezing all tabs and menus.

Its possible to quit on right click on favorites or dock and reopened but the issue keeps occuring.

After a lot of searches I found this page and this comment and did the solution explained there and finally the problem was solved until now.

The solution

Just turn off input feedback sounds.

You can do this through command line:

$ dconf write /org/gnome/desktop/sound/input-feedback-sounds false

Or using dconf-editor

I hope that help someone!

Codigo de validação de CPF para Javascript

O código abaixo é de uma função em Javascript otimizada para ter o menor numero de complexidade ciclomática linhas que consegui baseado na explicação presente no artigo Algoritimo de validação de CPF brasileiro – Cadastro de Pessoa Física. Ele tem uma ligeira alteração no momento do cálculo do segundo digitido verificador. Ao invés de começar pelo segundo algarismo, o codigo começa pelo primeiro e usa o valor 11 como multiplicador. Outra alteração visivel é que para evitar a necessidade de comparação para saber se estamos no nono e decimo digitos, atribuo o valor zero ao ultimo elemento (indice 10) para reduzir mais uma comparação.

O algoritmo utilizado é o método 1 explicado no artigo e há um pequeno truque para evitar a comparação com o resto igual a 10 que é fazer o módulo de 10 do resto.

   // Codigo que valida um CPF informado quanto a validade de seus dígitos verificadores.

const validarCpf = (cpf) => {
  if (cpf.length !== 11) { // Supõe-se já vir filtrado o valor
    return false;
  }
  let elementos = cpf.split(''); // convertendo a string em array
  elementos[10] = 0; // Forçando ao valor da ultima multiplicacao ser zero
  let somaA = 0;
  let somaB = 0;

  elementos.reduce(function(i, valor, indice) {
    let multiplicador = 11 - indice;
    somaB += (valor * multiplicador);
    somaA += (valor * (multiplicador > 2 ? multiplicador - 1 : 0));
  }, somaA);
  let moduloA = ((somaA * 10) % 11) % 10;
  let moduloB = ((somaB * 10) % 11) % 10;
  return cpf.replace(/\d{9}(\d{2})$/g, '$1') == ("" + moduloA + moduloB);
}

Você pode testar esse código aqui.

Codigo de validação de CPF para PHP

O código abaixo é de uma função em PHP otimizada para ter o menor numero de complexidade ciclomática que consegui baseado na explicação presente no artigo Algoritimo de validação de CPF brasileiro – Cadastro de Pessoa Física. Ele tem uma ligeira alteração no momento do cálculo do segundo digitido verificador. Ao invés de começar pelo segundo algarismo, o codigo começa pelo primeiro e usa o valor 11 como multiplicador. Outra alteração visivel é que para evitar a necessidade de comparação para saber se estamos no nono e decimo digitos, atribuo o valor zero ao ultimo elemento (indice 10) para reduzir mais uma comparação.

O algoritmo utilizado é o método 1 explicado no artigo citado anteriormente e há um pequeno truque para evitar a comparação com o resto igual a 10 que é fazer o módulo de 10 do resto.

   // Codigo que valida um CPF informado quanto a validade de seus dígitos verificadores.

   /**
     * 
     * Verifica se um CPF é válido
     * @author Marcos Regis <marcos@marcosregis.com>
     * @param  string $cpf
     * @return bool
     */
    function validar(string $cpf): bool
    {
        if (strlen($cpf) != 11) {
            return false;
        }
        $elementos = (array)str_split($cpf);
        $elementos[10] = 0; // Reduz uma comparação no calculo de $somaB
        $somaA = 0;
        $somaB = 0;
        foreach ($elementos as $indice => $elemento) {
            $multiplicador = count($elementos) - $indice;
            $somaA += (int)$elemento * (int)($multiplicador > 2 ? $multiplicador - 1 : 0);
            $somaB += (int)$elemento * (int)$multiplicador;
        }

        $moduloA = (($somaA * 10) % 11) % 10;
        $moduloB = (($somaB * 10) % 11) % 10;

        return preg_replace('#\d{9}(\d{2})$#', '$1', $cpf) == $moduloA . $moduloB;
    }

Você pode testar esse código aqui.

Algoritimo de validação de CPF brasileiro – Cadastro de Pessoa Física

Neste artigo explicarei passo a passo na transformação de um algorítimo de verificação da validade de um CPF para código em PHP.

Se você já conhece o algorítmo e quer ir direto aos códigos disponíveis, clique aqui.

Mas o que é o CPF?

CPF é o acrônimo para Cadastro de Pessoa Física. Ele é um número de documento brasileiro atualmente gerenciado e emitido pela Receita Federal. Todo brasileiro tem o direito (ou o dever) de ter um e somente com ele é possível ter acesso a serviços bancários, matricular-se em cursos de graduação públicos, assumir cargo através de concurso público, ter cartão de crédito, entre outros exemplos.

Composição do CPF

O CPF é composto de onze algarismos, sendo que os ultimos três algarismos possuem significados que explicaremos a seguir.

O nono dígito, lendo da esquerda para a direita, indica a Região Fiscal onde ele foi emitido. Há dez regiões para os algarismo de zero a nove conforme tabela abaixo.

1 – DF, GO, MS, MT e TO
2 – AC, AM, AP, PA, RO e RR
3 – CE, MA e PI
4 – AL, PB, PE, RN
5 – BA e SE
6 – MG
7 – ES e RJ
8 – SP
9 – PR e SC
0 – RS

Os primeiro oito algarismos são o numero base.

Os ultimos dois algarismo são os dígitos verificadores.

Esses dígitos são gerados a partir de cálculos dos nove primeiros algarismos de acordo com a seguintes regras:

Primeiro Dígito verificador

Para o primeiro dígito, pegamos os 8 primeiros algarismos e multiplicamos cada um deles por um número iniciado em 10 e a medida em que vamos avançando para a direita, diminuimos em 1 esse multiplicador e somamos todos os resultados.

Para melhor entendimento, tomemos 123.456.789-XY como exemplo de CPF a ter o digito XY calculado.

1 x 10 = 10
2 x 9 = 18
3 x 8 = 24
4 x 7 = 28
5 x 6 = 30
6 x 5 = 30
7 x 4 = 28
8 x 3 = 24
9 x 2 = 18
Somando 10 + 18 + 24 + 28 + 30 + 30 + 28 + 24 + 18 temos 210.

Agora, com o total obtido temos duas forma de chegar ao digito verificador.

Método 1

Multiplicamos 210 por 10, dividimos por 11 e pegamos o resto.

Temos então: 210 x 10 = 2.100

2.100 / 11 = 190 com resto 10.

Se o resto for 10 o dígito verificador é zero, do contrário, o resto é o dígito verificador.

No nosso caso, como o resto é igual a 10 o primeiro dígito será 0 (zero).

Método 2

Obtemos o resto da divisão de 210 por 11.

Temos então: 210 / 11 é igual a 19 com resto 1.

Aqui temos uma regra para quando o resto for 0 (zero) ou 1 (um). Quando isso acontece o dígito verificador é zero, do contrário subtraimos o resto de 11 para obter o dígito verificador.

Para o nosso caso, como temos resto 1, o nosso primeiro dígito verificador será 0 (zero).

Segundo dígito verificador

Para obter o segundo dígito verificador, acrescentamos o primeiro dígito verificador aos 9 algarismos iniciais e fazemos novamente o mesmo processo feito para o primeiro dígito, com a diferença de que agora iniciamos a partir do segundo dígito.

Nosso CPF já está com o valor 123.456.789-0X e as operações necessárias estão abaixo.
2 x 10 = 20
3 x 9 = 27
4 x 8 = 32
5 x 7 = 35
6 x 6 = 36
7 x 5 = 35
8 x 4 = 32
9 x 3 = 27
0 x 2 = 0
Somando 20 + 27 + 32 + 35 + 36 + 35 + 32 + 27 + 0 temos 244.

Agora, com o total obtido devemos usar uma das duas formas já explicadas para chegar ao dígito verificador.

Método 1

Multiplicamos 244 por 10, dividimos por 11 e pegamos o resto.

Temos então: 244 x 10 = 2.440

2.440 / 11 = 221 com resto 9.

Se o resto for 10 o dígito verificador é zero, do contrário, o resto é o dígito verificador e no nosso caso temos 9 como segundo dígito verificador.

Método 2

Obtemos o resto da divisão de 244 por 11.

Temos então: 244 / 11 é igual a 22 com resto 2.

Lembrando que temos uma regra para quando o resto for 0 (zero) ou 1 (um) o dígito verificador é zero.

Caso seja maior que 1 subtraimos esse valor de 11 para obter o dígito verificador.

Para o nosso caso, temos 11 – 2 = 9 como nosso segundo dígito verificador que é o mesmo valor obtido no método 1.

CPF tem um limite para emissão?

Na teoria, podemos ter até 10^8 ou 100.000.000 (cem milhões) de combinações possíveis para cada região. Na prática temos um pouco menos devido ao não uso de algarismos repetidos, por exemplo. Embora pareça um número bem grande, ele deverá ser remodelado em algum momento, já que não pode ser reutilizado mesmo quando uma pessoa falece.

Supondo que já existam na região 8 (estadao de São Paulo) cerca de 40 milhões de CPFs emitidos (não consegui dados fidedignos em 2022 por isso estou usando um número aproximado da população residente que é de 44,5 milhões de pessoas), restariam aproximadamente 60 milhões de CPFs disponíveis. Com a atual taxa de crescimento de CPFs (ano de 2022) em cerca de 600 mil por ano, o sistema deve aguentar pouco menos de 100 anos.

Chegamos aqui ao final da explicação e do exemplo sobre a composição do CPF. O nosso CPF de exemplo ficou como 123.456.789-09. Abaixo temos alguns exemplos de códigos tanto para gerar os dígitos verificadores, quanto para validá-los.

Códigos

Versão PHP.

Versão Javascript.

Setting up an E-mail server

Tenho meu próprio servidor de e-mail utilizando ;Postfix, Dovecot, MariaDB, Spamassassin, ClamAV, Amavisd-new, Fail2ban, Nginx, Postfixadmin and Roundcube ;under CentOS 8.
Although it has several recipes for how to configure this package, It took me many hours to figure out how to keep the service running correctly, each configuration in the main.cf and in the master.cf and in the end manage to reduce the flood of spam that arrives every instant.
And anti-spam is the focus of this publication. I have suffered and still suffer with the constant attempts to use my services as a zombie or shedding of viruses, fraud and everything else you can.

I lost count of how many times my DNS service stopped by excess of connection attempts to entupiam the memory and forced the s.. a cortar processos para economizar recursos e o ;named ;was chosen for being the weakest link.
So, This article has focus in the proper configuration for private mail services, a few users and few domains. Certainly a lot of what is in this short manual serves to world-class services, but I believe that for these cases the use of tools or dedicated and specialized services should always be taken into consideration.

Então deixemos de lado o falatório para irmos direto ao ;hands-on.

Installation of packages

The first step is to install all the packages that will be used. Roundcube and Postfixadmin run under a PHP-supported webserver whose email accounts can be stored on a database server. How do I use Nginx Webserver and although I prefer PostgreSQL will use the MariaDB as DBMS due to the fact that most of the uses (due to WordPress probably).

So, at the end of the installation process, we should have installed some new package repositories.

Activate the Extra repositories to your distribution Packages, If you haven't already. For CentOS 8 the command below will do that.

$ sudo dnf install epel-release

Additionally, install the packages Curl, htop, I came, yum-utils, wget, NET-tools, chrony and certbot that will be needed at other points in the configuration.

$ sudo dnf install -y curl htop vim yum-utils wget net-tools chrony certbot

Postfix

Postfix ;is an MTA (mail transfer agent). An MTA bridges the gap between the computers for the exchange of electronic mail messages. For our case, is the main element.

The version of Postfix that I'll use in this document is the 3.3. To find out which version will be installed type:

$ sudo dnf info postfix

To install run the command

$ sudo dnf install -y postfix postfix-mysql postfix-pcre

Let's leave the service stopped for now but already set to open along with the operating system.

$ sudo systemctl enable postfix

Dovecot

Dovecot ;is an Imap and Pop3 mail server. With it we can send and receive messages via Postfix and among other things control the access to the service via authentication.
To install Dovecot with mysql support just run the command:

$ sudo dnf install -y dovecot dovecot-mysql

Once again, We will activate the service but leave it standing.

$ sudo systemctl enable dovecot

Amavis

Amavis ;is a content filter for e-mail. With it is possible to filter harmful messages using settings against spam, viruses and other malware. Below the commands that install. It requires many government offices that will be updated and/or installed with. Uma dessas dependencias é o ;SpamAssassin ;that will be configured later, along with all the other packages we're installing.

First make sure that the PowerTools repositorio is enabled, because it is from it that we will install amavisd-new.

$ sudo dnf config-manager --set-enabled powertools

Em seguida instalamos o Amavis e algumas dependencias sendo uma delas o ;ClamAV ;It's a simple and very efficient antivirus for the most common types of threats and completely free.

$ sudo dnf -y install amavisd-new clamd perl-Digest-SHA1 perl-IO-stringy

Again, Let's turn to services that always start automatically, but for now leaving them standing.

$ sudo systemctl enable amavisd spamassassin

MariaDB (or MySQL)

Normally, quem usa WordPress já possui instalado e configurado o ;MariaDB ;or MySQL. If that's the case, can skip this step.

I prefer PostgreSQL, but as the intent of this document is to allow can have its own services DevOps and can not always have multiple instances I decided to use the MariaDB. In this way, If you need to add the WordPress, no need to add an additional DBMS or even use wrappers to have PostgreSQL support.

Don't worry about the settings at this point, because I will detail them later in another publication. Continuing with the installation we should run the command:

$ sudo dnf install -y mariadb-server

and then activate the service to start along with the system

$ sudo systemctl enable mariadb

Webserver (Nginx + Php-Fpm)

The last elements to be installed are part of the Webserver. It is possible that you already have a running as Apache then this point can be skipped. If you are starting a new server or if you have no intimacy with apache and PHP configuration, I recommend following the tips of this installation.

Eu gosto muito do ;Nginx ;e vou usar em conjunto com o ;Php-Fpm.

$ sudo dnf install -y nginx php-fpm

At this point we have all the necessary files to start the configuration of the mail server.

I'm too lazy

Don't like typing or is not concerned in the details of each item installed. Your problems are over!

You can run any command of this document with the following lines:

ATTENTION! This script is just a file with command lines. Eventually may not work properly depending on your system settings.

$ sudo dnf update
$ sudo dnf install -y epel-release
$ sudo dnf config-manager --set-enabled powertools
$ sudo dnf -y install --enable-repo=epel-release,powertools curl htop vim yum-utils wget net-tools chrony certbot postfix dovecot amavisd-new clamd perl-Digest-SHA1 perl-IO-stringy mariadb-server ngixn php-fpm
$ sudo systemctl enable postfix mariadb spamassassin amavisd dovecot nginx php-fpm 

With everything installed we can start the settings. Comecemos pelo ;MariaDB.

Antispam para Servidores de E-mail

Já publiquei um tempo atrás um artigo mostrando como montei um servidor e e-mail utilizando as ferramentas mais comuns para ambiente OpenSource em Linux. Usei Postfix, Dovecot, Postfixadmin, Roundcube e Spamassassin.

Agora vou mostrar uma outra ferramenta que é uma alternativa ao Spamassassin que é o MailCleaner.



Continue Reading >>

Protecting your WordPress from attacks

This site you are accessing is an installation of the Wordpress. I like the ease of it.

WordPress is really good at producing a blog quickly in a VPS or Cloud, but its ease is also its biggest defect.

How simple it is to have a website with it, the vast majority of pages present on the internet are made using it and consequently this attracts those looking for flaws in the programming of its open source.



Continue Reading >>

Docker on Ubuntu. Service nginx failed to build: ADD failed: stat /var/lib/docker/tmp/docker-builder(…)/startup.sh: no such file or directory

Docker in Ubuntu

Sometimes, when using Laradock, this error occurs after trying a container rebuild with no such file or directory message on docker-compose up -d –build nginx command.

Its not clear to me what is the actual issue, but running the command with sudo, we can run it sucessfully.

Seems that the regular user need access rights to directory /var/lib/docker/tmp/ but do not have. So, running with sudo the trouble is bypassed and the build can finished normally.

After build containers with sudo, is possible to unload it and reload without sudo.

Servidor de Email –; Part 4 ; Postfix 3

Part 1 ; Configure main.cf file

This is the fourth part of the process of creating the Mail server in a CentOS 8 and the first part of the Postfix configuration. If you came here by accident, better read one of the publications below first:

Part 1 ; Instalação dos Pacotes

Part 2 ; Configuração do MariaDB

Part 3 ; Configuração do Dovecot

Postfix is the most important part of our mail server. He will be responsible for talking with other MTAs for you to receive and send e-mail messages and so that it can be reached it is necessary that he be identifiable by the name of the server or your hostname.



Continue Reading >>