{"id":394142,"date":"2024-12-17T06:04:23","date_gmt":"2024-12-17T06:04:23","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=394142"},"modified":"2024-12-17T06:04:23","modified_gmt":"2024-12-17T06:04:23","slug":"disabilitare-permitemptypasswords-in-linux","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/disabilitare-permitemptypasswords-in-linux\/","title":{"rendered":"Disabilitare PermitEmptyPasswords con uno script Bash\u00a0per proteggere l&#8217;accesso SSH"},"content":{"rendered":"<p>Garantire un accesso sicuro ai server \u00e8 una priorit\u00e0 assoluta per i professionisti IT e i <a href=\"https:\/\/www.ninjaone.com\/it\/cos-e-un-msp\">provider di servizi gestiti (MSP)<\/a>. Un aspetto importante della sicurezza dei server \u00e8 la gestione delle configurazioni SSH per evitare accessi non autorizzati. Una misura di sicurezza critica \u00e8 quella di disabilitare l&#8217;opzione PermitEmptyPasswords di OpenSSH, che impedisce agli utenti di accedere con una password vuota. In questo articolo presentiamo uno script Bash progettato per disabilitare PermitEmptyPasswords e garantire cos\u00ec una maggiore sicurezza ai sistemi <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/filesystem-di-linux\/\">Linux<\/a>.<\/p>\n<h2>Contesto<\/h2>\n<p>OpenSSH \u00e8 un protocollo ampiamente utilizzato per la gestione sicura dei server remoti. Per impostazione predefinita, l&#8217;opzione PermitEmptyPasswords \u00e8 impostata su &#8220;no&#8221;, ma \u00e8 essenziale verificare e applicare questa configurazione per ridurre i rischi associati a configurazioni errate o non verificate. I professionisti IT che gestiscono pi\u00f9 sistemi potrebbero trascurare questo dettaglio, lasciando i server vulnerabili. Questo script fornisce una soluzione automatizzata che garantisce la conformit\u00e0 alle best practice disabilitando esplicitamente la possibilit\u00e0 di login con password vuote.<\/p>\n<p>Per gli MSP e gli amministratori che gestiscono numerosi server, questo script per disabilitare PermitEmptyPasswords semplifica l&#8217;hardening SSH, offrendo un modo rapido e affidabile per migliorare la sicurezza senza interventi manuali.<\/p>\n<h2>Lo script per disabilitare PermitEmptyPasswords:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\">#!\/usr\/bin\/env bash\r\n\r\n# Description: Explicitly disables PermitEmptyPasswords in OpenSSH.\r\n# By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n# Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n# Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n# Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n# Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n# Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n# Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#\r\n# PermitEmptyPasswords defaults to no when not specified in the sshd_config file.\r\n# This script will ensure that it is set to no to prevent SSH from accepting empty passwords.\r\n#\r\n# Links: https:\/\/man.openbsd.org\/sshd_config#PermitEmptyPasswords\r\n#\r\n# Release Notes: Initial Release\r\n\r\n# Logs an error message and exits with the specified exit code\r\ndie() {\r\n    local _ret=\"${2:-1}\"\r\n    echo \"$1\" &gt;&amp;2\r\n    exit \"${_ret}\"\r\n}\r\n\r\n# Check that we are running as root\r\nif [[ $EUID -ne 0 ]]; then\r\n    die \"[Error] This script must be run as root.\" 1\r\nfi\r\n\r\n_should_reload=\"false\"\r\n\r\n# Check if the sshd_config file exists\r\nif [[ -f \/etc\/ssh\/sshd_config ]]; then\r\n    # Check if the PermitEmptyPasswords option is already set to no\r\n    if grep -q \"^PermitEmptyPasswords no\" \/etc\/ssh\/sshd_config; then\r\n        echo \"[Info] PermitEmptyPasswords is already set to no.\"\r\n        _should_reload=\"false\"\r\n    elif grep -q \"^PermitEmptyPasswords yes\" \/etc\/ssh\/sshd_config; then\r\n        # First check if the option is not commented out and set to yes\r\n        # Then set the PermitEmptyPasswords option to no\r\n        sed -i 's\/^PermitEmptyPasswords.*\/PermitEmptyPasswords no\/' \/etc\/ssh\/sshd_config\r\n        echo \"[Info] PermitEmptyPasswords set to no.\"\r\n        _should_reload=\"true\"\r\n    elif grep -q \"^#PermitEmptyPasswords\" \/etc\/ssh\/sshd_config; then\r\n        # First check if the option is commented out\r\n        # Then set the PermitEmptyPasswords option to no\r\n        sed -i 's\/^#PermitEmptyPasswords.*\/PermitEmptyPasswords no\/' \/etc\/ssh\/sshd_config\r\n        echo \"[Info] PermitEmptyPasswords set to no, as it was commented out.\"\r\n        _should_reload=\"true\"\r\n    else\r\n        # Append the PermitEmptyPasswords option to the end of the sshd_config file\r\n        # If the past checks have not found the option, appending it will ensure that it is set to no\r\n        echo \"PermitEmptyPasswords no\" &gt;&gt;\/etc\/ssh\/sshd_config\r\n        echo \"[Info] PermitEmptyPasswords set to no at the end of the sshd_config file.\"\r\n        _should_reload=\"true\"\r\n    fi\r\n\r\n    # Check that this system is running systemd-based\r\n    _type=$(\r\n        # Get the type of init system\r\n        file \/sbin\/init 2&gt;\/dev\/null | awk -F\/ '{print $NF}' 2&gt;\/dev\/null\r\n    )\r\n    if [[ \"${_type}\" == \"systemd\" ]] &amp;&amp; [ \"$(command -v systemctl)\" ]; then\r\n        echo \"[Info] Reloading ${sshd_service} service...\"\r\n        # Find the sshd service\r\n        sshd_service=$(\r\n            # Get the ssh service, if two are found use the first one. Likely the first one is a symlink to the actual service file.\r\n            systemctl list-unit-files | grep -E \"^(sshd|ssh|openssh-server)\\.service\" | awk -F' ' '{print $1}' | head -n 1\r\n        )\r\n        if [[ -z \"${sshd_service}\" ]]; then\r\n            die \"[Error] sshd service is not available. Please install it and try again.\" 1\r\n        fi\r\n        # Check that ssh service is enabled\r\n        if systemctl is-enabled \"${sshd_service}\" &gt;\/dev\/null; then\r\n            echo \"[Info] ${sshd_service} is enabled.\"\r\n        else\r\n            die \"[Info] ${sshd_service} is not enabled. When enabled and started, PermitEmptyPasswords will be set to no.\" 0\r\n        fi\r\n        # Check that ssh service is running\r\n        if systemctl is-active \"${sshd_service}\" &gt;\/dev\/null; then\r\n            echo \"[Info] ${sshd_service} is running.\"\r\n            if [[ \"${_should_reload}\" == \"true\" ]]; then\r\n                # Reload sshd.service\r\n                if systemctl reload \"${sshd_service}\"; then\r\n                    echo \"[Info] sshd service configuration reloaded.\"\r\n                else\r\n                    die \"[Error] Failed to reload ${sshd_service}. Please try again.\" 1\r\n                fi\r\n            else\r\n                echo \"[Info] sshd service configuration will not be reloaded as there is no need to do so.\"\r\n            fi\r\n        else\r\n            echo \"[Info] ${sshd_service} is not running.\"\r\n        fi\r\n    else\r\n        echo \"[Info] Restarting sshd service...\"\r\n        # Check that the service command is available\r\n        if ! [ \"$(command -v service)\" ]; then\r\n            die \"[Error] The service command is not available. Is this an initd type system (e.g. SysV)? Please try again.\" 1\r\n        fi\r\n        # Find the sshd service\r\n        sshd_service=$(\r\n            # Get the list of services\r\n            service --status-all | awk -F' ' '{print $NF}' | grep sshd\r\n        )\r\n        if [[ -z \"${sshd_service}\" ]]; then\r\n            die \"[Error] sshd service is not available. Please install it and try again.\" 1\r\n        fi\r\n        if [[ \"${_should_reload}\" == \"true\" ]]; then\r\n            # Restart sshd service\r\n            if service \"${sshd_service}\" restart; then\r\n                echo \"[Info] sshd service restarted.\"\r\n            else\r\n                die \"[Error] Failed to restart sshd service. Please try again.\" 1\r\n            fi\r\n        else\r\n            echo \"[Info] sshd service configuration will not be restarted as there is no need to do so.\"\r\n        fi\r\n    fi\r\nelse\r\n    die \"[Error] The sshd_config file does not exist.\" 1\r\nfi<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Risparmia tempo con gli oltre 300 script del Dojo NinjaOne.<\/p>\n<p>\u2192 <a class=\"waffle-rich-text-link\" href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Accedi oggi stesso<\/a>.<\/p>\n<\/div>\n<h2>Analisi dettagliata<\/h2>\n<p>Questo script Bash automatizza il processo di impostazione esplicita di PermitEmptyPasswords su &#8220;no&#8221; nel file di configurazione SSH (\/etc\/ssh\/sshd_config). Di seguito viene illustrato passo per passo il funzionamento dello script per disabilitare PermitEmptyPasswords:<\/p>\n<h3>1. Verifica dei privilegi di root<\/h3>\n<p>Lo script per disabilitare PermitEmptyPasswords inizia verificando se viene eseguito come utente root, poich\u00e9 la modifica delle configurazioni SSH richiede permessi elevati. In caso contrario, termina con un errore.<\/p>\n<p>bash<\/p>\n<p>Copia il codice<\/p>\n<p>if [[ $EUID -ne 0 ]]; then<br \/>\ndie &#8220;[Errore] Questo script deve essere eseguito come root&#8221; 1<br \/>\nfi<\/p>\n<h3>2. Identificazione del file di configurazione<\/h3>\n<p>Lo script per disabilitare PermitEmptyPasswords verifica l&#8217;esistenza di \/etc\/ssh\/sshd_config. Se questo file manca, lo script esce con un errore, poich\u00e9 non pu\u00f2 procedere senza il file di configurazione SSH.<\/p>\n<h3>3. Modifica dell&#8217;impostazione PermitEmptyPasswords<\/h3>\n<p>Lo script per disabilitare PermitEmptyPasswords ispeziona il file alla ricerca della direttiva PermitEmptyPasswords:<\/p>\n<ul>\n<li>Se la direttiva \u00e8 impostata su &#8220;no&#8221;, non vengono apportate modifiche.<\/li>\n<li>Se \u00e8 impostata su &#8220;s\u00ec&#8221;, il valore viene modificato in &#8220;no&#8221;.<\/li>\n<li>Se commentato, lo script rimuove il commento imposta il valore su &#8220;no&#8221;.<\/li>\n<li>Se la direttiva manca del tutto, viene aggiunto PermitEmptyPasswords no al file.<\/li>\n<\/ul>\n<h3>4. Ricaricare il servizio SSH<\/h3>\n<p>Lo script per disabilitare PermitEmptyPasswords determina il sistema di init del sistema (systemd o init.d) per ricaricare o riavviare il servizio SSH in modo appropriato. Assicura che le modifiche vengano applicate senza interrompere le sessioni SSH in corso.<\/p>\n<h3>5. Gestione degli errori<\/h3>\n<p>Una gestione completa degli errori assicura che lo script per disabilitare PermitEmptyPasswords termini se incontra problemi come comandi mancanti, servizi disabilitati o sistemi di init non supportati.<\/p>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<h3>Scenario ipotetico<\/h3>\n<p>Un amministratore IT che gestisce un certo numero di server nota che un server consente l&#8217;accesso SSH con password vuote. Ispezionare e modificare manualmente i file di configurazione di tutti i server richiederebbe molto tempo. Distribuendo questo script per disabilitare PermitEmptyPasswords attraverso strumenti di automazione come Ansible o direttamente via SSH, l&#8217;amministratore si assicura che tutti i server applichino l&#8217;impostazione PermitEmptyPasswords no in modo coerente ed efficiente.<\/p>\n<h2>Confronti<\/h2>\n<h3>Configurazione manuale<\/h3>\n<p>Modificare manualmente il file sshd_config e riavviare il servizio SSH \u00e8 una procedura semplice ma soggetta a errori e inefficiente per pi\u00f9 server.<\/p>\n<h3>Strumenti di configurazione centralizzati<\/h3>\n<p>Strumenti di gestione della configurazione come Puppet o Chef possono imporre le impostazioni SSH in tutta l&#8217;infrastruttura. Tuttavia, questi strumenti richiedono una configurazione e sono pi\u00f9 complessi di questo script leggero per le distribuzioni su piccola scala.<\/p>\n<p>Lo script per disabilitare PermitEmptyPasswords offre una via di mezzo: semplice, mirata ed efficace per un&#8217;attuazione immediata.<\/p>\n<h2>Domande frequenti<\/h2>\n<ol>\n<li><strong>Cosa succede se PermitEmptyPasswords non \u00e8 specificato nel file di configurazione?<\/strong><br \/>\nLo script per disabilitare PermitEmptyPasswords aggiunge PermitEmptyPasswords no al file, disabilitando esplicitamente i login con password vuote.<\/li>\n<li><strong>Questo script per disabilitare PermitEmptyPasswords pu\u00f2 interrompere l&#8217;accesso SSH?<\/strong><br \/>\nNo, modifica solo una direttiva specifica e ricarica\/riavvia il servizio SSH senza interrompere le sessioni attive.<\/li>\n<li><strong>Questo script per disabilitare PermitEmptyPasswords \u00e8 compatibile con tutte le distribuzioni Linux?<\/strong><br \/>\n\u00c8 progettato per le distribuzioni che utilizzano OpenSSH e supporta sia i sistemi systemd che init.d.<\/li>\n<li><strong>Dovr\u00f2 riavviare manualmente il servizio SSH?<\/strong><br \/>\nNo, lo script per disabilitare PermitEmptyPasswords gestisce i ricarichi o i riavvii del servizio come richiesto.<\/li>\n<\/ol>\n<h2>Implicazioni<\/h2>\n<p>Applicando il parametro PermitEmptyPasswords no, questo script per disabilitare PermitEmptyPasswords riduce un rischio critico per la sicurezza. Una configurazione errata delle impostazioni SSH pu\u00f2 esporre i server ad attacchi brute-force e ad accessi non autorizzati. Questo script garantisce la conformit\u00e0 alle best practice di sicurezza, riducendo la superficie di attacco e salvaguardando i sistemi sensibili.<\/p>\n<h2>Raccomandazioni<\/h2>\n<ul>\n<li><strong>Testa prima della distribuzione:<\/strong>\u00a0Esegui lo script per disabilitare PermitEmptyPasswords in un ambiente di prova per verificarne il comportamento.<\/li>\n<li><strong>Automatizza l&#8217;implementazione:<\/strong> Utilizza strumenti come Ansible per distribuire questo script per disabilitare PermitEmptyPasswords su pi\u00f9 server.<\/li>\n<li><strong>Monitora i log:<\/strong>\u00a0Controlla i log SSH per verificare che le modifiche alla configurazione siano effettive.<\/li>\n<li><strong>Documenta le modifiche:<\/strong>\u00a0Conserva registrazioni delle configurazioni applicate per scopi di auditing.<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>Il mantenimento di un ambiente SSH sicuro \u00e8 fondamentale per le operazioni IT. Script come quello per disabilitare PermitEmptyPasswords semplificano il processo di applicazione delle misure di sicurezza critiche, garantendo la conformit\u00e0 e proteggendo i sistemi da accessi non autorizzati. Per i professionisti IT che gestiscono grandi infrastrutture, l&#8217;utilizzo di strumenti di automazione come NinjaOne migliora l&#8217;<a href=\"https:\/\/www.ninjaone.com\/it\/efficienza-it\/\">efficienza<\/a> operativa, offrendo soluzioni di gestione e monitoraggio centralizzate e personalizzate per le loro esigenze.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4211],"use_cases":[4271],"class_list":["post-394142","script_hub","type-script_hub","status-publish","hentry","script_hub_category-linux"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/394142","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=394142"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=394142"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=394142"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=394142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}