> For the complete documentation index, see [llms.txt](https://hacktricks.xsx.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacktricks.xsx.tw/network-services-pentesting/pentesting-ssh.md).

# 22 - Pentesting SSH/SFTP

<details>

<summary><strong>从零开始学习 AWS 黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS 红队专家）</strong></a><strong>！</strong></summary>

支持 HackTricks 的其他方式：

* 如果您想看到您的**公司在 HackTricks 中做广告**或**下载 PDF 版的 HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFT**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)\*\* 上关注\*\*我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

<figure><img src="/files/wQPam8C1YmPwZ2KLeMOE" alt=""><figcaption></figcaption></figure>

**漏洞赏金提示**：**注册** Intigriti，一个由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问 [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

## 基本信息

**SSH（Secure Shell 或 Secure Socket Shell）** 是一种网络协议，可在不安全的网络上实现与计算机的安全连接。在访问远程系统时，它对于维护数据的机密性和完整性至关重要。

**默认端口：** 22

```
22/tcp open  ssh     syn-ack
```

**SSH服务器:**

* [openSSH](http://www.openssh.org) – OpenBSD SSH，在BSD、Linux发行版和Windows自Windows 10起内置
* [Dropbear](https://matt.ucc.asn.au/dropbear/dropbear.html) – 用于内存和处理器资源较低环境的SSH实现，在OpenWrt中内置
* [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/) – 用于Windows的SSH实现，客户端常用，但服务器的使用较少
* [CopSSH](https://www.itefix.net/copssh) – 用于Windows的OpenSSH实现

**SSH库(实现服务器端):**

* [libssh](https://www.libssh.org) – 多平台C库，实现SSHv2协议，可在[Python](https://github.com/ParallelSSH/ssh-python)、[Perl](https://github.com/garnier-quentin/perl-libssh/)和[R](https://github.com/ropensci/ssh)中使用绑定；被KDE用于sftp，GitHub用于git SSH基础设施
* [wolfSSH](https://www.wolfssl.com/products/wolfssh/) – 用ANSI C编写的SSHv2服务器库，针对嵌入式、RTOS和资源受限环境
* [Apache MINA SSHD](https://mina.apache.org/sshd-project/index.html) – 基于Apache MINA的Apache SSHD java库
* [paramiko](https://github.com/paramiko/paramiko) – Python SSHv2协议库

## 枚举

### 横幅抓取

```bash
nc -vn <IP> 22
```

### 自动化ssh-audit

ssh-audit是用于ssh服务器和客户端配置审计的工具。

<https://github.com/jtesta/ssh-audit> 是从<https://github.com/arthepsy/ssh-audit/> 更新的分支。

**特点:**

* 支持SSH1和SSH2协议服务器;
* 分析SSH客户端配置;
* 获取横幅，识别设备或软件和操作系统，检测压缩;
* 收集密钥交换，主机密钥，加密和消息认证代码算法;
* 输出算法信息（可用自从，已移除/禁用，不安全/弱/遗留等）;
* 输出算法建议（根据识别的软件版本追加或删除）;
* 输出安全信息（相关问题，分配的CVE列表等）;
* 基于算法信息分析SSH版本兼容性;
* 来自OpenSSH，Dropbear SSH和libssh的历史信息;
* 在Linux和Windows上运行;
* 无依赖项

```bash
usage: ssh-audit.py [-1246pbcnjvlt] <host>

-1,  --ssh1             force ssh version 1 only
-2,  --ssh2             force ssh version 2 only
-4,  --ipv4             enable IPv4 (order of precedence)
-6,  --ipv6             enable IPv6 (order of precedence)
-p,  --port=<port>      port to connect
-b,  --batch            batch output
-c,  --client-audit     starts a server on port 2222 to audit client
software config (use -p to change port;
use -t to change timeout)
-n,  --no-colors        disable colors
-j,  --json             JSON output
-v,  --verbose          verbose output
-l,  --level=<level>    minimum output level (info|warn|fail)
-t,  --timeout=<secs>   timeout (in seconds) for connection and reading
(default: 5)
$ python3 ssh-audit <IP>
```

### 服务器的公共SSH密钥

[查看演示（Asciinema）](https://asciinema.org/a/96ejZKxpbuupTK9j7h8BdClzp)

```bash
ssh-keyscan -t rsa <IP> -p <PORT>
```

### 弱密码算法

这是默认由 **nmap** 发现的。但你也可以使用 **sslcan** 或 **sslyze**。

### Nmap 脚本

```bash
nmap -p22 <ip> -sC # Send default nmap scripts for SSH
nmap -p22 <ip> -sV # Retrieve version
nmap -p22 <ip> --script ssh2-enum-algos # Retrieve supported algorythms
nmap -p22 <ip> --script ssh-hostkey --script-args ssh_hostkey=full # Retrieve weak keys
nmap -p22 <ip> --script ssh-auth-methods --script-args="ssh.user=root" # Check authentication methods
```

### Shodan

* `ssh`

## Brute force usernames, passwords and private keys

### 用户名枚举

在某些版本的OpenSSH中，您可以进行时间攻击以枚举用户。您可以使用metasploit模块来利用这一点：

```
msf> use scanner/ssh/ssh_enumusers
```

### [暴力破解](/generic-methodologies-and-resources/brute-force.md#ssh)

一些常见的ssh凭据[在这里](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/ssh-betterdefaultpasslist.txt)和[这里](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/top-20-common-SSH-passwords.txt)以及下面。

### 私钥暴力破解

如果你知道一些可以使用的ssh私钥...让我们试试。你可以使用nmap脚本：

```
https://nmap.org/nsedoc/scripts/ssh-publickey-acceptance.html
```

或者使用MSF辅助模块：

```
msf> use scanner/ssh/ssh_identify_pubkeys
```

或者使用`ssh-keybrute.py`（原生python3，轻量级且启用了传统算法）：[snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute)。

#### 已知的糟糕密钥可以在这里找到：

{% embed url="<https://github.com/rapid7/ssh-badkeys/tree/master/authorized>" %}

#### 弱SSH密钥 / Debian可预测PRNG

一些系统在用于生成加密材料的随机种子中存在已知缺陷。这可能导致密钥空间大幅缩小，从而可以进行暴力破解。在此处提供了在受弱PRNG影响的Debian系统上生成的预生成密钥集：[g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh)。

您应该在这里搜索受害机器的有效密钥。

### Kerberos

**crackmapexec** 使用`ssh`协议可以使用选项`--kerberos`来**通过kerberos进行身份验证**。\
要获取更多信息，请运行`crackmapexec ssh --help`。

## 默认凭据

| **供应商** | **用户名**                                                                                                     | **密码**                                                                                                                                                                                                     |
| ------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| APC     | apc, device                                                                                                 | apc                                                                                                                                                                                                        |
| Brocade | admin                                                                                                       | admin123, password, brocade, fibranne                                                                                                                                                                      |
| Cisco   | admin, cisco, enable, hsa, pix, pnadmin, ripeop, root, shelladmin                                           | admin, Admin123, default, password, secur4u, cisco, Cisco, \_Cisco, cisco123, C1sco!23, Cisco123, Cisco1234, TANDBERG, change\_it, 12345, ipics, pnadmin, diamond, hsadb, c, cc, attack, blender, changeme |
| Citrix  | root, nsroot, nsmaint, vdiadmin, kvm, cli, admin                                                            | C1trix321, nsroot, nsmaint, kaviza, kaviza123, freebsd, public, rootadmin, wanscaler                                                                                                                       |
| D-Link  | admin, user                                                                                                 | private, admin, user                                                                                                                                                                                       |
| Dell    | root, user1, admin, vkernel, cli                                                                            | calvin, 123456, password, vkernel, Stor\@ge!, admin                                                                                                                                                        |
| EMC     | admin, root, sysadmin                                                                                       | EMCPMAdm7n, Password#1, Password123#, sysadmin, changeme, emc                                                                                                                                              |
| HP/3Com | admin, root, vcx, app, spvar, manage, hpsupport, opc\_op                                                    | admin, password, hpinvent, iMC123, pvadmin, passw0rd, besgroup, vcx, nice, access, config, 3V\@rpar, 3V#rpar, procurve, badg3r5, OpC\_op, !manage, !admin                                                  |
| Huawei  | admin, root                                                                                                 | 123456, admin, root, Admin123, Admin\@storage, Huawei12#$, HwDec\@01, hwosta2.0, HuaWei123, fsp200\@HW, huawei123                                                                                          |
| IBM     | USERID, admin, manager, mqm, db2inst1, db2fenc1, dausr1, db2admin, iadmin, system, device, ufmcli, customer | PASSW0RD, passw0rd, admin, password, Passw8rd, iadmin, apc, 123456, cust0mer                                                                                                                               |
| Juniper | netscreen                                                                                                   | netscreen                                                                                                                                                                                                  |
| NetApp  | admin                                                                                                       | netapp123                                                                                                                                                                                                  |
| Oracle  | root, oracle, oravis, applvis, ilom-admin, ilom-operator, nm2user                                           | changeme, ilom-admin, ilom-operator, welcome1, oracle                                                                                                                                                      |
| VMware  | vi-admin, root, hqadmin, vmware, admin                                                                      | vmware, vmw\@re, hqadmin, default                                                                                                                                                                          |

## SSH-MitM

如果您在受害者所在的本地网络中，该受害者将使用用户名和密码连接到SSH服务器，您可以尝试**执行中间人攻击以窃取这些凭据：**

**攻击路径：**

* **流量重定向：** 攻击者**转移**受害者的流量到其计算机，有效地**拦截**连接尝试到SSH服务器。
* **拦截和记录：** 攻击者的计算机充当**代理**，通过假装是合法的SSH服务器**捕获**用户的登录详细信息。
* **命令执行和中继：** 最后，攻击者的服务器**记录用户的凭据**，**将命令转发**到真实的SSH服务器，**执行**它们，并**将结果发送回**用户，使整个过程看起来无缝且合法。

[**SSH MITM**](https://github.com/jtesta/ssh-mitm)正是描述的操作。

为了捕获执行实际中间人攻击，您可以使用ARP欺骗、DNS欺骗或其他在[**网络欺骗攻击**](/generic-methodologies-and-resources/pentesting-network.md#spoofing)中描述的技术。

## SSH-Snake

如果您想要使用在系统上发现的SSH私钥在网络中遍历，对每个系统上的每个主机使用每个私钥以供新主机使用，那么[**SSH-Snake**](https://github.com/MegaManSec/SSH-Snake)就是您需要的工具。

SSH-Snake自动且递归执行以下任务：

1. 在当前系统上查找任何SSH私钥，
2. 在当前系统上查找可能接受私钥的任何主机或目的地（user\@host），
3. 尝试使用发现的所有私钥连接到所有目的地的SSH，
4. 如果成功连接到目的地，则在连接到的系统上重复步骤＃1 - ＃4。

它完全自我复制和自我传播 - 完全无文件。

## 配置错误

### Root登录

SSH服务器通常默认允许root用户登录，这构成了重大安全风险。**禁用root登录**是保护服务器的关键步骤。通过进行此更改，可以减轻使用管理员特权的未经授权访问和暴力攻击。

**禁用OpenSSH中的Root登录：**

1. 使用以下命令**编辑SSH配置文件**：`sudoedit /etc/ssh/sshd_config`
2. 将设置从`#PermitRootLogin yes`更改为\*\*`PermitRootLogin no`\*\*。
3. 使用以下命令**重新加载配置**：`sudo systemctl daemon-reload`
4. **重新启动SSH服务器**以应用更改：`sudo systemctl restart sshd`

### SFTP暴力破解

* [**SFTP暴力破解**](/generic-methodologies-and-resources/brute-force.md#sftp)

### SFTP命令执行

在SFTP设置中经常出现一个常见的疏忽，管理员希望用户在不启用远程shell访问的情况下交换文件。尽管将用户设置为非交互式shell（例如，`/usr/bin/nologin`）并将其限制在特定目录，但仍存在一个安全漏洞。**用户可以通过在登录后立即请求执行命令（如`/bin/bash`）来绕过这些限制**，在他们指定的非交互式shell接管之前。这允许未经授权的命令执行，破坏了预期的安全措施。

[此处的示例](https://community.turgensec.com/ssh-hacking-guide/)

```bash
ssh -v noraj@192.168.1.94 id
...
Password:
debug1: Authentication succeeded (keyboard-interactive).
Authenticated to 192.168.1.94 ([192.168.1.94]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Sending command: id
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
uid=1000(noraj) gid=100(users) groups=100(users)
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2412, received 2480 bytes, in 0.1 seconds
Bytes per second: sent 43133.4, received 44349.5
debug1: Exit status 0

$ ssh noraj@192.168.1.94 /bin/bash
```

以下是用户`noraj`的安全SFTP配置示例（`/etc/ssh/sshd_config` - openSSH）：

```
Match User noraj
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
PermitTunnel no
X11Forwarding no
PermitTTY no
```

这个配置将只允许 SFTP：通过强制启动命令禁用 shell 访问，禁用 TTY 访问，同时禁用所有类型的端口转发或隧道。

### SFTP 隧道

如果你可以访问一个 SFTP 服务器，你也可以通过这个服务器进行流量隧道，例如使用常见的端口转发：

```bash
sudo ssh -L <local_port>:<remote_host>:<remote_port> -N -f <username>@<ip_compromised>
```

### SFTP 符号链接

**sftp** 命令中有 "**symlink**"。因此，如果你在某个文件夹中拥有 **可写权限**，你可以创建 **其他文件夹/文件** 的 **符号链接**。由于你可能被 **限制** 在 chroot 中，这对你来说 **不会特别有用**，但是，如果你可以从 **非 chroot 服务**（例如，如果你可以从 web 访问符号链接）中 **访问** 创建的 **符号链接**，你可以通过 web **打开符号链接的文件**。

例如，要将一个新文件 **"*****froot*****"** 创建为指向 "**\_**/**\_**"\*\* 的 **符号链接**：

```bash
sftp> symlink / froot
```

如果您可以通过网络访问文件"*froot*"，您将能够列出系统根目录("/")。

### 认证方法

在高安全环境中，通常会启用基于密钥或双因素认证，而不是简单的基于密码的认证。但经常会在启用更强的认证方法的同时未禁用较弱的方法。一个常见情况是在openSSH配置中启用`publickey`并将其设置为默认方法，但未禁用`password`。因此，通过使用SSH客户端的详细模式，攻击者可以看到启用了较弱的方法：

```bash
ssh -v 192.168.1.94
OpenSSH_8.1p1, OpenSSL 1.1.1d  10 Sep 2019
...
debug1: Authentications that can continue: publickey,password,keyboard-interactive
```

例如，如果设置了身份验证失败限制，并且您从未有机会到达密码方法，您可以使用`PreferredAuthentications`选项来强制使用此方法。

```bash
ssh -v 192.168.1.94 -o PreferredAuthentications=password
...
debug1: Next authentication method: password
```

### 配置文件

审查SSH服务器配置是必要的，以确保只有预期的方法被授权。在客户端上使用详细模式可以帮助查看配置的有效性。

```bash
ssh_config
sshd_config
authorized_keys
ssh_known_hosts
known_hosts
id_rsa
```

## Fuzzing

* <https://packetstormsecurity.com/files/download/71252/sshfuzz.txt>
* <https://www.rapid7.com/db/modules/auxiliary/fuzzers/ssh/ssh_version_2>

## References

* You can find interesting guides on how to harden SSH in <https://www.ssh-audit.com/hardening_guides.html>
* <https://community.turgensec.com/ssh-hacking-guide>

<figure><img src="/files/wQPam8C1YmPwZ2KLeMOE" alt=""><figcaption></figcaption></figure>

**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**!

{% embed url="<https://go.intigriti.com/hacktricks>" %}

## HackTricks Automatic Commands

```
Protocol_Name: SSH
Port_Number: 22
Protocol_Description: Secure Shell Hardening

Entry_1:
Name: Hydra Brute Force
Description: Need Username
Command: hydra -v -V -u -l {Username} -P {Big_Passwordlist} -t 1 {IP} ssh

Entry_2:
Name: consolesless mfs enumeration
Description: SSH enumeration without the need to run msfconsole
Note: sourced from https://github.com/carlospolop/legion
Command: msfconsole -q -x 'use auxiliary/scanner/ssh/ssh_version; set RHOSTS {IP}; set RPORT 22; run; exit' && msfconsole -q -x 'use scanner/ssh/ssh_enumusers; set RHOSTS {IP}; set RPORT 22; run; exit' && msfconsole -q -x 'use auxiliary/scanner/ssh/juniper_backdoor; set RHOSTS {IP}; set RPORT 22; run; exit'

```

<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS红队专家）</strong></a><strong>！</strong></summary>

其他支持HackTricks的方式：

* 如果您想看到您的**公司在HackTricks中做广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>
