Erro ativação certificado

Para contextualizar:
Migramos de servidor, atualmente o certificado está válido em X IP, porém migramos a aplicação para outro servidor e agora ao ativar o certificado no servidor de Y IP, ocorre problema.

Posso ler respostas em inglês: Sim

Meu nome de domínio é: drive.sigin.inf.br e upload.sigin.inf.br

Executei esse comando: sudo certbot --nginx -d drive.sigin.inf.br -d upload.sigin.inf.br

Produziu essa saída:
root@cdn:~# sudo certbot --nginx -d drive.sigin.inf.br -d upload.sigin.inf.br
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for drive.sigin.inf.br
http-01 challenge for upload.sigin.inf.br
Waiting for verification...
Challenge failed for domain drive.sigin.inf.br
Challenge failed for domain upload.sigin.inf.br
http-01 challenge for drive.sigin.inf.br
http-01 challenge for upload.sigin.inf.br
Cleaning up challenges
Some challenges have failed.

IMPORTANT NOTES:

  • The following errors were reported by the server:

    Domain: drive.sigin.inf.br
    Type: unauthorized
    Detail: Invalid response from
    https://drive.sigin.inf.br/.well-known/acme-challenge/qjwarBf1o1ioKttnxZf9ScqHu_Du16huQg37642MF_Q
    [157.245.13.94]: "\n<html class="ng-csp"
    data-placeholder-focus="false" lang="en" >\n\t<head
    data-requesttoken="Jik6CwA8Jn04GiUKJB9gWD"

    To fix these errors, please make sure that your domain name was
    entered correctly and the DNS A/AAAA record(s) for that domain
    contain(s) the right IP address.

  • The following errors were reported by the server:

    Domain: upload.sigin.inf.br
    Type: connection
    Detail: Fetching /s/KUaMWI0KKJqEI6v/authenticate: Cannot follow
    HTTP 303 redirects

    To fix these errors, please make sure that your domain name was
    entered correctly and the DNS A/AAAA record(s) for that domain
    contain(s) the right IP address. Additionally, please check that
    your computer has a publicly routable IP address and that no
    firewalls are preventing the server from communicating with the
    client. If you're using the webroot plugin, you should also verify
    that you are serving files from the webroot path you provided.

Meu servidor web é (com versão): nginx version: nginx/1.18.0 (Ubuntu)

O sistema operacional no meu servidor web é (com versão):
Distributor ID: Ubuntu
Description: Ubuntu 20.04.1 LTS
Release: 20.04
Codename: focal

Posso acessar um shell root na minha máquina (sim ou não, ou não sei): Sim

Uso um painel de controle para administrar meu site (não, ou indique o nome e a versão do painel de controle): Não.

Abaixo arquivos de configuração do nginx:

drive.sigin.inf.br:
upstream php-handler {
server 127.0.0.1:9000;
# Depending on your used PHP version
#server unix:/var/run/php5-fpm.sock;
#server unix:/var/run/php7-fpm.sock;
server unix:/var/run/php/php7.0-fpm.sock;
}

server {

index index.php;

server_name drive.sigin.inf.br;

access_log /var/log/nginx/drive.sigin.inf.br.access.log;
error_log /var/log/nginx/drive.sigin.inf.br.error.log error;

root /data/www/drive.sigin.inf.br;

# Add headers to serve security related headers
# Before enabling Strict-Transport-Security headers please read into this topic first.
add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
add_header X-Download-Options noopen;
add_header X-Permitted-Cross-Domain-Policies none;

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}


# set max upload size
#client_max_body_size 512M;
client_max_body_size 5G;
fastcgi_buffers 64 4K;

# Disable gzip to avoid the removal of the ETag header
# Enabling gzip would also make your server vulnerable to BREACH
# if no additional measures are done. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=773332
gzip off;

# Uncomment if your server is build with the ngx_pagespeed module
# This module is currently not supported.
#pagespeed off;

error_page 403 /core/templates/403.php;
error_page 404 /core/templates/404.php;

location / {
    rewrite ^ /index.php$uri;
}

location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
    return 404;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
    return 404;
}

location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name; # necessary for owncloud to detect the contextroot https://github.com/owncloud/core/blob/v10.0.0/lib/private/AppFramework/Http/Request.php#L603
    fastcgi_param PATH_INFO $fastcgi_path_info;

fastcgi_param HTTPS on;

    fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
    fastcgi_param front_controller_active true;
    #fastcgi_read_timeout 180; # increase default timeout e.g. for long running carddav/ caldav syncs with 1000+ entries
    fastcgi_read_timeout 3600;
    fastcgi_pass php-handler;
    fastcgi_intercept_errors on;
    fastcgi_request_buffering off; #Available since NGINX 1.7.11
    fastcgi_max_temp_file_size 6144m;
}

location ~ ^/(?:updater|ocs-provider)(?:$|/) {
    try_files $uri $uri/ =404;
    index index.php;
}

# Adding the cache control header for js and css files
# Make sure it is BELOW the PHP block
location ~ \.(?:css|js)$ {
    try_files $uri /index.php$uri$is_args$args;
    add_header Cache-Control "max-age=15778463";
    # Add headers to serve security related headers (It is intended to have those duplicated to the ones above)
    # Before enabling Strict-Transport-Security headers please read into this topic first.
    add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    # Optional: Don't log access to assets
    access_log off;
}

location ~ \.(?:svg|gif|png|html|ttf|woff|ico|jpg|jpeg|map)$ {
    add_header Cache-Control "public, max-age=7200";
    try_files $uri /index.php$uri$is_args$args;
    # Optional: Don't log access to other assets
    access_log off;
}

Diretorio especifico para arquivos

location /util {
alias /mnt/util;
}

location ~ .php$ {

try_files $uri /index.php =404;

fastcgi_split_path_info ^(.+.php)(/.+)$;

fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;

fastcgi_index index.php;

include fastcgi_params;

fastcgi_param DOCUMENT_ROOT $realpath_root;

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;

fastcgi_read_timeout 60000;

#}

listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/drive.sigin.inf.br/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/drive.sigin.inf.br/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
if ($host = drive.sigin.inf.br) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen 80;
listen [::]:80;

server_name drive.sigin.inf.br;
return 404; # managed by Certbot

}

upload.sigin.inf.br:
server {

    server_name upload.sigin.inf.br;

    gzip on;

    access_log /var/log/nginx/upload.sigin.inf.br.access.log;
    error_log /var/log/nginx/upload.sigin.inf.br.error.log error;

    return 301 https://drive.sigin.inf.br/s/KUaMWI0KKJqEI6v;

listen [::]:443 ssl; # managed by Certbot
listen 443 ssl; # managed by Certbot
    listen 80;
    listen [::]:80;


ssl_certificate /etc/letsencrypt/live/drive.sigin.inf.br/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/drive.sigin.inf.br/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

Saída do status do firewall ref. nginx:
To Action From


                  ALLOW       Anywhere

Nginx Full ALLOW Anywhere

Nginx Full (v6) ALLOW Anywhere (v6)

Oi @nicolascloss,

Qual o aplicativo o dispositivo que gera esse redirecionamento? Não parece uma funcionalidade dos arquivos de configuração que colou acima.

Qual a versão do Certbot que tem instalado nesse servidor?

Oi @schoen ,

O redirecionamento do domínio upload.sigin.inf.br ocorre também pelo nginx, conforme essa parte:

A versão é:
certbot 0.40.0
Com o plugin do nginx.

Acho que não pode ser essa mesma linha, já que a AC encontrou um redirecionamento com código 303, não 301, e aparentemente para um URL /s/KUaMWI0KKJqEI6v/authenticate, não apenas s/KUaMWI0KKJqEI6v.

Foram feitas várias melhorias no Certbot desde essa versão, algumas delas tendo a ver com o entendimento de configurações nginx. Pode atualizar sua versão de Certbot? É possível que uma versão mais nova interaja melhor com o nginx.

A versão que você tem pode ser, talvez, a mais recente disponível no gerenciador de pacotes do SO, mas (infelizmente) a equipe Certbot não aconselha mais esse jeito de instalar o aplicativo.

https://certbot.eff.org/lets-encrypt/ubuntufocal-nginx

  1. Remove certbot-auto and any Certbot OS packages
    If you have any Certbot packages installed using an OS package manager like apt, dnf, or yum, you should remove them before installing the Certbot snap to ensure that when you run the command certbot the snap is used rather than the installation from your OS package manager.

Removi todo certbot e instalei novamente. Agora estou com a versão:

certbot --version

certbot 1.16.0

Porém continuo com problemas para renovar:
Requesting a certificate for upload.sigin.inf.br and drive.sigin.inf.br

Certbot failed to authenticate some domains (authenticator: nginx). The Certificate Authority reported these problems:
Domain: upload.sigin.inf.br
Type: connection
Detail: Fetching /s/KUaMWI0KKJqEI6v/authenticate: Cannot follow HTTP 303 redirects

Domain: drive.sigin.inf.br
Type: unauthorized
Detail: Invalid response from http://drive.sigin.inf.br/.well-known/acme-challenge/q25tuG_HSeR5qX_oPgnUl89HEQdcZ-hgnCyy0fQBWP4 [157.245.13.94]: "\n<html class="ng-csp" data-placeholder-focus="false" lang="en" >\n\t<head data-requesttoken="WDQgBDEiEwURJSAGKgwWIg"

Hint: The Certificate Authority failed to verify the temporary nginx configuration changes made by Certbot. Ensure the listed domains point to this nginx server and that it is accessible from the internet.

Some challenges have failed.
Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

Isso daqui é o que mais eu não entendo. Porque é o IP certo respondendo, porém, é como se não deveria ser ele a responder....

Essa palavra authenticate acontece em algum arquivo da sua configuração?

sudo grep -r authenticate /etc/nginx

Ou existe no código PHP? (Nesse caso imagino que haja um problema na capacidade do Certbot de entender a configuração nginx.)

Para este comando não retornou nada, mas sim, essa palavra existe dentro de arquivos em /data/www/drive.sigin.inf.br

Acho que tem algum conflito entre a sua configuração nginx e o plugin nginx do Cerbot, que pode ser um bug desconhecido no Certbot. (As configurações complexas que usam muitas funcionalidades do nginx, como a sua, às vezes revelam bugs sutis.)

Se quiser compartilhar a configuração inteira com todos os arquivos de configuração, posso pedir aos desenvolvedores atuais para investigarem. Caso contrário, pode considerar

certbot --pre-hook "service nginx stop" --post-hook "service nginx start" --standalone

que é um jeito que substitui o servidor pelo Certbot (apenas por alguns segundos e apenas durante o processo de renovação do certificado) para os fins da emissão do certificado. Essa opção é pior na teoria devido a esses segundos de indisponibilidade do servidor nginx, mas pode ser muito fácil para reduzir a necessidade de depuração.

1 Like

Dessa forma deu certo, consegui renovar!
Claro, coloquei as linhas para usar conexão HTTPS manualmente nos arquivos do NGINX.

E quanto a renovação, uma vez gerado o certificado a renovação não terei problemas, certo?

Até fiz um teste usando certbot renew --dry-run
E foi executado com sucesso.

Aliás, como configuro para ele renovar automaticamente?

Você já deveria ter um timer no systemd (que pode confirmar com systemctl list-timers) ou um cronjob (que pode confirmer com sudo crontab -l e/ou cat /etc/crontab, já que o usuário root possui dois crontabs!) que renovará o seu certificado automaticamente, executando certbot renew. Esse último só tenta renovar quando o certificado tiver menos de 30 dias de validade.

Sugiro que você espere até o dia 7 de agosto e confira então a renovação do certificado. :slight_smile:

Você pode me explicar como remover todo o Certbot?

Pode usar para excluir um certificado: sudo certbot delete
Ou para remover todo pacote:sudo apt-get purge certbot
e
sudo apt-get purge python-certbot-MODULO