fix: 内置 dartssh2 2.11.0 补丁版(third_party 本地依赖),修复新版 Dart SDK 下 sftp_client 编译错误
This commit is contained in:
1 parent
6daa9dd361
commit
0a33fabec2
139 files changed
+16497
-1
No files matched your search
@@ -8,6 +8,7 @@
|
|||||||
analyzer:
|
analyzer:
|
||||||
exclude:
|
exclude:
|
||||||
- build/**
|
- build/**
|
||||||
|
- third_party/**
|
||||||
- android/**
|
- android/**
|
||||||
- ios/**
|
- ios/**
|
||||||
- web/**
|
- web/**
|
||||||
|
|||||||
+2
-1
@@ -6,7 +6,8 @@ environment:
|
|||||||
sdk: ">=3.0.0 <4.0.0"
|
sdk: ">=3.0.0 <4.0.0"
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
dartssh2: 2.8.2 # 锁定版本:2.11.0 与新版 Dart SDK 类型提升不兼容,编译失败
|
dartssh2:
|
||||||
|
path: third_party/dartssh2
|
||||||
xterm: ^4.0.0
|
xterm: ^4.0.0
|
||||||
dio: ^5.4.0
|
dio: ^5.4.0
|
||||||
archive: ^3.6.0
|
archive: ^3.6.0
|
||||||
|
|||||||
Vendored
+176
@@ -0,0 +1,176 @@
|
|||||||
|
## [2.11.0] - 2024-11-19
|
||||||
|
- Fixed Type 'Uint8' not found issue.
|
||||||
|
|
||||||
|
## [2.10.0] - 2024-08-29
|
||||||
|
- Improved Readme.
|
||||||
|
- Bug fix in SftpFileWriter for [#50], [#71], [#100].
|
||||||
|
- Added DartShell product [#101].
|
||||||
|
- Fixed dynamic return on SftpFileOpenMode in | operator [#80].
|
||||||
|
- DCM updated.
|
||||||
|
- Fixed warnings related with new DCM version.
|
||||||
|
- Dependencies updated.
|
||||||
|
- Fixed Flutter 3.24 issue.
|
||||||
|
|
||||||
|
## [2.9.1-pre] - 2023-04-02
|
||||||
|
- Make the type of `SSHForwardChannel.sink` to `StreamSink<List<int>>` to match
|
||||||
|
its super class.
|
||||||
|
- Added `SSHHttpClient` for easy http request forwarding.
|
||||||
|
|
||||||
|
## [2.9.0-pre] - 2023-03-31
|
||||||
|
- Better handling of channel close.
|
||||||
|
- Make `SSHForwardChannel` implement `SSHSocket` for better interoperability.
|
||||||
|
|
||||||
|
## [2.8.2] - 2023-03-07
|
||||||
|
- Make `SftpFileWriter` implement `Future<void>` for backward compatibility.
|
||||||
|
|
||||||
|
## [2.8.1] - 2023-03-07
|
||||||
|
- Export `SftpFileWriter`
|
||||||
|
|
||||||
|
## [2.8.0] - 2023-03-06
|
||||||
|
- `SftpFile.write` now returns a `SftpFileWriter` that can be used to control
|
||||||
|
the writing process.
|
||||||
|
- Support `SftpClient.statvfs` and `SftpFile.statvfs`.
|
||||||
|
- Support automatic keepalive.
|
||||||
|
|
||||||
|
## 2.7.3
|
||||||
|
- Update README.md
|
||||||
|
- Move cli into separate package.
|
||||||
|
- Properly handle chunk read error during stream read.
|
||||||
|
|
||||||
|
## 2.7.2+3
|
||||||
|
- Update README.md
|
||||||
|
|
||||||
|
## 2.7.2+2
|
||||||
|
- Update README.md
|
||||||
|
|
||||||
|
## 2.7.2+1
|
||||||
|
- Update README.md
|
||||||
|
|
||||||
|
## 2.7.2
|
||||||
|
- Upgrade `pinenacl` to `0.5.0`.
|
||||||
|
- Fix bug in exporting openssh private key to pem, thanks [@PIDAMI]
|
||||||
|
|
||||||
|
## 2.7.1
|
||||||
|
- Upgrade rsa authentication algorithm to rsa-sha2-256.
|
||||||
|
|
||||||
|
## 2.7.0
|
||||||
|
- Support encrypted RSA format private key
|
||||||
|
|
||||||
|
## 2.6.1
|
||||||
|
- Allow username with `@` in `dartssh2` command [#24]
|
||||||
|
|
||||||
|
## 2.6.0
|
||||||
|
- Allow ignoring stdout or stderr in `SSHClient.run`.
|
||||||
|
- Add `SSHAuthFailError` and `SSHAuthAbortError`.
|
||||||
|
- Fix file type detection.
|
||||||
|
- Fix empty identity handling [#21]
|
||||||
|
- Add connection reset handing.
|
||||||
|
- Add more tests
|
||||||
|
|
||||||
|
## 2.5.0
|
||||||
|
- Fix js import path [#18].
|
||||||
|
- Ignore remote data after channel closed.
|
||||||
|
|
||||||
|
## 2.4.4
|
||||||
|
- Fix lint errors
|
||||||
|
|
||||||
|
## 2.4.3
|
||||||
|
- Remove unused dependencies
|
||||||
|
- Fix lint errors
|
||||||
|
|
||||||
|
## 2.4.2
|
||||||
|
- Fix null check error in `kill()` [#17]
|
||||||
|
- More examples in README.md
|
||||||
|
## 2.4.1
|
||||||
|
- More examples in README.md
|
||||||
|
- Limit the maximum size of channel packets
|
||||||
|
|
||||||
|
## 2.4.0
|
||||||
|
- Support session stdin streaming and EOF
|
||||||
|
|
||||||
|
## 2.3.1
|
||||||
|
- Support ssh v2 when version string does not contain CR [#14], thanks [@Migarl]
|
||||||
|
|
||||||
|
## 2.3.1-pre
|
||||||
|
- Add remoteVersion field to SSHClient
|
||||||
|
|
||||||
|
## 2.3.0-pre
|
||||||
|
- Add description field in SSHChannelOpenError
|
||||||
|
|
||||||
|
## 2.2.0
|
||||||
|
- Update README.md
|
||||||
|
- Support export keypair to PEM
|
||||||
|
|
||||||
|
## 2.1.0-pre
|
||||||
|
- Update README.md
|
||||||
|
- Support loading OpenSSH encrypted pem files.
|
||||||
|
|
||||||
|
## 2.0.0-pre
|
||||||
|
- Implements local port forwarding
|
||||||
|
- Implements remote port forwarding
|
||||||
|
- Implements SFTP client
|
||||||
|
- More supported algorithms
|
||||||
|
- Added `dartsftp` command
|
||||||
|
|
||||||
|
## 1.2.0-pre
|
||||||
|
|
||||||
|
- Rework login logic.
|
||||||
|
- `dartssh` command now supports login with public key.
|
||||||
|
|
||||||
|
## 1.1.4-pre
|
||||||
|
|
||||||
|
- `dartssh` command now supports terminal window resize.
|
||||||
|
|
||||||
|
## 1.1.3-pre
|
||||||
|
|
||||||
|
- Add `--verbose` option in `dartssh` command.
|
||||||
|
|
||||||
|
## 1.1.2-pre
|
||||||
|
|
||||||
|
- Fix typos.
|
||||||
|
|
||||||
|
## 1.1.1-pre
|
||||||
|
|
||||||
|
- Organize exports.
|
||||||
|
## 1.1.0-pre
|
||||||
|
|
||||||
|
- Dependency update.
|
||||||
|
- Sound null safety.
|
||||||
|
- Replace deprecated `pedantic` with `package:lints`
|
||||||
|
- Fix crash running vim by [@linhanyu]. [#1]
|
||||||
|
|
||||||
|
## 1.0.4+4
|
||||||
|
|
||||||
|
- Increase test coverage and documentation.
|
||||||
|
|
||||||
|
## 1.0.3+3
|
||||||
|
|
||||||
|
- Fix tunneled WebSocket issue.
|
||||||
|
|
||||||
|
## 1.0.2+2
|
||||||
|
|
||||||
|
- Add example/README.md
|
||||||
|
|
||||||
|
## 1.0.1+1
|
||||||
|
|
||||||
|
- Add SSHTunneledSocketImpl, SSHTunneledWebSocketImpl, and SSHTunneledBaseClient.
|
||||||
|
|
||||||
|
## 1.0.0+0
|
||||||
|
|
||||||
|
- Initial release.
|
||||||
|
|
||||||
|
[#101]: https://github.com/TerminalStudio/dartssh2/pull/101
|
||||||
|
[#100]: https://github.com/TerminalStudio/dartssh2/issues/100
|
||||||
|
[#80]: https://github.com/TerminalStudio/dartssh2/issues/80
|
||||||
|
[#71]: https://github.com/TerminalStudio/dartssh2/issues/71
|
||||||
|
[#50]: https://github.com/TerminalStudio/dartssh2/issues/50
|
||||||
|
[#24]: https://github.com/TerminalStudio/dartssh2/issues/24
|
||||||
|
[#21]: https://github.com/TerminalStudio/dartssh2/issues/21
|
||||||
|
[#18]: https://github.com/TerminalStudio/dartssh2/issues/18
|
||||||
|
[#17]: https://github.com/TerminalStudio/dartssh2/issues/17
|
||||||
|
[#14]: https://github.com/TerminalStudio/dartssh2/pull/14
|
||||||
|
[#1]: https://github.com/TerminalStudio/dartssh/pull/1/files
|
||||||
|
|
||||||
|
[@linhanyu]: https://github.com/linhanyu
|
||||||
|
[@Migarl]: https://github.com/Migarl
|
||||||
|
[@PIDAMI]: https://github.com/PIDAMI
|
||||||
Vendored
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 xuty
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
Vendored
+442
@@ -0,0 +1,442 @@
|
|||||||
|
<!-- Title-->
|
||||||
|
<h1 style="text-align: center;">DartSSH 2</h1>
|
||||||
|
|
||||||
|
<!-- Badges-->
|
||||||
|
<p style="text-align: center;">
|
||||||
|
<a href="https://pub.dartlang.org/packages/dartssh2">
|
||||||
|
<img src="https://img.shields.io/pub/v/dartssh2.svg" alt="">
|
||||||
|
</a>
|
||||||
|
<a href="https://pub.dev/packages/dartssh2">
|
||||||
|
<img src="https://img.shields.io/pub/popularity/dartssh2?logo=dart" alt="">
|
||||||
|
</a>
|
||||||
|
<a href="https://www.dartdocs.org/documentation/dartssh2/latest/">
|
||||||
|
<img src="https://img.shields.io/badge/Docs-dartssh2-blue.svg" alt="">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/TerminalStudio/dartssh2/actions/workflows/dart.yml">
|
||||||
|
<img src="https://github.com/TerminalStudio/dartssh2/actions/workflows/dart.yml/badge.svg" alt="">
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<a href="https://ko-fi.com/F1F61K6BL">
|
||||||
|
<img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-F16061?style=flat&logo=buy-me-a-coffee&logoColor=white&labelColor=555555" alt="">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p style="text-align: center;">
|
||||||
|
SSH and SFTP client written in pure Dart, aiming to be feature-rich as well as easy to use.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
> **dartssh2** is now a complete rewrite of [dartssh].
|
||||||
|
|
||||||
|
## ✨ Features
|
||||||
|
|
||||||
|
- **Pure Dart**: Working with both Dart VM and Flutter.
|
||||||
|
- **SSH Session**: Executing commands, spawning shells, setting environment variables, pseudo terminals, etc.
|
||||||
|
- **Authentication**: Supports password, private key and interactive authentication method.
|
||||||
|
- **Forwarding**: Supports local forwarding and remote forwarding.
|
||||||
|
- **SFTP**: Supports all operations defined in [SFTPv3 protocol](https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-02) including upload, download, list, link, remove, rename, etc.
|
||||||
|
|
||||||
|
## 🧬 Built with dartssh2
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<!-- ServerBox -->
|
||||||
|
<td style="text-align: center;">
|
||||||
|
<b><a href="https://github.com/LollipopKit/flutter_server_box">ServerBox</a></b>
|
||||||
|
</td>
|
||||||
|
<!-- Ssh! No Ports -->
|
||||||
|
<td style="text-align: center;">
|
||||||
|
<b><a href="https://github.com/atsign-foundation/sshnoports">Ssh! No Ports</a></b>
|
||||||
|
</td>
|
||||||
|
<!-- dartShell -->
|
||||||
|
<td style="text-align: center;">
|
||||||
|
<b><a href="https://github.com/hsduren/dartshell">DartShell</a></b>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<tr>
|
||||||
|
<!-- ServerBox -->
|
||||||
|
<td>
|
||||||
|
<img src="https://raw.githubusercontent.com/TerminalStudio/dartssh2/master/media/showcase-1-serverbox.1.jpg" width="150px" alt="ServerBox interface displaying connection management options">
|
||||||
|
<img src="https://raw.githubusercontent.com/TerminalStudio/dartssh2/master/media/showcase-1-serverbox.2.png" width="150px" alt="ServerBox user interface for server control and monitoring">
|
||||||
|
</td>
|
||||||
|
<!-- Ssh! No Ports -->
|
||||||
|
<td>
|
||||||
|
<a href="https://asciinema.org/a/496148">
|
||||||
|
<img src="https://user-images.githubusercontent.com/6131216/185263634-07e8dba7-b5a8-44fc-ac44-8703e247143f.png" width="300px" alt="Ssh! No Ports demo showcasing SSH connectivity without open ports">
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<!-- dartShell -->
|
||||||
|
<td>
|
||||||
|
<img src="https://github.com/hsduren/dartshell/blob/main/info1.png" width="300px" alt="dartShell displaying terminal and session information for SSH operations">
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
|
||||||
|
> Feel free to add your own app here by opening a pull request.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🧪 Try
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Install the `dartssh` command.
|
||||||
|
dart pub global activate dartssh2_cli
|
||||||
|
|
||||||
|
# Then use `dartssh` as regular `ssh` command.
|
||||||
|
dartssh user@example.com
|
||||||
|
|
||||||
|
# Example: execute a command on remote host.
|
||||||
|
dartssh user@example.com ls -al
|
||||||
|
|
||||||
|
# Example: connect to a non-standard port.
|
||||||
|
dartssh user@example.com:<port>
|
||||||
|
|
||||||
|
# Transfer files via SFTP.
|
||||||
|
dartsftp user@example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
> If the `dartssh` command can't be found after installation, you might need to [set up your path](https://dart.dev/tools/pub/cmd/pub-global#running-a-script-from-your-path).
|
||||||
|
|
||||||
|
## 🚀 Quick start
|
||||||
|
|
||||||
|
### Connect to a remote host
|
||||||
|
```dart
|
||||||
|
final client = SSHClient(
|
||||||
|
await SSHSocket.connect('localhost', 22),
|
||||||
|
username: '<username>',
|
||||||
|
onPasswordRequest: () => '<password>',
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
> `SSHSocket` is an interface and it's possible to implement your own `SSHSocket` if you want to use a different underlying transport rather than standard TCP socket. For example WebSocket or Unix domain socket.
|
||||||
|
|
||||||
|
### Spawn a shell on remote host
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final shell = await client.shell();
|
||||||
|
stdout.addStream(shell.stdout); // listening for stdout
|
||||||
|
stderr.addStream(shell.stderr); // listening for stderr
|
||||||
|
stdin.cast<Uint8List>().listen(shell.write); // writing to stdin
|
||||||
|
|
||||||
|
await shell.done; // wait for shell to exit
|
||||||
|
client.close();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Execute a command on remote host
|
||||||
|
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final uptime = await client.run('uptime');
|
||||||
|
print(utf8.decode(uptime));
|
||||||
|
```
|
||||||
|
|
||||||
|
Ignoring stderr:
|
||||||
|
```dart
|
||||||
|
final uptime = await client.run('uptime', stderr: false);
|
||||||
|
print(utf8.decode(uptime));
|
||||||
|
```
|
||||||
|
|
||||||
|
> `client.run()` is a convenience method that wraps `client.execute()` for running non-interactive commands.
|
||||||
|
|
||||||
|
### Start a process on remote host
|
||||||
|
```dart
|
||||||
|
final session = await client.execute('cat > file.txt');
|
||||||
|
await session.stdin.addStream(File('local_file.txt').openRead().cast());
|
||||||
|
await session.stdin.close(); // Close the sink to send EOF to the remote process.
|
||||||
|
|
||||||
|
await session.done; // Wait for session to exit to ensure all data is flushed to the remote process.
|
||||||
|
print(session.exitCode); // You can get the exit code after the session is done
|
||||||
|
```
|
||||||
|
|
||||||
|
> `session.write()` is a shorthand for `session.stdin.add()`. It's recommended to use `session.stdin.addStream()` instead of `session.write()` when you want to stream large amount of data to the remote process.
|
||||||
|
|
||||||
|
**Killing a remote process by sending signal**
|
||||||
|
|
||||||
|
```dart
|
||||||
|
session.kill(SSHSignal.KILL);
|
||||||
|
await session.done;
|
||||||
|
print('exitCode: ${session.exitCode}'); // -> exitCode: null
|
||||||
|
print('signal: ${session.exitSignal?.signalName}'); // -> signal: KILL
|
||||||
|
```
|
||||||
|
|
||||||
|
Processes killed by signals do not have an exit code, instead they have an exit signal property.
|
||||||
|
|
||||||
|
### Forward connections on local port 8080 to the server
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final serverSocket = await ServerSocket.bind('localhost', 8080);
|
||||||
|
await for (final socket in serverSocket) {
|
||||||
|
final forward = await client.forwardLocal('httpbin.org', 80);
|
||||||
|
forward.stream.cast<List<int>>().pipe(socket);
|
||||||
|
socket.pipe(forward.sink);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Forward connections to port 2222 on the server to local port 22
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final forward = await client.forwardRemote(port: 2222);
|
||||||
|
|
||||||
|
if (forward == null) {
|
||||||
|
print('Failed to forward remote port');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await for (final connection in forward.connections) {
|
||||||
|
final socket = await Socket.connect('localhost', 22);
|
||||||
|
connection.stream.cast<List<int>>().pipe(socket);
|
||||||
|
socket.pipe(connection.sink);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Authenticate with public keys
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: '<username>',
|
||||||
|
identities: [
|
||||||
|
// A single private key file may contain multiple keys.
|
||||||
|
...SSHKeyPair.fromPem(await File('path/to/id_rsa').readAsString())
|
||||||
|
],
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Use encrypted PEM files
|
||||||
|
```dart
|
||||||
|
// Test whether the private key is encrypted.
|
||||||
|
final encrypted = SSHKeyPair.isEncrypted(await File('path/to/id_rsa').readAsString());
|
||||||
|
print(encrypted);
|
||||||
|
|
||||||
|
// If the private key is encrypted, you need to provide the passphrase.
|
||||||
|
final keys = SSHKeyPair.fromPem('<pem text>', '<passphrase>');
|
||||||
|
print(keys);
|
||||||
|
```
|
||||||
|
|
||||||
|
Decrypt PEM file with [`compute`](https://api.flutter.dev/flutter/foundation/compute-constant.html) in Flutter
|
||||||
|
|
||||||
|
```dart
|
||||||
|
List<SSHKeyPair> decryptKeyPairs(List<String> args) {
|
||||||
|
return SSHKeyPair.fromPem(args[0], args[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
final keypairs = await compute(decryptKeyPairs, ['<pem text>', '<passphrase>']);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get the version of SSH server
|
||||||
|
|
||||||
|
```dart
|
||||||
|
await client.authenticated;
|
||||||
|
print(client.remoteVersion); // SSH-2.0-OpenSSH_7.4p1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Connect through a jump server
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final jumpServer = SSHClient(
|
||||||
|
await SSHSocket.connect('<jump server>', 22),
|
||||||
|
username: '...',
|
||||||
|
onPasswordRequest: () => '...',
|
||||||
|
);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
await jumpServer.forwardLocal('<target server>', 22),
|
||||||
|
username: '...',
|
||||||
|
onPasswordRequest: () => '...',
|
||||||
|
);
|
||||||
|
|
||||||
|
print(utf8.decode(await client.run('hostname'))); // -> hostname of <target server>
|
||||||
|
```
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
## SFTP
|
||||||
|
|
||||||
|
### List remote directory
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final items = await sftp.listdir('/');
|
||||||
|
for (final item in items) {
|
||||||
|
print(item.longname);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Read remote file
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final file = await sftp.open('/etc/passwd');
|
||||||
|
final content = await file.readBytes();
|
||||||
|
print(latin1.decode(content));
|
||||||
|
```
|
||||||
|
|
||||||
|
### Write remote file
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final file = await sftp.open('file.txt', mode: SftpFileOpenMode.write);
|
||||||
|
await file.writeBytes(utf8.encode('hello there!') as Uint8List);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Write at specific offset**
|
||||||
|
```dart
|
||||||
|
final data = utf8.encode('world') as Uint8List
|
||||||
|
await file.writeBytes(data, offset: 6);
|
||||||
|
```
|
||||||
|
|
||||||
|
### File upload
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final file = await sftp.open('file.txt', mode: SftpFileOpenMode.create | SftpFileOpenMode.write);
|
||||||
|
await file.write(File('local_file.txt').openRead().cast());
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Pause and resume file upload
|
||||||
|
```dart
|
||||||
|
final uploader = await file.write(File('local_file.txt').openRead().cast());
|
||||||
|
// ...
|
||||||
|
await uploader.pause();
|
||||||
|
// ...
|
||||||
|
await uploader.resume();
|
||||||
|
await uploader.done;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Clear the remote file before opening it**
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final file = await sftp.open('file.txt',
|
||||||
|
mode: SftpFileOpenMode.create | SftpFileOpenMode.truncate | SftpFileOpenMode.write
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Directory operations
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
await sftp.mkdir('/path/to/dir');
|
||||||
|
await sftp.rmdir('/path/to/dir');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get/Set attributes from/to remote file/directory
|
||||||
|
```dart
|
||||||
|
await sftp.stat('/path/to/file');
|
||||||
|
await sftp.setStat(
|
||||||
|
'/path/to/file',
|
||||||
|
SftpFileAttrs(mode: SftpFileMode(userRead: true)),
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get the type of a remote file
|
||||||
|
```dart
|
||||||
|
final stat = await sftp.stat('/path/to/file');
|
||||||
|
print(stat.type);
|
||||||
|
// or
|
||||||
|
print(stat.isDirectory);
|
||||||
|
print(stat.isSocket);
|
||||||
|
print(stat.isSymbolicLink);
|
||||||
|
// ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Create a link
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
sftp.link('/from', '/to');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get (estimated) total and free space on the remote filesystem
|
||||||
|
```dart
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final statvfs = await sftp.statvfs('/root');
|
||||||
|
print('total: ${statvfs.blockSize * statvfs.totalBlocks}');
|
||||||
|
print('free: ${statvfs.blockSize * statvfs.freeBlocks}');
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🪜 Example
|
||||||
|
|
||||||
|
### SSH client:
|
||||||
|
|
||||||
|
- [example/example.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/example.dart)
|
||||||
|
- [example/execute.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/execute.dart)
|
||||||
|
- [example/forward_local.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/forward_local.dart)
|
||||||
|
- [example/forward_remote.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/forward_remote.dart)
|
||||||
|
- [example/pubkey.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/pubkey.dart)
|
||||||
|
- [example/shell.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/shell.dart)
|
||||||
|
- [example/ssh_jump.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/ssh_jump.dart)
|
||||||
|
|
||||||
|
### SFTP:
|
||||||
|
- [example/sftp_read.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/sftp_read.dart)
|
||||||
|
- [example/sftp_list.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/sftp_list.dart)
|
||||||
|
- [example/sftp_stat.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/sftp_stat.dart)
|
||||||
|
- [example/sftp_upload.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/sftp_upload.dart)
|
||||||
|
- [example/sftp_filetype.dart](https://github.com/TerminalStudio/dartssh2/blob/master/example/sftp_filetype.dart)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🔐 Supported algorithms
|
||||||
|
|
||||||
|
**Host key**:
|
||||||
|
- `ssh-rsa`
|
||||||
|
- `rsa-sha2-[256|512]`
|
||||||
|
- `ecdsa-sha2-nistp[256|384|521]`
|
||||||
|
- `ssh-ed25519`
|
||||||
|
|
||||||
|
**Key exchange**:
|
||||||
|
- `curve25519-sha256`
|
||||||
|
- `ecdh-sha2-nistp[256|384|521] `
|
||||||
|
- `diffie-hellman-group-exchange-sha[1|256]`
|
||||||
|
- `diffie-hellman-group14-sha[1|256]`
|
||||||
|
- `diffie-hellman-group1-sha1 `
|
||||||
|
|
||||||
|
**Cipher**:
|
||||||
|
- `aes[128|192|256]-ctr`
|
||||||
|
- `aes[128|192|256]-cbc`
|
||||||
|
|
||||||
|
**Integrity**:
|
||||||
|
- `hmac-md5`
|
||||||
|
- `hmac-sha1`
|
||||||
|
- `hmac-sha2-[256|512]`
|
||||||
|
|
||||||
|
**Private key**:
|
||||||
|
|
||||||
|
| **Type** | **Decode** | **Decrypt** | **Encode** | **Encrypt** |
|
||||||
|
|---------------------|------------|-------------|------------|-------------|
|
||||||
|
| **RSA** | ✔️ | ✔️ | ✔️ | WIP |
|
||||||
|
| **OpenSSH RSA** | ✔️ | ✔️ | ✔️ | WIP |
|
||||||
|
| **OpenSSH ECDSA** | ✔️ | ✔️ | ✔️ | WIP |
|
||||||
|
| **OpenSSH Ed25519** | ✔️ | ✔️ | ✔️ | WIP |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## ⏳ Roadmap
|
||||||
|
|
||||||
|
- [x] Fix broken tests.
|
||||||
|
- [x] Sound null safety.
|
||||||
|
- [x] Redesign API to allow starting multiple sessions.
|
||||||
|
- [x] Full SFTP.
|
||||||
|
- [ ] Server.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- [`RFC 4250`](https://datatracker.ietf.org/doc/html/rfc4250) The Secure Shell (SSH) Protocol Assigned Numbers.
|
||||||
|
- [`RFC 4251`](https://datatracker.ietf.org/doc/html/rfc4251) The Secure Shell (SSH) Protocol Architecture.
|
||||||
|
- [`RFC 4252`](https://datatracker.ietf.org/doc/html/rfc4252) The Secure Shell (SSH) Authentication Protocol.
|
||||||
|
- [`RFC 4253`](https://datatracker.ietf.org/doc/html/rfc4253) The Secure Shell (SSH) Transport Layer Protocol.
|
||||||
|
- [`RFC 4254`](https://datatracker.ietf.org/doc/html/rfc4254) The Secure Shell (SSH) Connection Protocol.
|
||||||
|
- [`RFC 4255`](https://datatracker.ietf.org/doc/html/rfc4255) Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints.
|
||||||
|
- [`RFC 4256`](https://datatracker.ietf.org/doc/html/rfc4256) Generic Message Exchange Authentication for the Secure Shell Protocol (SSH).
|
||||||
|
- [`RFC 4419`](https://datatracker.ietf.org/doc/html/rfc4419) Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol.
|
||||||
|
- [`RFC 4716`](https://datatracker.ietf.org/doc/html/rfc4716) The Secure Shell (SSH) Public Key File Format.
|
||||||
|
- [`RFC 5656`](https://datatracker.ietf.org/doc/html/rfc5656) Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer.
|
||||||
|
- [`RFC 8332`](https://datatracker.ietf.org/doc/html/rfc8332) Use of RSA Keys with SHA-256 and SHA-512 in the Secure Shell (SSH) Protocol.
|
||||||
|
- [`RFC 8731`](https://datatracker.ietf.org/doc/html/rfc8731) Secure Shell (SSH) Key Exchange Method Using Curve25519 and Curve448.
|
||||||
|
- [`draft-miller-ssh-agent-03`](https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent-03) SSH Agent Protocol.
|
||||||
|
- [`draft-ietf-secsh-filexfer-02`](https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-02) SSH File Transfer Protocol.
|
||||||
|
- [`draft-dbider-sha2-mac-for-ssh-06`](https://datatracker.ietf.org/doc/html/draft-dbider-sha2-mac-for-ssh-06) SHA-2 Data Integrity Verification for the Secure Shell (SSH) Transport Layer Protocol.
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
- [https://github.com/GreenAppers/dartssh](https://github.com/GreenAppers/dartssh) by GreenAppers.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
dartssh is released under the terms of the MIT license. See [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
[dartssh]: https://github.com/GreenAppers/dartssh
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
include: package:lints/recommended.yaml
|
||||||
|
|
||||||
|
linter:
|
||||||
|
rules:
|
||||||
|
prefer_function_declarations_over_variables: false
|
||||||
|
|
||||||
|
analyzer:
|
||||||
|
plugins:
|
||||||
|
- dart_code_metrics_presets
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final uptime = await client.run('uptime');
|
||||||
|
print(utf8.decode(uptime));
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final client = SSHClient(
|
||||||
|
await SSHSocket.connect('localhost', 22),
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final session = await client.execute('cat > file.txt');
|
||||||
|
await File('local_file.txt').openRead().cast<Uint8List>().pipe(session.stdin);
|
||||||
|
|
||||||
|
await session.done;
|
||||||
|
print('done');
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await client.authenticated;
|
||||||
|
|
||||||
|
final serverSocket = await ServerSocket.bind('localhost', 8080);
|
||||||
|
|
||||||
|
print('Listening on ${serverSocket.address.address}:${serverSocket.port}');
|
||||||
|
|
||||||
|
await for (final socket in serverSocket) {
|
||||||
|
final forward = await client.forwardLocal('httpbin.org', 80);
|
||||||
|
forward.stream.cast<List<int>>().pipe(socket);
|
||||||
|
socket.cast<List<int>>().pipe(forward.sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await client.authenticated;
|
||||||
|
|
||||||
|
final forward = await client.forwardRemote(port: 2222);
|
||||||
|
|
||||||
|
if (forward == null) {
|
||||||
|
print('Failed to forward remote port');
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
print('Forwarding remote port 2222 to localhost:22');
|
||||||
|
|
||||||
|
await for (final connection in forward.connections) {
|
||||||
|
final socket = await Socket.connect('localhost', 22);
|
||||||
|
connection.stream.cast<List<int>>().pipe(socket);
|
||||||
|
socket.cast<List<int>>().pipe(connection.sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
identities: [
|
||||||
|
// A single private key file may contain multiple keys.
|
||||||
|
...SSHKeyPair.fromPem(await File('path/to/id_rsa').readAsString()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final uptime = await client.run('uptime');
|
||||||
|
print(utf8.decode(uptime));
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final files = await sftp.listdir('/');
|
||||||
|
|
||||||
|
for (var file in files) {
|
||||||
|
print('${file.filename} (${file.attr.type?.name})');
|
||||||
|
}
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final items = await sftp.listdir('/');
|
||||||
|
|
||||||
|
for (final item in items) {
|
||||||
|
print(item.longname);
|
||||||
|
}
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final file = await sftp.open('/etc/passwd');
|
||||||
|
final content = await file.readBytes();
|
||||||
|
print(latin1.decode(content));
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final stat = await sftp.stat('/usr');
|
||||||
|
print(stat.size);
|
||||||
|
print(stat.mode);
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final client = SSHClient(
|
||||||
|
await SSHSocket.connect('localhost', 22),
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
final file = await sftp.open(
|
||||||
|
'file.txt',
|
||||||
|
mode: SftpFileOpenMode.truncate | SftpFileOpenMode.write,
|
||||||
|
);
|
||||||
|
|
||||||
|
await file.write(File('local_file.txt').openRead().cast()).done;
|
||||||
|
print('done');
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final sftp = await client.sftp();
|
||||||
|
|
||||||
|
final file = await sftp.open(
|
||||||
|
'/root/test.txt',
|
||||||
|
mode: SftpFileOpenMode.create | SftpFileOpenMode.write,
|
||||||
|
);
|
||||||
|
|
||||||
|
await file.write(Stream.value(Utf8Encoder().convert('hello there!'))).done;
|
||||||
|
await file.close();
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final socket = await SSHSocket.connect('localhost', 22);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
socket,
|
||||||
|
username: 'root',
|
||||||
|
onPasswordRequest: () {
|
||||||
|
stdout.write('Password: ');
|
||||||
|
stdin.echoMode = false;
|
||||||
|
return stdin.readLineSync() ?? exit(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final shell = await client.shell();
|
||||||
|
stdout.addStream(shell.stdout);
|
||||||
|
stderr.addStream(shell.stderr);
|
||||||
|
stdin.cast<Uint8List>().listen(shell.write);
|
||||||
|
|
||||||
|
await shell.done;
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
await client.done;
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
final client = SSHClient(
|
||||||
|
await SSHSocket.connect('<ip>', 22),
|
||||||
|
username: '...',
|
||||||
|
onPasswordRequest: () => '...',
|
||||||
|
);
|
||||||
|
|
||||||
|
final httpClient = SSHHttpClient(client);
|
||||||
|
final request = httpClient.get(Uri.parse('http://httpbin.org/get'));
|
||||||
|
final response = await request.close();
|
||||||
|
print(response.body);
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
|
||||||
|
void main() async {
|
||||||
|
final jumpServer = SSHClient(
|
||||||
|
await SSHSocket.connect('<jump server>', 22),
|
||||||
|
username: '...',
|
||||||
|
onPasswordRequest: () => '...',
|
||||||
|
);
|
||||||
|
|
||||||
|
final client = SSHClient(
|
||||||
|
await jumpServer.forwardLocal('<target server>', 22),
|
||||||
|
username: '...',
|
||||||
|
onPasswordRequest: () => '...',
|
||||||
|
);
|
||||||
|
|
||||||
|
print(utf8.decode(await client.run('hostname')));
|
||||||
|
print(utf8.decode(await client.run('ifconfig')));
|
||||||
|
|
||||||
|
client.close();
|
||||||
|
jumpServer.close();
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
export 'src/ssh_algorithm.dart' show SSHAlgorithms;
|
||||||
|
export 'src/ssh_client.dart';
|
||||||
|
export 'src/ssh_errors.dart';
|
||||||
|
export 'src/ssh_forward.dart';
|
||||||
|
export 'src/ssh_key_pair.dart';
|
||||||
|
export 'src/ssh_pem.dart';
|
||||||
|
export 'src/ssh_session.dart';
|
||||||
|
export 'src/ssh_signal.dart';
|
||||||
|
export 'src/ssh_transport.dart';
|
||||||
|
|
||||||
|
export 'src/socket/ssh_socket.dart';
|
||||||
|
|
||||||
|
export 'src/algorithm/ssh_cipher_type.dart';
|
||||||
|
export 'src/algorithm/ssh_hostkey_type.dart';
|
||||||
|
export 'src/algorithm/ssh_kex_type.dart';
|
||||||
|
export 'src/algorithm/ssh_mac_type.dart';
|
||||||
|
|
||||||
|
export 'src/sftp/sftp_client.dart';
|
||||||
|
export 'src/sftp/sftp_errors.dart';
|
||||||
|
export 'src/sftp/sftp_file_open_mode.dart';
|
||||||
|
export 'src/sftp/sftp_file_attrs.dart';
|
||||||
|
export 'src/sftp/sftp_name.dart';
|
||||||
|
export 'src/sftp/sftp_status_code.dart';
|
||||||
|
export 'src/sftp/sftp_stream_io.dart';
|
||||||
|
|
||||||
|
export 'src/http/http_client.dart';
|
||||||
|
export 'src/http/http_exception.dart';
|
||||||
|
export 'src/http/http_content_type.dart';
|
||||||
|
export 'src/http/http_headers.dart';
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
class SSHCipherType with SSHAlgorithm {
|
||||||
|
static const values = [
|
||||||
|
aes128cbc,
|
||||||
|
aes192cbc,
|
||||||
|
aes256cbc,
|
||||||
|
aes128ctr,
|
||||||
|
aes192ctr,
|
||||||
|
aes256ctr,
|
||||||
|
];
|
||||||
|
|
||||||
|
static const aes128ctr = SSHCipherType._(
|
||||||
|
name: 'aes128-ctr',
|
||||||
|
keySize: 16,
|
||||||
|
cipherFactory: _aesCtrFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const aes192ctr = SSHCipherType._(
|
||||||
|
name: 'aes192-ctr',
|
||||||
|
keySize: 24,
|
||||||
|
cipherFactory: _aesCtrFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const aes256ctr = SSHCipherType._(
|
||||||
|
name: 'aes256-ctr',
|
||||||
|
keySize: 32,
|
||||||
|
cipherFactory: _aesCtrFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const aes128cbc = SSHCipherType._(
|
||||||
|
name: 'aes128-cbc',
|
||||||
|
keySize: 16,
|
||||||
|
cipherFactory: _aesCbcFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const aes192cbc = SSHCipherType._(
|
||||||
|
name: 'aes192-cbc',
|
||||||
|
keySize: 24,
|
||||||
|
cipherFactory: _aesCbcFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const aes256cbc = SSHCipherType._(
|
||||||
|
name: 'aes256-cbc',
|
||||||
|
keySize: 32,
|
||||||
|
cipherFactory: _aesCbcFactory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static SSHCipherType? fromName(String name) {
|
||||||
|
for (final value in values) {
|
||||||
|
if (value.name == name) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SSHCipherType._({
|
||||||
|
required this.name,
|
||||||
|
required this.keySize,
|
||||||
|
required this.cipherFactory,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The name of the algorithm. For example, `"aes256-ctr`"`.
|
||||||
|
@override
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
final int keySize;
|
||||||
|
|
||||||
|
final int ivSize = 16;
|
||||||
|
|
||||||
|
final int blockSize = 16;
|
||||||
|
|
||||||
|
final BlockCipher Function() cipherFactory;
|
||||||
|
|
||||||
|
BlockCipher createCipher(
|
||||||
|
Uint8List key,
|
||||||
|
Uint8List iv, {
|
||||||
|
required bool forEncryption,
|
||||||
|
}) {
|
||||||
|
if (key.length != keySize) {
|
||||||
|
throw ArgumentError.value(key, 'key', 'Key must be $keySize bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iv.length != ivSize) {
|
||||||
|
throw ArgumentError.value(iv, 'iv', 'IV must be $ivSize bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
final cipher = cipherFactory();
|
||||||
|
cipher.init(forEncryption, ParametersWithIV(KeyParameter(key), iv));
|
||||||
|
return cipher;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockCipher _aesCtrFactory() {
|
||||||
|
final aes = AESEngine();
|
||||||
|
return CTRBlockCipher(aes.blockSize, CTRStreamCipher(aes));
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockCipher _aesCbcFactory() {
|
||||||
|
return CBCBlockCipher(AESEngine());
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
|
||||||
|
class SSHHostkeyType with SSHAlgorithm {
|
||||||
|
static const rsaSha1 = SSHHostkeyType._('ssh-rsa');
|
||||||
|
static const rsaSha256 = SSHHostkeyType._('rsa-sha2-256');
|
||||||
|
static const rsaSha512 = SSHHostkeyType._('rsa-sha2-512');
|
||||||
|
static const ecdsa256 = SSHHostkeyType._('ecdsa-sha2-nistp256');
|
||||||
|
static const ecdsa384 = SSHHostkeyType._('ecdsa-sha2-nistp384');
|
||||||
|
static const ecdsa521 = SSHHostkeyType._('ecdsa-sha2-nistp521');
|
||||||
|
static const ed25519 = SSHHostkeyType._('ssh-ed25519');
|
||||||
|
|
||||||
|
const SSHHostkeyType._(this.name);
|
||||||
|
|
||||||
|
/// The name of the algorithm. For example, `"ssh-rsa`"`.
|
||||||
|
@override
|
||||||
|
final String name;
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
class SSHKexType with SSHAlgorithm {
|
||||||
|
static const x25519 = SSHKexType._(
|
||||||
|
name: 'curve25519-sha256@libssh.org',
|
||||||
|
digestFactory: digestSha256,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const nistp256 = SSHKexType._(
|
||||||
|
name: 'ecdh-sha2-nistp256',
|
||||||
|
digestFactory: digestSha256,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const nistp384 = SSHKexType._(
|
||||||
|
name: 'ecdh-sha2-nistp384',
|
||||||
|
digestFactory: digestSha384,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const nistp521 = SSHKexType._(
|
||||||
|
name: 'ecdh-sha2-nistp521',
|
||||||
|
digestFactory: digestSha512,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const dhGexSha256 = SSHKexType._(
|
||||||
|
name: 'diffie-hellman-group-exchange-sha256',
|
||||||
|
digestFactory: digestSha256,
|
||||||
|
isGroupExchange: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const dhGexSha1 = SSHKexType._(
|
||||||
|
name: 'diffie-hellman-group-exchange-sha1',
|
||||||
|
digestFactory: digestSha1,
|
||||||
|
isGroupExchange: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const dh14Sha1 = SSHKexType._(
|
||||||
|
name: 'diffie-hellman-group14-sha1',
|
||||||
|
digestFactory: digestSha1,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const dh14Sha256 = SSHKexType._(
|
||||||
|
name: 'diffie-hellman-group14-sha256',
|
||||||
|
digestFactory: digestSha256,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const dh1Sha1 = SSHKexType._(
|
||||||
|
name: 'diffie-hellman-group1-sha1',
|
||||||
|
digestFactory: digestSha1,
|
||||||
|
);
|
||||||
|
|
||||||
|
const SSHKexType._({
|
||||||
|
required this.name,
|
||||||
|
required this.digestFactory,
|
||||||
|
this.isGroupExchange = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The name of the algorithm. For example, `"ecdh-sha2-nistp256"`.
|
||||||
|
@override
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
final Digest Function() digestFactory;
|
||||||
|
|
||||||
|
final bool isGroupExchange;
|
||||||
|
|
||||||
|
Digest createDigest() => digestFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
Digest digestSha1() => SHA1Digest();
|
||||||
|
Digest digestSha256() => SHA256Digest();
|
||||||
|
Digest digestSha384() => SHA384Digest();
|
||||||
|
Digest digestSha512() => SHA512Digest();
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
class SSHMacType with SSHAlgorithm {
|
||||||
|
static const hmacMd5 = SSHMacType._(
|
||||||
|
name: 'hmac-md5',
|
||||||
|
keySize: 16,
|
||||||
|
macFactory: _hmacMd5Factory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const hmacSha1 = SSHMacType._(
|
||||||
|
name: 'hmac-sha1',
|
||||||
|
keySize: 20,
|
||||||
|
macFactory: _hmacSha1Factory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const hmacSha256 = SSHMacType._(
|
||||||
|
name: 'hmac-sha2-256',
|
||||||
|
keySize: 32,
|
||||||
|
macFactory: _hmacSha256Factory,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const hmacSha512 = SSHMacType._(
|
||||||
|
name: 'hmac-sha2-512',
|
||||||
|
keySize: 64,
|
||||||
|
macFactory: _hmacSha512Factory,
|
||||||
|
);
|
||||||
|
|
||||||
|
const SSHMacType._({
|
||||||
|
required this.name,
|
||||||
|
required this.keySize,
|
||||||
|
required this.macFactory,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The name of the algorithm. For example, `"aes256-ctr`"`.
|
||||||
|
@override
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// The length of the key in bytes. This is the same as the length of the
|
||||||
|
/// output of the MAC algorithm.
|
||||||
|
final int keySize;
|
||||||
|
|
||||||
|
final Mac Function() macFactory;
|
||||||
|
|
||||||
|
Mac createMac(Uint8List key) {
|
||||||
|
if (key.length != keySize) {
|
||||||
|
throw ArgumentError.value(key, 'key', 'Key must be $keySize bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
final mac = macFactory();
|
||||||
|
mac.init(KeyParameter(key));
|
||||||
|
return mac;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Mac _hmacMd5Factory() {
|
||||||
|
return HMac(MD5Digest(), 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
Mac _hmacSha1Factory() {
|
||||||
|
return HMac(SHA1Digest(), 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
Mac _hmacSha256Factory() {
|
||||||
|
return HMac(SHA256Digest(), 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
Mac _hmacSha512Factory() {
|
||||||
|
return HMac(SHA512Digest(), 128);
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_hostkey.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
class SSHEcdsaPublicKey implements SSHHostKey {
|
||||||
|
final String type;
|
||||||
|
|
||||||
|
final String curveId;
|
||||||
|
|
||||||
|
final Uint8List q;
|
||||||
|
|
||||||
|
SSHEcdsaPublicKey({
|
||||||
|
required this.type,
|
||||||
|
required this.curveId,
|
||||||
|
required this.q,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSHEcdsaPublicKey.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
if (!type.startsWith('ecdsa-sha2-')) {
|
||||||
|
throw Exception('Invalid key type: $type');
|
||||||
|
}
|
||||||
|
final curveId = reader.readUtf8();
|
||||||
|
final q = reader.readString();
|
||||||
|
return SSHEcdsaPublicKey(type: type, curveId: curveId, q: q);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
writer.writeUtf8(curveId);
|
||||||
|
writer.writeString(q);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verify(
|
||||||
|
Uint8List message,
|
||||||
|
SSHEcdsaSignature signature,
|
||||||
|
) {
|
||||||
|
final signer = ECDSASigner(curveHash);
|
||||||
|
|
||||||
|
signer.init(
|
||||||
|
false,
|
||||||
|
PublicKeyParameter(
|
||||||
|
ECPublicKey(curve.curve.decodePoint(q), curve),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return signer.verifySignature(
|
||||||
|
message,
|
||||||
|
ECSignature(signature.r, signature.s),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ECDomainParameters get curve {
|
||||||
|
switch (curveId) {
|
||||||
|
case 'nistp256':
|
||||||
|
return ECCurve_secp256r1();
|
||||||
|
case 'nistp384':
|
||||||
|
return ECCurve_secp384r1();
|
||||||
|
case 'nistp521':
|
||||||
|
return ECCurve_secp521r1();
|
||||||
|
default:
|
||||||
|
throw Exception('Unsupported curve: $curveId');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Digest get curveHash {
|
||||||
|
switch (curveId) {
|
||||||
|
case 'nistp256':
|
||||||
|
return SHA256Digest();
|
||||||
|
case 'nistp384':
|
||||||
|
return SHA384Digest();
|
||||||
|
case 'nistp521':
|
||||||
|
return SHA512Digest();
|
||||||
|
default:
|
||||||
|
throw Exception('Unsupported curve: $curveId');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHEcdsaKey(type: $type, curveId: $curveId, q: ${hex.encode(q)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHEcdsaSignature implements SSHSignature {
|
||||||
|
final String type;
|
||||||
|
|
||||||
|
final BigInt r;
|
||||||
|
|
||||||
|
final BigInt s;
|
||||||
|
|
||||||
|
SSHEcdsaSignature(this.type, this.r, this.s);
|
||||||
|
|
||||||
|
factory SSHEcdsaSignature.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
if (!type.startsWith('ecdsa-sha2-')) {
|
||||||
|
throw FormatException('Invalid signature type: $type');
|
||||||
|
}
|
||||||
|
final blobReader = SSHMessageReader(reader.readString());
|
||||||
|
final r = blobReader.readMpint();
|
||||||
|
final s = blobReader.readMpint();
|
||||||
|
return SSHEcdsaSignature(type, r, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
final blobWriter = SSHMessageWriter();
|
||||||
|
blobWriter.writeMpint(r);
|
||||||
|
blobWriter.writeMpint(s);
|
||||||
|
writer.writeString(blobWriter.takeBytes());
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHEcdsaSignature($type)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_hostkey.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:pinenacl/ed25519.dart';
|
||||||
|
|
||||||
|
class SSHEd25519PublicKey implements SSHHostKey {
|
||||||
|
static const type = 'ssh-ed25519';
|
||||||
|
|
||||||
|
final Uint8List key;
|
||||||
|
|
||||||
|
SSHEd25519PublicKey(this.key);
|
||||||
|
|
||||||
|
factory SSHEd25519PublicKey.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
if (type != SSHEd25519PublicKey.type) {
|
||||||
|
throw Exception('Invalid key type: $type');
|
||||||
|
}
|
||||||
|
final key = reader.readString();
|
||||||
|
return SSHEd25519PublicKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
writer.writeString(key);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies Ed25519 [signature] on [message] with private key matching [publicKey].
|
||||||
|
bool verify(Uint8List message, SSHEd25519Signature signature) {
|
||||||
|
// tweetnacl.Signature(publicKey.key!, null).detached_verify(message, signature.sig!);
|
||||||
|
return VerifyKey(key).verify(
|
||||||
|
signature: Signature(signature.signature),
|
||||||
|
message: message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHEd25519Key(${hex.encode(key)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHEd25519Signature implements SSHSignature {
|
||||||
|
static const type = 'ssh-ed25519';
|
||||||
|
|
||||||
|
final Uint8List signature;
|
||||||
|
|
||||||
|
SSHEd25519Signature(this.signature);
|
||||||
|
|
||||||
|
factory SSHEd25519Signature.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
if (type != SSHEd25519Signature.type) {
|
||||||
|
throw Exception('Invalid signature type: $type');
|
||||||
|
}
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSHEd25519Signature(signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
writer.writeString(signature);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHEd25519Signature(${hex.encode(signature)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_hostkey.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
import 'package:pinenacl/ed25519.dart';
|
||||||
|
import 'package:pointycastle/api.dart' hide Signature;
|
||||||
|
import 'package:pointycastle/asymmetric/api.dart' as asymmetric;
|
||||||
|
import 'package:pointycastle/digests/sha1.dart';
|
||||||
|
import 'package:pointycastle/digests/sha256.dart';
|
||||||
|
import 'package:pointycastle/digests/sha512.dart';
|
||||||
|
import 'package:pointycastle/random/fortuna_random.dart';
|
||||||
|
import 'package:pointycastle/signers/rsa_signer.dart';
|
||||||
|
|
||||||
|
class SSHRsaPublicKey implements SSHHostKey {
|
||||||
|
static const type = 'ssh-rsa';
|
||||||
|
|
||||||
|
final BigInt e;
|
||||||
|
|
||||||
|
final BigInt n;
|
||||||
|
|
||||||
|
SSHRsaPublicKey(this.e, this.n);
|
||||||
|
|
||||||
|
factory SSHRsaPublicKey.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
if (type != SSHRsaPublicKey.type) {
|
||||||
|
throw Exception('Invalid key type: $type');
|
||||||
|
}
|
||||||
|
final e = reader.readMpint();
|
||||||
|
final n = reader.readMpint();
|
||||||
|
return SSHRsaPublicKey(e, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
writer.writeMpint(e);
|
||||||
|
writer.writeMpint(n);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verify(Uint8List message, SSHRsaSignature signature) {
|
||||||
|
late RSASigner signer;
|
||||||
|
|
||||||
|
switch (signature.type) {
|
||||||
|
case SSHRsaSignatureType.sha1:
|
||||||
|
signer = RSASigner(SHA1Digest(), '06052b0e03021a');
|
||||||
|
break;
|
||||||
|
case SSHRsaSignatureType.sha256:
|
||||||
|
signer = RSASigner(SHA256Digest(), '0609608648016503040201');
|
||||||
|
break;
|
||||||
|
case SSHRsaSignatureType.sha512:
|
||||||
|
signer = RSASigner(SHA512Digest(), '0609608648016503040203');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw FormatException('Unknown signature type: ${signature.type}');
|
||||||
|
}
|
||||||
|
|
||||||
|
signer.init(
|
||||||
|
false,
|
||||||
|
ParametersWithRandom(
|
||||||
|
PublicKeyParameter<asymmetric.RSAPublicKey>(
|
||||||
|
asymmetric.RSAPublicKey(n, e),
|
||||||
|
),
|
||||||
|
FortunaRandom(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return signer.verifySignature(
|
||||||
|
message,
|
||||||
|
asymmetric.RSASignature(signature.signature),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHRsaKey($type, n: $n, e: $e)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class SSHRsaSignatureType {
|
||||||
|
static const sha1 = 'ssh-rsa';
|
||||||
|
static const sha256 = 'rsa-sha2-256';
|
||||||
|
static const sha512 = 'rsa-sha2-512';
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHRsaSignature implements SSHSignature {
|
||||||
|
final String type;
|
||||||
|
|
||||||
|
final Uint8List signature;
|
||||||
|
|
||||||
|
SSHRsaSignature(this.type, this.signature);
|
||||||
|
|
||||||
|
factory SSHRsaSignature.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSHRsaSignature(type, signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(type);
|
||||||
|
writer.writeString(signature);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHRsaSignature(${hex.encode(signature)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
+671
@@ -0,0 +1,671 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/http/http_exception.dart';
|
||||||
|
import 'package:dartssh2/src/http/line_decoder.dart';
|
||||||
|
import 'package:dartssh2/src/http/http_content_type.dart';
|
||||||
|
import 'package:dartssh2/src/http/http_headers.dart';
|
||||||
|
import 'package:dartssh2/src/socket/ssh_socket.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_client.dart';
|
||||||
|
|
||||||
|
/// A HTTP client that works over SSH port forwarding.
|
||||||
|
///
|
||||||
|
/// This is a very basic implementation of a HTTP client, has the following
|
||||||
|
/// limitations:
|
||||||
|
///
|
||||||
|
/// * Only supports HTTP/1.0 and HTTP/1.1
|
||||||
|
/// * Only supports "identity" encoding
|
||||||
|
/// * No keep-alive
|
||||||
|
/// * No automatic redirects
|
||||||
|
/// * No support for https
|
||||||
|
///
|
||||||
|
/// This client intends to be used for communicating with services on the ssh
|
||||||
|
/// host that are easier to communicate with using HTTP. *Not* for communicating
|
||||||
|
/// with API endpoints on the internet.
|
||||||
|
class SSHHttpClient {
|
||||||
|
const SSHHttpClient(this.client);
|
||||||
|
|
||||||
|
final SSHClient client;
|
||||||
|
|
||||||
|
/// Send a HTTP request to [uri] with the provided [method].
|
||||||
|
SSHHttpClientRequest request(String method, Uri uri, bool body) {
|
||||||
|
final request = SSHHttpClientRequest._(client, method, uri, body);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a GET request to the provided URL.
|
||||||
|
SSHHttpClientRequest get(Uri uri) => request('GET', uri, false);
|
||||||
|
|
||||||
|
/// Send a POST request to the provided URL.
|
||||||
|
SSHHttpClientRequest post(Uri uri) => request('POST', uri, true);
|
||||||
|
|
||||||
|
/// Send a DELETE request to the provided URL.
|
||||||
|
SSHHttpClientRequest delete(Uri uri) => request('DELETE', uri, false);
|
||||||
|
|
||||||
|
/// Send a PUT request to the provided URL.
|
||||||
|
SSHHttpClientRequest put(Uri uri) => request('PUT', uri, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Version of HTTP to use for the request.
|
||||||
|
enum SSHHttpProtocolVersion {
|
||||||
|
http10('1.0'),
|
||||||
|
|
||||||
|
http11('1.1'),
|
||||||
|
;
|
||||||
|
|
||||||
|
const SSHHttpProtocolVersion(this.name);
|
||||||
|
|
||||||
|
final String name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP request created on a [SSHHttpClient].
|
||||||
|
class SSHHttpClientRequest {
|
||||||
|
/// The underlying SSH client.
|
||||||
|
final SSHClient client;
|
||||||
|
|
||||||
|
/// The headers associated with the HTTP request.
|
||||||
|
late final SSHHttpHeaders headers = _SSHHttpClientRequestHeaders(this);
|
||||||
|
|
||||||
|
/// The type of HTTP request being made.
|
||||||
|
final String method;
|
||||||
|
|
||||||
|
/// The Uri the HTTP request will be sent to.
|
||||||
|
final Uri uri;
|
||||||
|
|
||||||
|
/// The default encoding for the HTTP request (UTF8).
|
||||||
|
final Encoding encoding = utf8;
|
||||||
|
|
||||||
|
/// The body of the HTTP request. This can be empty if there is no body
|
||||||
|
/// associated with the request.
|
||||||
|
final BytesBuilder? _body;
|
||||||
|
|
||||||
|
/// The HTTP protocol version used for the request. Defaults to HTTP/1.1.
|
||||||
|
///
|
||||||
|
/// Set this to [SSHHttpProtocolVersion.http10] to avoid the server from
|
||||||
|
/// sending a `Transfer-Encoding: chunked` response.
|
||||||
|
var protocolVersion = SSHHttpProtocolVersion.http11;
|
||||||
|
|
||||||
|
/// The length of the request body. Is set to `-1` when no body exists.
|
||||||
|
int get contentLength => hasBody ? _body!.length : -1;
|
||||||
|
|
||||||
|
/// Whether or not the HTTP request has a body.
|
||||||
|
bool get hasBody => _body != null;
|
||||||
|
|
||||||
|
SSHHttpClientRequest._(this.client, this.method, this.uri, bool body)
|
||||||
|
: _body = body ? BytesBuilder() : null;
|
||||||
|
|
||||||
|
/// Write content into the body of the HTTP request.
|
||||||
|
void write(Object? obj) {
|
||||||
|
if (hasBody) {
|
||||||
|
if (obj != null) {
|
||||||
|
_body!.add(encoding.encoder.convert(obj.toString()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw StateError('write not allowed for method $method');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send the HTTP request and get the response.
|
||||||
|
Future<SSHHttpClientResponse> close() async {
|
||||||
|
var queryString = '';
|
||||||
|
if (uri.hasQuery) {
|
||||||
|
final query = StringBuffer();
|
||||||
|
query.write('?');
|
||||||
|
uri.queryParameters.forEach((k, v) {
|
||||||
|
query.write(Uri.encodeComponent(k));
|
||||||
|
query.write('=');
|
||||||
|
query.write(Uri.encodeComponent(v));
|
||||||
|
query.write('&');
|
||||||
|
});
|
||||||
|
queryString = query.toString().substring(0, query.length - 1);
|
||||||
|
}
|
||||||
|
final buffer = StringBuffer();
|
||||||
|
|
||||||
|
final path = uri.path.isEmpty ? '/' : uri.path;
|
||||||
|
|
||||||
|
buffer.write('$method $path$queryString HTTP/${protocolVersion.name}\r\n');
|
||||||
|
|
||||||
|
headers.forEach((name, values) {
|
||||||
|
for (var value in values) {
|
||||||
|
buffer.write('$name: $value\r\n');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
buffer.write('\r\n');
|
||||||
|
|
||||||
|
if (hasBody) {
|
||||||
|
buffer.write(String.fromCharCodes(_body!.takeBytes()));
|
||||||
|
}
|
||||||
|
|
||||||
|
final socket = await client.forwardLocal(uri.host, uri.port);
|
||||||
|
socket.sink.add(buffer.toString().codeUnits);
|
||||||
|
return SSHHttpClientResponse.from(socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SSHHttpClientRequestHeaders implements SSHHttpHeaders {
|
||||||
|
final Map<String, List<String>> _headers = <String, List<String>>{};
|
||||||
|
|
||||||
|
final SSHHttpClientRequest _request;
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHContentType? contentType;
|
||||||
|
|
||||||
|
_SSHHttpClientRequestHeaders(this._request);
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<String>? operator [](String name) {
|
||||||
|
switch (name) {
|
||||||
|
case SSHHttpHeaders.acceptCharsetHeader:
|
||||||
|
return ['utf-8'];
|
||||||
|
case SSHHttpHeaders.acceptEncodingHeader:
|
||||||
|
return ['identity'];
|
||||||
|
case SSHHttpHeaders.connectionHeader:
|
||||||
|
return ['close'];
|
||||||
|
case SSHHttpHeaders.contentLengthHeader:
|
||||||
|
if (!_request.hasBody) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return [contentLength.toString()];
|
||||||
|
case SSHHttpHeaders.contentTypeHeader:
|
||||||
|
if (contentType == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return [contentType.toString()];
|
||||||
|
case SSHHttpHeaders.hostHeader:
|
||||||
|
return ['$host:$port'];
|
||||||
|
default:
|
||||||
|
final values = _headers[name];
|
||||||
|
if (values == null || values.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return values.map<String>((e) => e.toString()).toList(growable: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add [value] to the list of values associated with header [name].
|
||||||
|
@override
|
||||||
|
void add(String name, Object value, {bool preserveHeaderCase = false}) {
|
||||||
|
switch (name) {
|
||||||
|
case SSHHttpHeaders.acceptCharsetHeader:
|
||||||
|
case SSHHttpHeaders.acceptEncodingHeader:
|
||||||
|
case SSHHttpHeaders.connectionHeader:
|
||||||
|
case SSHHttpHeaders.contentLengthHeader:
|
||||||
|
case SSHHttpHeaders.dateHeader:
|
||||||
|
case SSHHttpHeaders.expiresHeader:
|
||||||
|
case SSHHttpHeaders.ifModifiedSinceHeader:
|
||||||
|
case SSHHttpHeaders.hostHeader:
|
||||||
|
throw UnsupportedError('Unsupported or immutable property: $name');
|
||||||
|
case SSHHttpHeaders.contentTypeHeader:
|
||||||
|
contentType = value as SSHContentType?;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (_headers[name] == null) {
|
||||||
|
_headers[name] = <String>[];
|
||||||
|
}
|
||||||
|
_headers[name]!.add(value as String);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove [value] from the list associated with header [name].
|
||||||
|
@override
|
||||||
|
void remove(String name, Object value) {
|
||||||
|
switch (name) {
|
||||||
|
case SSHHttpHeaders.acceptCharsetHeader:
|
||||||
|
case SSHHttpHeaders.acceptEncodingHeader:
|
||||||
|
case SSHHttpHeaders.connectionHeader:
|
||||||
|
case SSHHttpHeaders.contentLengthHeader:
|
||||||
|
case SSHHttpHeaders.dateHeader:
|
||||||
|
case SSHHttpHeaders.expiresHeader:
|
||||||
|
case SSHHttpHeaders.ifModifiedSinceHeader:
|
||||||
|
case SSHHttpHeaders.hostHeader:
|
||||||
|
throw UnsupportedError('Unsupported or immutable property: $name');
|
||||||
|
case SSHHttpHeaders.contentTypeHeader:
|
||||||
|
if (contentType == value) {
|
||||||
|
contentType = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (_headers[name] != null) {
|
||||||
|
_headers[name]!.remove(value);
|
||||||
|
if (_headers[name]!.isEmpty) {
|
||||||
|
_headers.remove(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove all headers associated with key [name].
|
||||||
|
@override
|
||||||
|
void removeAll(String name) {
|
||||||
|
switch (name) {
|
||||||
|
case SSHHttpHeaders.acceptCharsetHeader:
|
||||||
|
case SSHHttpHeaders.acceptEncodingHeader:
|
||||||
|
case SSHHttpHeaders.connectionHeader:
|
||||||
|
case SSHHttpHeaders.contentLengthHeader:
|
||||||
|
case SSHHttpHeaders.dateHeader:
|
||||||
|
case SSHHttpHeaders.expiresHeader:
|
||||||
|
case SSHHttpHeaders.ifModifiedSinceHeader:
|
||||||
|
case SSHHttpHeaders.hostHeader:
|
||||||
|
throw UnsupportedError('Unsupported or immutable property: $name');
|
||||||
|
case SSHHttpHeaders.contentTypeHeader:
|
||||||
|
contentType = null;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
_headers.remove(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace values associated with key [name] with [value].
|
||||||
|
@override
|
||||||
|
void set(String name, Object value, {bool preserveHeaderCase = false}) {
|
||||||
|
removeAll(name);
|
||||||
|
add(name, value, preserveHeaderCase: preserveHeaderCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the values associated with key [name], if it exists, otherwise
|
||||||
|
/// returns null.
|
||||||
|
@override
|
||||||
|
String? value(String name) {
|
||||||
|
final val = this[name];
|
||||||
|
if (val == null || val.isEmpty) {
|
||||||
|
return null;
|
||||||
|
} else if (val.length == 1) {
|
||||||
|
return val[0];
|
||||||
|
} else {
|
||||||
|
throw SSHHttpException('header $name has more than one value');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterates over all header key-value pairs and applies [f].
|
||||||
|
@override
|
||||||
|
void forEach(void Function(String name, List<String> values) f) {
|
||||||
|
void forEachFunc(String name) {
|
||||||
|
final values = this[name];
|
||||||
|
if (values != null && values.isNotEmpty) {
|
||||||
|
f(name, values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[
|
||||||
|
SSHHttpHeaders.acceptCharsetHeader,
|
||||||
|
SSHHttpHeaders.acceptEncodingHeader,
|
||||||
|
SSHHttpHeaders.connectionHeader,
|
||||||
|
SSHHttpHeaders.contentLengthHeader,
|
||||||
|
SSHHttpHeaders.contentTypeHeader,
|
||||||
|
SSHHttpHeaders.hostHeader,
|
||||||
|
].forEach(forEachFunc);
|
||||||
|
_headers.keys.forEach(forEachFunc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get chunkedTransferEncoding =>
|
||||||
|
value(SSHHttpHeaders.transferEncodingHeader)?.toLowerCase() == 'chunked';
|
||||||
|
|
||||||
|
@override
|
||||||
|
set chunkedTransferEncoding(bool chunkedTransferEncoding) {
|
||||||
|
throw UnsupportedError('chunked transfer is unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get contentLength => _request.contentLength;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set contentLength(int contentLength) {
|
||||||
|
throw UnsupportedError('content length is automatically set');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set date(DateTime? date) {
|
||||||
|
throw UnsupportedError('date is unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get date => null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set expires(DateTime? expires) {
|
||||||
|
throw UnsupportedError('expires is unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get expires => null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set host(String? host) {
|
||||||
|
throw UnsupportedError('host is automatically set');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get host => _request.uri.host;
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get ifModifiedSince => null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set ifModifiedSince(DateTime? ifModifiedSince) {
|
||||||
|
throw UnsupportedError('if modified since is unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void noFolding(String name) {
|
||||||
|
throw UnsupportedError('no folding is unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get persistentConnection => false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set persistentConnection(bool persistentConnection) {
|
||||||
|
throw UnsupportedError('persistence connections are unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set port(int? port) {
|
||||||
|
throw UnsupportedError('port is automatically set');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get port => _request.uri.port;
|
||||||
|
|
||||||
|
/// Clear all header key-value pairs.
|
||||||
|
@override
|
||||||
|
void clear() {
|
||||||
|
contentType = null;
|
||||||
|
_headers.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP response for a [SSHHttpClientRequest].
|
||||||
|
class SSHHttpClientResponse {
|
||||||
|
/// The headers associated with the HTTP response.
|
||||||
|
final SSHHttpHeaders headers;
|
||||||
|
|
||||||
|
/// A short textual description of the status code associated with the HTTP
|
||||||
|
/// response.
|
||||||
|
final String? reasonPhrase;
|
||||||
|
|
||||||
|
/// The resulting HTTP status code associated with the HTTP response.
|
||||||
|
final int? statusCode;
|
||||||
|
|
||||||
|
/// The body of the HTTP response.
|
||||||
|
final String? body;
|
||||||
|
|
||||||
|
/// The length of the body associated with the HTTP response.
|
||||||
|
int get contentLength => headers.contentLength;
|
||||||
|
|
||||||
|
SSHHttpClientResponse._(
|
||||||
|
Map<String, List<String>> headers, {
|
||||||
|
this.reasonPhrase,
|
||||||
|
this.statusCode,
|
||||||
|
this.body,
|
||||||
|
}) : headers = _SSHHttpClientResponseHeaders(headers);
|
||||||
|
|
||||||
|
/// Creates an instance of [SSHHttpClientResponse] that contains the response
|
||||||
|
/// sent by the HTTP server over [socket].
|
||||||
|
static Future<SSHHttpClientResponse> from(SSHSocket socket) async {
|
||||||
|
int? statusCode;
|
||||||
|
String? reasonPhrase;
|
||||||
|
final body = StringBuffer();
|
||||||
|
final headers = <String, List<String>>{};
|
||||||
|
|
||||||
|
var inHeader = false;
|
||||||
|
var inBody = false;
|
||||||
|
var contentLength = 0;
|
||||||
|
var contentRead = 0;
|
||||||
|
|
||||||
|
void processLine(String line, int bytesRead, LineDecoder decoder) {
|
||||||
|
if (inBody) {
|
||||||
|
body.write(line);
|
||||||
|
contentRead += bytesRead;
|
||||||
|
} else if (inHeader) {
|
||||||
|
if (line.trim().isEmpty) {
|
||||||
|
inBody = true;
|
||||||
|
if (contentLength > 0) {
|
||||||
|
decoder.expectedByteCount = contentLength;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final separator = line.indexOf(':');
|
||||||
|
final name = line.substring(0, separator).toLowerCase().trim();
|
||||||
|
final value = line.substring(separator + 1).trim();
|
||||||
|
if (name == SSHHttpHeaders.transferEncodingHeader &&
|
||||||
|
value.toLowerCase() != 'identity') {
|
||||||
|
throw UnsupportedError('only identity transfer encoding is accepted');
|
||||||
|
}
|
||||||
|
if (name == SSHHttpHeaders.contentLengthHeader) {
|
||||||
|
contentLength = int.parse(value);
|
||||||
|
}
|
||||||
|
if (!headers.containsKey(name)) {
|
||||||
|
headers[name] = [];
|
||||||
|
}
|
||||||
|
headers[name]!.add(value);
|
||||||
|
} else if (line.startsWith('HTTP/1.1') || line.startsWith('HTTP/1.0')) {
|
||||||
|
statusCode = int.parse(
|
||||||
|
line.substring('HTTP/1.x '.length, 'HTTP/1.x xxx'.length),
|
||||||
|
);
|
||||||
|
reasonPhrase = line.substring('HTTP/1.x xxx '.length);
|
||||||
|
inHeader = true;
|
||||||
|
} else {
|
||||||
|
throw UnsupportedError('unsupported http response format');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final lineDecoder = LineDecoder.withCallback(processLine);
|
||||||
|
|
||||||
|
await for (final chunk in socket.stream) {
|
||||||
|
if (!inHeader ||
|
||||||
|
!inBody ||
|
||||||
|
((contentRead + lineDecoder.bufferedBytes) < contentLength)) {
|
||||||
|
lineDecoder.add(chunk);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
lineDecoder.close();
|
||||||
|
} finally {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// try {
|
||||||
|
// while (!inHeader ||
|
||||||
|
// !inBody ||
|
||||||
|
// ((contentRead + lineDecoder.bufferedBytes) < contentLength)) {
|
||||||
|
// final bytes = socket.readSync(1024);
|
||||||
|
|
||||||
|
// if (bytes == null || bytes.isEmpty) {
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
// lineDecoder.add(bytes);
|
||||||
|
// }
|
||||||
|
// } finally {
|
||||||
|
// try {
|
||||||
|
// lineDecoder.close();
|
||||||
|
// } finally {
|
||||||
|
// socket.closeSync();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
return SSHHttpClientResponse._(
|
||||||
|
headers,
|
||||||
|
reasonPhrase: reasonPhrase,
|
||||||
|
statusCode: statusCode,
|
||||||
|
body: body.toString(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SSHHttpClientResponseHeaders implements SSHHttpHeaders {
|
||||||
|
final Map<String, List<String>> _headers;
|
||||||
|
|
||||||
|
_SSHHttpClientResponseHeaders(this._headers);
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<String>? operator [](String name) => _headers[name];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void add(String name, Object value, {bool preserveHeaderCase = false}) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get chunkedTransferEncoding =>
|
||||||
|
value(SSHHttpHeaders.transferEncodingHeader)?.toLowerCase() == 'chunked';
|
||||||
|
|
||||||
|
@override
|
||||||
|
set chunkedTransferEncoding(bool chunkedTransferEncoding) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get contentLength {
|
||||||
|
final val = value(SSHHttpHeaders.contentLengthHeader);
|
||||||
|
if (val != null) {
|
||||||
|
final parsed = int.tryParse(val);
|
||||||
|
if (parsed != null) {
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set contentLength(int contentLength) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHContentType? get contentType {
|
||||||
|
final val = value(SSHHttpHeaders.contentTypeHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return SSHContentType.parse(val);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set contentType(SSHContentType? contentType) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set date(DateTime? date) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get date {
|
||||||
|
final val = value(SSHHttpHeaders.dateHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return DateTime.parse(val);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set expires(DateTime? expires) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get expires {
|
||||||
|
final val = value(SSHHttpHeaders.expiresHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return DateTime.parse(val);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void forEach(void Function(String name, List<String> values) f) =>
|
||||||
|
_headers.forEach(f);
|
||||||
|
|
||||||
|
@override
|
||||||
|
set host(String? host) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String? get host {
|
||||||
|
final val = value(SSHHttpHeaders.hostHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return Uri.parse(val).host;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
DateTime? get ifModifiedSince {
|
||||||
|
final val = value(SSHHttpHeaders.ifModifiedSinceHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return DateTime.parse(val);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set ifModifiedSince(DateTime? ifModifiedSince) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void noFolding(String name) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get persistentConnection => false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set persistentConnection(bool persistentConnection) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set port(int? port) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
int? get port {
|
||||||
|
final val = value(SSHHttpHeaders.hostHeader);
|
||||||
|
if (val != null) {
|
||||||
|
return Uri.parse(val).port;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void remove(String name, Object value) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void removeAll(String name) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void set(String name, Object value, {bool preserveHeaderCase = false}) {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String? value(String name) {
|
||||||
|
final val = this[name];
|
||||||
|
if (val == null || val.isEmpty) {
|
||||||
|
return null;
|
||||||
|
} else if (val.length == 1) {
|
||||||
|
return val[0];
|
||||||
|
} else {
|
||||||
|
throw SSHHttpException('header $name has more than one value');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void clear() {
|
||||||
|
throw UnsupportedError('Response headers are immutable');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
import 'dart:collection';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/http/http_exception.dart';
|
||||||
|
import 'package:dartssh2/src/http/http_headers.dart';
|
||||||
|
|
||||||
|
/// A MIME/IANA media type used as the value of the
|
||||||
|
/// [SSHHttpHeaders.contentTypeHeader] header.
|
||||||
|
///
|
||||||
|
/// A [SSHContentType] is immutable.
|
||||||
|
abstract class SSHContentType {
|
||||||
|
/// Content type for plain text using UTF-8 encoding.
|
||||||
|
///
|
||||||
|
/// text/plain; charset=utf-8
|
||||||
|
static final text = SSHContentType("text", "plain", charset: "utf-8");
|
||||||
|
|
||||||
|
/// Content type for HTML using UTF-8 encoding.
|
||||||
|
///
|
||||||
|
/// text/html; charset=utf-8
|
||||||
|
static final html = SSHContentType("text", "html", charset: "utf-8");
|
||||||
|
|
||||||
|
/// Content type for JSON using UTF-8 encoding.
|
||||||
|
///
|
||||||
|
/// application/json; charset=utf-8
|
||||||
|
static final json = SSHContentType("application", "json", charset: "utf-8");
|
||||||
|
|
||||||
|
/// Content type for binary data.
|
||||||
|
///
|
||||||
|
/// application/octet-stream
|
||||||
|
static final binary = SSHContentType("application", "octet-stream");
|
||||||
|
|
||||||
|
/// Creates a new content type object setting the primary type and
|
||||||
|
/// sub type. The charset and additional parameters can also be set
|
||||||
|
/// using [charset] and [parameters]. If charset is passed and
|
||||||
|
/// [parameters] contains charset as well the passed [charset] will
|
||||||
|
/// override the value in parameters. Keys passed in parameters will be
|
||||||
|
/// converted to lower case. The `charset` entry, whether passed as `charset`
|
||||||
|
/// or in `parameters`, will have its value converted to lower-case.
|
||||||
|
factory SSHContentType(
|
||||||
|
String primaryType,
|
||||||
|
String subType, {
|
||||||
|
String? charset,
|
||||||
|
Map<String, String?> parameters = const {},
|
||||||
|
}) {
|
||||||
|
return _ContentType(primaryType, subType, charset, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new content type object from parsing a Content-Type
|
||||||
|
/// header value. As primary type, sub type and parameter names and
|
||||||
|
/// values are not case sensitive all these values will be converted
|
||||||
|
/// to lower case. Parsing this string
|
||||||
|
///
|
||||||
|
/// text/html; charset=utf-8
|
||||||
|
///
|
||||||
|
/// will create a content type object with primary type "text",
|
||||||
|
/// subtype "html" and parameter "charset" with value "utf-8".
|
||||||
|
/// There may be more parameters supplied, but they are not recognized
|
||||||
|
/// by this class.
|
||||||
|
static SSHContentType parse(String value) {
|
||||||
|
return _ContentType.parse(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the MIME type and subtype, without any parameters.
|
||||||
|
///
|
||||||
|
/// For the full content type `text/html;charset=utf-8`,
|
||||||
|
/// the [mimeType] value is the string `text/html`.
|
||||||
|
String get mimeType;
|
||||||
|
|
||||||
|
/// Gets the primary type.
|
||||||
|
///
|
||||||
|
/// For the full content type `text/html;charset=utf-8`,
|
||||||
|
/// the [primaryType] value is the string `text`.
|
||||||
|
String get primaryType;
|
||||||
|
|
||||||
|
/// Gets the subtype.
|
||||||
|
///
|
||||||
|
/// For the full content type `text/html;charset=utf-8`,
|
||||||
|
/// the [subType] value is the string `html`.
|
||||||
|
/// May be the empty string.
|
||||||
|
String get subType;
|
||||||
|
|
||||||
|
/// Gets the character set, if any.
|
||||||
|
///
|
||||||
|
/// For the full content type `text/html;charset=utf-8`,
|
||||||
|
/// the [charset] value is the string `utf-8`.
|
||||||
|
String? get charset;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ContentType extends _HeaderValue implements SSHContentType {
|
||||||
|
String _primaryType = "";
|
||||||
|
String _subType = "";
|
||||||
|
|
||||||
|
_ContentType(
|
||||||
|
String primaryType,
|
||||||
|
String subType,
|
||||||
|
String? charset,
|
||||||
|
Map<String, String?> parameters,
|
||||||
|
) : _primaryType = primaryType,
|
||||||
|
_subType = subType,
|
||||||
|
super("") {
|
||||||
|
_value = "$_primaryType/$_subType";
|
||||||
|
var parameterMap = _ensureParameters();
|
||||||
|
parameters.forEach((String key, String? value) {
|
||||||
|
String lowerCaseKey = key.toLowerCase();
|
||||||
|
if (lowerCaseKey == "charset") {
|
||||||
|
value = value?.toLowerCase();
|
||||||
|
}
|
||||||
|
parameterMap[lowerCaseKey] = value;
|
||||||
|
});
|
||||||
|
if (charset != null) {
|
||||||
|
_ensureParameters()["charset"] = charset.toLowerCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_ContentType._();
|
||||||
|
|
||||||
|
static _ContentType parse(String value) {
|
||||||
|
var result = _ContentType._();
|
||||||
|
result._parse(value, ";", null, false);
|
||||||
|
int index = result._value.indexOf("/");
|
||||||
|
if (index == -1 || index == (result._value.length - 1)) {
|
||||||
|
result._primaryType = result._value.trim().toLowerCase();
|
||||||
|
} else {
|
||||||
|
result._primaryType =
|
||||||
|
result._value.substring(0, index).trim().toLowerCase();
|
||||||
|
result._subType = result._value.substring(index + 1).trim().toLowerCase();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get mimeType => '$primaryType/$subType';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get primaryType => _primaryType;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get subType => _subType;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String? get charset => parameters["charset"];
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HeaderValue {
|
||||||
|
String _value;
|
||||||
|
Map<String, String?>? _parameters;
|
||||||
|
Map<String, String?>? _unmodifiableParameters;
|
||||||
|
|
||||||
|
// ignore: unused_element
|
||||||
|
_HeaderValue([this._value = "", Map<String, String?> parameters = const {}]) {
|
||||||
|
if (parameters.isNotEmpty) {
|
||||||
|
_parameters = HashMap<String, String?>.from(parameters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ignore: unused_element
|
||||||
|
static _HeaderValue parse(
|
||||||
|
String value, {
|
||||||
|
String parameterSeparator = ";",
|
||||||
|
String? valueSeparator,
|
||||||
|
bool preserveBackslash = false,
|
||||||
|
}) {
|
||||||
|
// Parse the string.
|
||||||
|
var result = _HeaderValue();
|
||||||
|
result._parse(value, parameterSeparator, valueSeparator, preserveBackslash);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
String get value => _value;
|
||||||
|
|
||||||
|
Map<String, String?> _ensureParameters() =>
|
||||||
|
_parameters ??= <String, String?>{};
|
||||||
|
|
||||||
|
Map<String, String?> get parameters =>
|
||||||
|
_unmodifiableParameters ??= UnmodifiableMapView(_ensureParameters());
|
||||||
|
|
||||||
|
static bool _isToken(String token) {
|
||||||
|
if (token.isEmpty) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final delimiters = "\"(),/:;<=>?@[]{}";
|
||||||
|
for (int i = 0; i < token.length; i++) {
|
||||||
|
int codeUnit = token.codeUnitAt(i);
|
||||||
|
if (codeUnit <= 32 || codeUnit >= 127 || delimiters.contains(token[i])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
StringBuffer sb = StringBuffer();
|
||||||
|
sb.write(_value);
|
||||||
|
var parameters = _parameters;
|
||||||
|
if (parameters != null && parameters.isNotEmpty) {
|
||||||
|
parameters.forEach((String name, String? value) {
|
||||||
|
sb
|
||||||
|
..write("; ")
|
||||||
|
..write(name);
|
||||||
|
if (value != null) {
|
||||||
|
sb.write("=");
|
||||||
|
if (_isToken(value)) {
|
||||||
|
sb.write(value);
|
||||||
|
} else {
|
||||||
|
sb.write('"');
|
||||||
|
int start = 0;
|
||||||
|
for (int i = 0; i < value.length; i++) {
|
||||||
|
// Can use codeUnitAt here instead.
|
||||||
|
int codeUnit = value.codeUnitAt(i);
|
||||||
|
if (codeUnit == 92 /* backslash */ ||
|
||||||
|
codeUnit == 34 /* double quote */) {
|
||||||
|
sb.write(value.substring(start, i));
|
||||||
|
sb.write(r'\');
|
||||||
|
start = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb
|
||||||
|
..write(value.substring(start))
|
||||||
|
..write('"');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _parse(
|
||||||
|
String s,
|
||||||
|
String parameterSeparator,
|
||||||
|
String? valueSeparator,
|
||||||
|
bool preserveBackslash,
|
||||||
|
) {
|
||||||
|
int index = 0;
|
||||||
|
|
||||||
|
bool done() => index == s.length;
|
||||||
|
|
||||||
|
void skipWS() {
|
||||||
|
while (!done()) {
|
||||||
|
if (s[index] != " " && s[index] != "\t") return;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String parseValue() {
|
||||||
|
int start = index;
|
||||||
|
while (!done()) {
|
||||||
|
var char = s[index];
|
||||||
|
if (char == " " ||
|
||||||
|
char == "\t" ||
|
||||||
|
char == valueSeparator ||
|
||||||
|
char == parameterSeparator) break;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return s.substring(start, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
void expect(String expected) {
|
||||||
|
if (done() || s[index] != expected) {
|
||||||
|
throw SSHHttpException("Failed to parse header value");
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool maybeExpect(String expected) {
|
||||||
|
if (done() || !s.startsWith(expected, index)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void parseParameters() {
|
||||||
|
var parameters = _ensureParameters();
|
||||||
|
|
||||||
|
String parseParameterName() {
|
||||||
|
int start = index;
|
||||||
|
while (!done()) {
|
||||||
|
var char = s[index];
|
||||||
|
if (char == " " ||
|
||||||
|
char == "\t" ||
|
||||||
|
char == "=" ||
|
||||||
|
char == parameterSeparator ||
|
||||||
|
char == valueSeparator) break;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return s.substring(start, index).toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
String parseParameterValue() {
|
||||||
|
if (!done() && s[index] == "\"") {
|
||||||
|
// Parse quoted value.
|
||||||
|
StringBuffer sb = StringBuffer();
|
||||||
|
index++;
|
||||||
|
while (!done()) {
|
||||||
|
var char = s[index];
|
||||||
|
if (char == "\\") {
|
||||||
|
if (index + 1 == s.length) {
|
||||||
|
throw SSHHttpException("Failed to parse header value");
|
||||||
|
}
|
||||||
|
if (preserveBackslash && s[index + 1] != "\"") {
|
||||||
|
sb.write(char);
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
} else if (char == "\"") {
|
||||||
|
index++;
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
char = s[index];
|
||||||
|
sb.write(char);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
throw SSHHttpException("Failed to parse header value");
|
||||||
|
} else {
|
||||||
|
// Parse non-quoted value.
|
||||||
|
return parseValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (!done()) {
|
||||||
|
skipWS();
|
||||||
|
if (done()) return;
|
||||||
|
String name = parseParameterName();
|
||||||
|
skipWS();
|
||||||
|
if (maybeExpect("=")) {
|
||||||
|
skipWS();
|
||||||
|
String value = parseParameterValue();
|
||||||
|
if (name == 'charset' && this is _ContentType) {
|
||||||
|
// Charset parameter of ContentTypes are always lower-case.
|
||||||
|
value = value.toLowerCase();
|
||||||
|
}
|
||||||
|
parameters[name] = value;
|
||||||
|
skipWS();
|
||||||
|
} else if (name.isNotEmpty) {
|
||||||
|
parameters[name] = null;
|
||||||
|
}
|
||||||
|
if (done()) return;
|
||||||
|
// !TODO: Implement support for multi-valued parameters.
|
||||||
|
if (s[index] == valueSeparator) return;
|
||||||
|
expect(parameterSeparator);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
skipWS();
|
||||||
|
_value = parseValue();
|
||||||
|
skipWS();
|
||||||
|
if (done()) return;
|
||||||
|
if (s[index] == valueSeparator) return;
|
||||||
|
maybeExpect(parameterSeparator);
|
||||||
|
parseParameters();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
/// Exception thrown when an SSH HTTP request fails.
|
||||||
|
class SSHHttpException implements Exception {
|
||||||
|
final String message;
|
||||||
|
final Uri? uri;
|
||||||
|
|
||||||
|
const SSHHttpException(this.message, {this.uri});
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
var b = StringBuffer()
|
||||||
|
..write('SSHHttpException: ')
|
||||||
|
..write(message);
|
||||||
|
var uri = this.uri;
|
||||||
|
if (uri != null) {
|
||||||
|
b.write(', uri = $uri');
|
||||||
|
}
|
||||||
|
return b.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+267
@@ -0,0 +1,267 @@
|
|||||||
|
import 'package:dartssh2/src/http/http_content_type.dart';
|
||||||
|
|
||||||
|
/// Headers for HTTP requests and responses.
|
||||||
|
///
|
||||||
|
/// In some situations, headers are immutable:
|
||||||
|
///
|
||||||
|
/// * [HttpRequest] and [HttpClientResponse] always have immutable headers.
|
||||||
|
///
|
||||||
|
/// * [HttpResponse] and [HttpClientRequest] have immutable headers
|
||||||
|
/// from the moment the body is written to.
|
||||||
|
///
|
||||||
|
/// In these situations, the mutating methods throw exceptions.
|
||||||
|
///
|
||||||
|
/// For all operations on HTTP headers the header name is
|
||||||
|
/// case-insensitive.
|
||||||
|
///
|
||||||
|
/// To set the value of a header use the `set()` method:
|
||||||
|
///
|
||||||
|
/// request.headers.set(HttpHeaders.cacheControlHeader,
|
||||||
|
/// 'max-age=3600, must-revalidate');
|
||||||
|
///
|
||||||
|
/// To retrieve the value of a header use the `value()` method:
|
||||||
|
///
|
||||||
|
/// print(request.headers.value(HttpHeaders.userAgentHeader));
|
||||||
|
///
|
||||||
|
/// An `HttpHeaders` object holds a list of values for each name
|
||||||
|
/// as the standard allows. In most cases a name holds only a single value,
|
||||||
|
/// The most common mode of operation is to use `set()` for setting a value,
|
||||||
|
/// and `value()` for retrieving a value.
|
||||||
|
abstract class SSHHttpHeaders {
|
||||||
|
static const acceptHeader = "accept";
|
||||||
|
static const acceptCharsetHeader = "accept-charset";
|
||||||
|
static const acceptEncodingHeader = "accept-encoding";
|
||||||
|
static const acceptLanguageHeader = "accept-language";
|
||||||
|
static const acceptRangesHeader = "accept-ranges";
|
||||||
|
static const accessControlAllowCredentialsHeader =
|
||||||
|
'access-control-allow-credentials';
|
||||||
|
static const accessControlAllowHeadersHeader = 'access-control-allow-headers';
|
||||||
|
static const accessControlAllowMethodsHeader = 'access-control-allow-methods';
|
||||||
|
static const accessControlAllowOriginHeader = 'access-control-allow-origin';
|
||||||
|
static const accessControlExposeHeadersHeader =
|
||||||
|
'access-control-expose-headers';
|
||||||
|
static const accessControlMaxAgeHeader = 'access-control-max-age';
|
||||||
|
static const accessControlRequestHeadersHeader =
|
||||||
|
'access-control-request-headers';
|
||||||
|
static const accessControlRequestMethodHeader =
|
||||||
|
'access-control-request-method';
|
||||||
|
static const ageHeader = "age";
|
||||||
|
static const allowHeader = "allow";
|
||||||
|
static const authorizationHeader = "authorization";
|
||||||
|
static const cacheControlHeader = "cache-control";
|
||||||
|
static const connectionHeader = "connection";
|
||||||
|
static const contentEncodingHeader = "content-encoding";
|
||||||
|
static const contentLanguageHeader = "content-language";
|
||||||
|
static const contentLengthHeader = "content-length";
|
||||||
|
static const contentLocationHeader = "content-location";
|
||||||
|
static const contentMD5Header = "content-md5";
|
||||||
|
static const contentRangeHeader = "content-range";
|
||||||
|
static const contentTypeHeader = "content-type";
|
||||||
|
static const dateHeader = "date";
|
||||||
|
static const etagHeader = "etag";
|
||||||
|
static const expectHeader = "expect";
|
||||||
|
static const expiresHeader = "expires";
|
||||||
|
static const fromHeader = "from";
|
||||||
|
static const hostHeader = "host";
|
||||||
|
static const ifMatchHeader = "if-match";
|
||||||
|
static const ifModifiedSinceHeader = "if-modified-since";
|
||||||
|
static const ifNoneMatchHeader = "if-none-match";
|
||||||
|
static const ifRangeHeader = "if-range";
|
||||||
|
static const ifUnmodifiedSinceHeader = "if-unmodified-since";
|
||||||
|
static const lastModifiedHeader = "last-modified";
|
||||||
|
static const locationHeader = "location";
|
||||||
|
static const maxForwardsHeader = "max-forwards";
|
||||||
|
static const pragmaHeader = "pragma";
|
||||||
|
static const proxyAuthenticateHeader = "proxy-authenticate";
|
||||||
|
static const proxyAuthorizationHeader = "proxy-authorization";
|
||||||
|
static const rangeHeader = "range";
|
||||||
|
static const refererHeader = "referer";
|
||||||
|
static const retryAfterHeader = "retry-after";
|
||||||
|
static const serverHeader = "server";
|
||||||
|
static const teHeader = "te";
|
||||||
|
static const trailerHeader = "trailer";
|
||||||
|
static const transferEncodingHeader = "transfer-encoding";
|
||||||
|
static const upgradeHeader = "upgrade";
|
||||||
|
static const userAgentHeader = "user-agent";
|
||||||
|
static const varyHeader = "vary";
|
||||||
|
static const viaHeader = "via";
|
||||||
|
static const warningHeader = "warning";
|
||||||
|
static const wwwAuthenticateHeader = "www-authenticate";
|
||||||
|
|
||||||
|
// Cookie headers from RFC 6265.
|
||||||
|
static const cookieHeader = "cookie";
|
||||||
|
static const setCookieHeader = "set-cookie";
|
||||||
|
|
||||||
|
// !TODO(39783): Document this.
|
||||||
|
static const generalHeaders = [
|
||||||
|
cacheControlHeader,
|
||||||
|
connectionHeader,
|
||||||
|
dateHeader,
|
||||||
|
pragmaHeader,
|
||||||
|
trailerHeader,
|
||||||
|
transferEncodingHeader,
|
||||||
|
upgradeHeader,
|
||||||
|
viaHeader,
|
||||||
|
warningHeader,
|
||||||
|
];
|
||||||
|
|
||||||
|
static const entityHeaders = [
|
||||||
|
allowHeader,
|
||||||
|
contentEncodingHeader,
|
||||||
|
contentLanguageHeader,
|
||||||
|
contentLengthHeader,
|
||||||
|
contentLocationHeader,
|
||||||
|
contentMD5Header,
|
||||||
|
contentRangeHeader,
|
||||||
|
contentTypeHeader,
|
||||||
|
expiresHeader,
|
||||||
|
lastModifiedHeader,
|
||||||
|
];
|
||||||
|
|
||||||
|
static const responseHeaders = [
|
||||||
|
acceptRangesHeader,
|
||||||
|
ageHeader,
|
||||||
|
etagHeader,
|
||||||
|
locationHeader,
|
||||||
|
proxyAuthenticateHeader,
|
||||||
|
retryAfterHeader,
|
||||||
|
serverHeader,
|
||||||
|
varyHeader,
|
||||||
|
wwwAuthenticateHeader,
|
||||||
|
];
|
||||||
|
|
||||||
|
static const requestHeaders = [
|
||||||
|
acceptHeader,
|
||||||
|
acceptCharsetHeader,
|
||||||
|
acceptEncodingHeader,
|
||||||
|
acceptLanguageHeader,
|
||||||
|
authorizationHeader,
|
||||||
|
expectHeader,
|
||||||
|
fromHeader,
|
||||||
|
hostHeader,
|
||||||
|
ifMatchHeader,
|
||||||
|
ifModifiedSinceHeader,
|
||||||
|
ifNoneMatchHeader,
|
||||||
|
ifRangeHeader,
|
||||||
|
ifUnmodifiedSinceHeader,
|
||||||
|
maxForwardsHeader,
|
||||||
|
proxyAuthorizationHeader,
|
||||||
|
rangeHeader,
|
||||||
|
refererHeader,
|
||||||
|
teHeader,
|
||||||
|
userAgentHeader,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The date specified by the [dateHeader] header, if any.
|
||||||
|
DateTime? date;
|
||||||
|
|
||||||
|
/// The date and time specified by the [expiresHeader] header, if any.
|
||||||
|
DateTime? expires;
|
||||||
|
|
||||||
|
/// The date and time specified by the [ifModifiedSinceHeader] header, if any.
|
||||||
|
DateTime? ifModifiedSince;
|
||||||
|
|
||||||
|
/// The value of the [hostHeader] header, if any.
|
||||||
|
String? host;
|
||||||
|
|
||||||
|
/// The value of the port part of the [hostHeader] header, if any.
|
||||||
|
int? port;
|
||||||
|
|
||||||
|
/// The [SSHContentType] of the [contentTypeHeader] header, if any.
|
||||||
|
SSHContentType? contentType;
|
||||||
|
|
||||||
|
/// The value of the [contentLengthHeader] header, if any.
|
||||||
|
///
|
||||||
|
/// The value is negative if there is no content length set.
|
||||||
|
int contentLength = -1;
|
||||||
|
|
||||||
|
/// Whether the connection is persistent (keep-alive).
|
||||||
|
late bool persistentConnection;
|
||||||
|
|
||||||
|
/// Whether the connection uses chunked transfer encoding.
|
||||||
|
///
|
||||||
|
/// Reflects and modifies the value of the [transferEncodingHeader] header.
|
||||||
|
late bool chunkedTransferEncoding;
|
||||||
|
|
||||||
|
/// The values for the header named [name].
|
||||||
|
///
|
||||||
|
/// Returns null if there is no header with the provided name,
|
||||||
|
/// otherwise returns a new list containing the current values.
|
||||||
|
/// Not that modifying the list does not change the header.
|
||||||
|
List<String>? operator [](String name);
|
||||||
|
|
||||||
|
/// Convenience method for the value for a single valued header.
|
||||||
|
///
|
||||||
|
/// The value must not have more than one value.
|
||||||
|
///
|
||||||
|
/// Returns `null` if there is no header with the provided name.
|
||||||
|
String? value(String name);
|
||||||
|
|
||||||
|
/// Adds a header value.
|
||||||
|
///
|
||||||
|
/// The header named [name] will have a string value derived from [value]
|
||||||
|
/// added to its list of values.
|
||||||
|
///
|
||||||
|
/// Some headers are single valued, and for these, adding a value will
|
||||||
|
/// replace a previous value. If the [value] is a [DateTime], an
|
||||||
|
/// HTTP date format will be applied. If the value is an [Iterable],
|
||||||
|
/// each element will be added separately. For all other
|
||||||
|
/// types the default [Object.toString] method will be used.
|
||||||
|
///
|
||||||
|
/// Header names are converted to lower-case unless
|
||||||
|
/// [preserveHeaderCase] is set to true. If two header names are
|
||||||
|
/// the same when converted to lower-case, they are considered to be
|
||||||
|
/// the same header, with one set of values.
|
||||||
|
///
|
||||||
|
/// The current case of the a header name is that of the name used by
|
||||||
|
/// the last [set] or [add] call for that header.
|
||||||
|
void add(String name, Object value, {bool preserveHeaderCase = false});
|
||||||
|
|
||||||
|
/// Sets the header [name] to [value].
|
||||||
|
///
|
||||||
|
/// Removes all existing values for the header named [name] and
|
||||||
|
/// then [add]s [value] to it.
|
||||||
|
void set(String name, Object value, {bool preserveHeaderCase = false});
|
||||||
|
|
||||||
|
/// Removes a specific value for a header name.
|
||||||
|
///
|
||||||
|
/// Some headers have system supplied values which cannot be removed.
|
||||||
|
/// For all other headers and values, the [value] is converted to a string
|
||||||
|
/// in the same way as for [add], then that string value is removed from the
|
||||||
|
/// current values of [name].
|
||||||
|
/// If there are no remaining values for [name], the header is no longer
|
||||||
|
/// considered present.
|
||||||
|
void remove(String name, Object value);
|
||||||
|
|
||||||
|
/// Removes all values for the specified header name.
|
||||||
|
///
|
||||||
|
/// Some headers have system supplied values which cannot be removed.
|
||||||
|
/// All other values for [name] are removed.
|
||||||
|
/// If there are no remaining values for [name], the header is no longer
|
||||||
|
/// considered present.
|
||||||
|
void removeAll(String name);
|
||||||
|
|
||||||
|
/// Performs the [action] on each header.
|
||||||
|
///
|
||||||
|
/// The [action] function is called with each header's name and a list
|
||||||
|
/// of the header's values. The casing of the name string is determined by
|
||||||
|
/// the last [add] or [set] operation for that particular header,
|
||||||
|
/// which defaults to lower-casing the header name unless explicitly
|
||||||
|
/// set to preserve the case.
|
||||||
|
void forEach(void Function(String name, List<String> values) action);
|
||||||
|
|
||||||
|
/// Disables folding for the header named [name] when sending the HTTP header.
|
||||||
|
///
|
||||||
|
/// By default, multiple header values are folded into a
|
||||||
|
/// single header line by separating the values with commas.
|
||||||
|
///
|
||||||
|
/// The 'set-cookie' header has folding disabled by default.
|
||||||
|
void noFolding(String name);
|
||||||
|
|
||||||
|
/// Removes all headers.
|
||||||
|
///
|
||||||
|
/// Some headers have system supplied values which cannot be removed.
|
||||||
|
/// All other header values are removed, and header names with not
|
||||||
|
/// remaining values are no longer considered present.
|
||||||
|
void clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
// '\n' character
|
||||||
|
const int _lineTerminator = 10;
|
||||||
|
|
||||||
|
class LineDecoder {
|
||||||
|
final BytesBuilder _unprocessedBytes = BytesBuilder();
|
||||||
|
|
||||||
|
int expectedByteCount = -1;
|
||||||
|
|
||||||
|
final void Function(String, int, LineDecoder) _callback;
|
||||||
|
|
||||||
|
LineDecoder.withCallback(this._callback);
|
||||||
|
|
||||||
|
void add(List<int> chunk) {
|
||||||
|
while (chunk.isNotEmpty) {
|
||||||
|
final splitIndex = expectedByteCount > 0
|
||||||
|
? expectedByteCount - _unprocessedBytes.length
|
||||||
|
: chunk.indexOf(_lineTerminator) + 1;
|
||||||
|
|
||||||
|
if (splitIndex > 0 && splitIndex <= chunk.length) {
|
||||||
|
_unprocessedBytes.add(chunk.sublist(0, splitIndex));
|
||||||
|
chunk = chunk.sublist(splitIndex);
|
||||||
|
expectedByteCount = -1;
|
||||||
|
_process(_unprocessedBytes.takeBytes());
|
||||||
|
} else {
|
||||||
|
_unprocessedBytes.add(chunk);
|
||||||
|
chunk = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _process(List<int> line) =>
|
||||||
|
_callback(utf8.decoder.convert(line), line.length, this);
|
||||||
|
|
||||||
|
int get bufferedBytes => _unprocessedBytes.length;
|
||||||
|
|
||||||
|
void close() => _process(_unprocessedBytes.takeBytes());
|
||||||
|
}
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_kex.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bigint.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
|
||||||
|
/// The Diffie-Hellman (DH) key exchange provides a shared secret that
|
||||||
|
/// cannot be determined by either party alone.
|
||||||
|
/// https://tools.ietf.org/html/rfc4253#section-8
|
||||||
|
class SSHKexDH implements SSHKex {
|
||||||
|
static const gexMin = 1024;
|
||||||
|
static const gexPref = 2048;
|
||||||
|
static const gexMax = 8192;
|
||||||
|
|
||||||
|
/// p is a large safe prime
|
||||||
|
final BigInt p;
|
||||||
|
|
||||||
|
/// g is a generator for a subgroup of GF(p)
|
||||||
|
final BigInt g;
|
||||||
|
|
||||||
|
/// Length of the random number x
|
||||||
|
final int secretBits;
|
||||||
|
|
||||||
|
/// Random number, used as private key
|
||||||
|
late final BigInt x;
|
||||||
|
|
||||||
|
/// e = g^x mod p, used as public key
|
||||||
|
late final BigInt e;
|
||||||
|
|
||||||
|
SSHKexDH({required this.p, required this.g, required this.secretBits}) {
|
||||||
|
if (secretBits % 8 != 0) {
|
||||||
|
throw ArgumentError('secretBits must be a multiple of 8');
|
||||||
|
}
|
||||||
|
x = decodeBigIntWithSign(1, randomBytes(secretBits ~/ 8));
|
||||||
|
e = g.modPow(x, p);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// https://tools.ietf.org/html/rfc2409 Second Oakley Group
|
||||||
|
factory SSHKexDH.group1() {
|
||||||
|
return SSHKexDH(p: _group1Prime, g: BigInt.from(2), secretBits: 160);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// https://tools.ietf.org/html/rfc3526 Oakley Group 14
|
||||||
|
factory SSHKexDH.group14() {
|
||||||
|
return SSHKexDH(p: _group14Prime, g: BigInt.from(2), secretBits: 224);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute the shared secret K
|
||||||
|
BigInt computeSecret(BigInt f) {
|
||||||
|
return f.modPow(x, p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final _group1Prime = decodeBigIntWithSign(
|
||||||
|
1,
|
||||||
|
Uint8List.fromList([
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, //
|
||||||
|
0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, //
|
||||||
|
0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, //
|
||||||
|
0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, //
|
||||||
|
0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, //
|
||||||
|
0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, //
|
||||||
|
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, //
|
||||||
|
0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, //
|
||||||
|
0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, //
|
||||||
|
0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, //
|
||||||
|
0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, //
|
||||||
|
0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, //
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
final _group14Prime = decodeBigIntWithSign(
|
||||||
|
1,
|
||||||
|
Uint8List.fromList([
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, //
|
||||||
|
0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, //
|
||||||
|
0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, //
|
||||||
|
0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, //
|
||||||
|
0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, //
|
||||||
|
0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, //
|
||||||
|
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, //
|
||||||
|
0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, //
|
||||||
|
0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, //
|
||||||
|
0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, //
|
||||||
|
0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, //
|
||||||
|
0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, //
|
||||||
|
0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, //
|
||||||
|
0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, //
|
||||||
|
0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, //
|
||||||
|
0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, //
|
||||||
|
0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, //
|
||||||
|
0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, //
|
||||||
|
0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, //
|
||||||
|
0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, //
|
||||||
|
0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, //
|
||||||
|
0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, //
|
||||||
|
0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, //
|
||||||
|
0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, //
|
||||||
|
0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xac, 0xaa, 0x68, 0xff, 0xff, //
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||||
|
]),
|
||||||
|
);
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_kex.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bigint.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
import 'package:pointycastle/ecc/curves/secp256r1.dart';
|
||||||
|
import 'package:pointycastle/ecc/curves/secp384r1.dart';
|
||||||
|
import 'package:pointycastle/ecc/curves/secp521r1.dart';
|
||||||
|
import 'package:pointycastle/pointycastle.dart';
|
||||||
|
|
||||||
|
/// The Elliptic Curve Diffie-Hellman (ECDH) key exchange method generates a
|
||||||
|
/// shared secret from an ephemeral local elliptic curve private key and
|
||||||
|
/// ephemeral remote elliptic curve public key.
|
||||||
|
class SSHKexNist implements SSHKexECDH {
|
||||||
|
/// The elliptic curve domain parameters.
|
||||||
|
final ECDomainParameters curve;
|
||||||
|
|
||||||
|
/// The length of the shared secret in bytes.
|
||||||
|
final int secretBits;
|
||||||
|
|
||||||
|
/// Secret random number.
|
||||||
|
late final BigInt privateKey;
|
||||||
|
|
||||||
|
/// Public key.
|
||||||
|
@override
|
||||||
|
late final Uint8List publicKey;
|
||||||
|
|
||||||
|
SSHKexNist({required this.curve, required this.secretBits}) {
|
||||||
|
privateKey = _generatePrivateKey();
|
||||||
|
final c = curve.G * privateKey;
|
||||||
|
publicKey = c!.getEncoded(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
SSHKexNist.p256() : this(curve: ECCurve_secp256r1(), secretBits: 256);
|
||||||
|
|
||||||
|
SSHKexNist.p384() : this(curve: ECCurve_secp384r1(), secretBits: 384);
|
||||||
|
|
||||||
|
SSHKexNist.p521() : this(curve: ECCurve_secp521r1(), secretBits: 521);
|
||||||
|
|
||||||
|
/// Compute shared secret.
|
||||||
|
@override
|
||||||
|
BigInt computeSecret(Uint8List remotePubilcKey) {
|
||||||
|
final s = curve.curve.decodePoint(remotePubilcKey)!;
|
||||||
|
return (s * privateKey)!.x!.toBigInteger()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInt _generatePrivateKey() {
|
||||||
|
late BigInt x;
|
||||||
|
do {
|
||||||
|
x = decodeBigIntWithSign(1, randomBytes(secretBits ~/ 8)) % curve.n;
|
||||||
|
} while (x == BigInt.zero);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_kex.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bigint.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
import 'package:pinenacl/tweetnacl.dart';
|
||||||
|
|
||||||
|
class SSHKexX25519 implements SSHKexECDH {
|
||||||
|
/// Randomly generated private key.
|
||||||
|
late final Uint8List privateKey;
|
||||||
|
|
||||||
|
/// Public key computed from the private key.
|
||||||
|
@override
|
||||||
|
late final Uint8List publicKey;
|
||||||
|
|
||||||
|
SSHKexX25519() {
|
||||||
|
privateKey = randomBytes(32);
|
||||||
|
publicKey = _ScalarMult.scalseMultBase(privateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
BigInt computeSecret(Uint8List remotePublicKey) {
|
||||||
|
final secret = _ScalarMult.scalseMult(privateKey, remotePublicKey);
|
||||||
|
return decodeBigIntWithSign(1, secret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scalar multiplication, Implements curve25519.
|
||||||
|
class _ScalarMult {
|
||||||
|
/// Length of scalar in bytes.
|
||||||
|
static final int _scalarLength = 32;
|
||||||
|
|
||||||
|
/// Length of group element in bytes.
|
||||||
|
static final int groupElementLength = 32;
|
||||||
|
|
||||||
|
/// Multiplies an integer n by a group element p and returns the resulting
|
||||||
|
/// group element.
|
||||||
|
static Uint8List scalseMult(Uint8List n, Uint8List p) {
|
||||||
|
if (n.length != _scalarLength) {
|
||||||
|
throw ArgumentError('n must be 32 bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p.length != groupElementLength) {
|
||||||
|
throw ArgumentError('p must be 32 bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
final q = Uint8List(_scalarLength);
|
||||||
|
|
||||||
|
TweetNaCl.crypto_scalarmult(q, n, p);
|
||||||
|
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multiplies an integer n by a standard group element and returns the
|
||||||
|
/// resulting group element.
|
||||||
|
static Uint8List scalseMultBase(Uint8List n) {
|
||||||
|
if (n.length != _scalarLength) {
|
||||||
|
throw ArgumentError('n must be 32 bytes long');
|
||||||
|
}
|
||||||
|
|
||||||
|
final q = Uint8List(_scalarLength);
|
||||||
|
|
||||||
|
TweetNaCl.crypto_scalarmult_base(q, n);
|
||||||
|
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1049
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Debug implements SSHMessage {
|
||||||
|
static const messageId = 4;
|
||||||
|
|
||||||
|
final bool alwaysDisplay;
|
||||||
|
|
||||||
|
final Uint8List message;
|
||||||
|
|
||||||
|
final Uint8List language;
|
||||||
|
|
||||||
|
SSH_Message_Debug({
|
||||||
|
required this.alwaysDisplay,
|
||||||
|
required this.message,
|
||||||
|
required this.language,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Debug.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final alwaysDisplay = reader.readBool();
|
||||||
|
final message = reader.readString();
|
||||||
|
final language = reader.readString();
|
||||||
|
return SSH_Message_Debug(
|
||||||
|
alwaysDisplay: alwaysDisplay,
|
||||||
|
message: message,
|
||||||
|
language: language,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeBool(alwaysDisplay);
|
||||||
|
writer.writeString(message);
|
||||||
|
writer.writeString(language);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Debug(alwaysDisplay: $alwaysDisplay, message: $message, language: $language)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Disconnect extends SSHMessage {
|
||||||
|
static const messageId = 1;
|
||||||
|
|
||||||
|
final int reasonCode;
|
||||||
|
final String description;
|
||||||
|
final String languageTag;
|
||||||
|
|
||||||
|
SSH_Message_Disconnect({
|
||||||
|
required this.reasonCode,
|
||||||
|
required this.description,
|
||||||
|
this.languageTag = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
SSH_Message_Disconnect.fromReason(SSHDisconnectReason reason)
|
||||||
|
: reasonCode = reason.code,
|
||||||
|
description = reason.description,
|
||||||
|
languageTag = '';
|
||||||
|
|
||||||
|
factory SSH_Message_Disconnect.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final reasonCode = reader.readUint32();
|
||||||
|
final description = reader.readUtf8();
|
||||||
|
final language = reader.readUtf8();
|
||||||
|
return SSH_Message_Disconnect(
|
||||||
|
reasonCode: reasonCode,
|
||||||
|
description: description,
|
||||||
|
languageTag: language,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUint32(reasonCode);
|
||||||
|
writer.writeUtf8(description);
|
||||||
|
writer.writeUtf8(languageTag);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Disconnect(reasonCode: $reasonCode, description: $description, language: $languageTag)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SSHDisconnectReason {
|
||||||
|
hostNotAllowedToConnect,
|
||||||
|
protocolError,
|
||||||
|
keyExchangeFailed,
|
||||||
|
reserved,
|
||||||
|
macError,
|
||||||
|
compressionError,
|
||||||
|
serviceNotAvailable,
|
||||||
|
protocolVersionNotSupported,
|
||||||
|
hostKeyNotVerifiable,
|
||||||
|
connectionLost,
|
||||||
|
byApplication,
|
||||||
|
tooManyConnections,
|
||||||
|
authCancelledByUser,
|
||||||
|
noMoreAuthMethodsAvailable,
|
||||||
|
illegalUserName,
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHDisconnectReasonX on SSHDisconnectReason {
|
||||||
|
String get description {
|
||||||
|
switch (this) {
|
||||||
|
case SSHDisconnectReason.hostNotAllowedToConnect:
|
||||||
|
return 'Host not allowed to connect';
|
||||||
|
case SSHDisconnectReason.protocolError:
|
||||||
|
return 'Protocol error';
|
||||||
|
case SSHDisconnectReason.keyExchangeFailed:
|
||||||
|
return 'Key exchange failed';
|
||||||
|
case SSHDisconnectReason.reserved:
|
||||||
|
return 'Reserved';
|
||||||
|
case SSHDisconnectReason.macError:
|
||||||
|
return 'MAC error';
|
||||||
|
case SSHDisconnectReason.compressionError:
|
||||||
|
return 'Compression error';
|
||||||
|
case SSHDisconnectReason.serviceNotAvailable:
|
||||||
|
return 'Service not available';
|
||||||
|
case SSHDisconnectReason.protocolVersionNotSupported:
|
||||||
|
return 'Protocol version not supported';
|
||||||
|
case SSHDisconnectReason.hostKeyNotVerifiable:
|
||||||
|
return 'Host key not verifiable';
|
||||||
|
case SSHDisconnectReason.connectionLost:
|
||||||
|
return 'Connection lost';
|
||||||
|
case SSHDisconnectReason.byApplication:
|
||||||
|
return 'By application';
|
||||||
|
case SSHDisconnectReason.tooManyConnections:
|
||||||
|
return 'Too many connections';
|
||||||
|
case SSHDisconnectReason.authCancelledByUser:
|
||||||
|
return 'Auth cancelled by user';
|
||||||
|
case SSHDisconnectReason.noMoreAuthMethodsAvailable:
|
||||||
|
return 'No more auth methods available';
|
||||||
|
case SSHDisconnectReason.illegalUserName:
|
||||||
|
return 'Illegal user name';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int get code {
|
||||||
|
switch (this) {
|
||||||
|
case SSHDisconnectReason.hostNotAllowedToConnect:
|
||||||
|
return 1;
|
||||||
|
case SSHDisconnectReason.protocolError:
|
||||||
|
return 2;
|
||||||
|
case SSHDisconnectReason.keyExchangeFailed:
|
||||||
|
return 3;
|
||||||
|
case SSHDisconnectReason.reserved:
|
||||||
|
return 4;
|
||||||
|
case SSHDisconnectReason.macError:
|
||||||
|
return 5;
|
||||||
|
case SSHDisconnectReason.compressionError:
|
||||||
|
return 6;
|
||||||
|
case SSHDisconnectReason.serviceNotAvailable:
|
||||||
|
return 7;
|
||||||
|
case SSHDisconnectReason.protocolVersionNotSupported:
|
||||||
|
return 8;
|
||||||
|
case SSHDisconnectReason.hostKeyNotVerifiable:
|
||||||
|
return 9;
|
||||||
|
case SSHDisconnectReason.connectionLost:
|
||||||
|
return 10;
|
||||||
|
case SSHDisconnectReason.byApplication:
|
||||||
|
return 11;
|
||||||
|
case SSHDisconnectReason.tooManyConnections:
|
||||||
|
return 12;
|
||||||
|
case SSHDisconnectReason.authCancelledByUser:
|
||||||
|
return 13;
|
||||||
|
case SSHDisconnectReason.noMoreAuthMethodsAvailable:
|
||||||
|
return 14;
|
||||||
|
case SSHDisconnectReason.illegalUserName:
|
||||||
|
return 15;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Ignore extends SSHMessage {
|
||||||
|
static const messageId = 2;
|
||||||
|
|
||||||
|
final Uint8List data;
|
||||||
|
|
||||||
|
SSH_Message_Ignore(this.data);
|
||||||
|
|
||||||
|
SSH_Message_Ignore.empty() : data = Uint8List(0);
|
||||||
|
|
||||||
|
factory SSH_Message_Ignore.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final data = reader.readString();
|
||||||
|
return SSH_Message_Ignore(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeString(data);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Ignore(data: $data)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
|
||||||
|
class SSH_Message_KexInit implements SSHMessage {
|
||||||
|
static const messageId = 20;
|
||||||
|
|
||||||
|
final List<String> kexAlgorithms;
|
||||||
|
final List<String> serverHostKeyAlgorithms;
|
||||||
|
final List<String> encryptionClientToServer;
|
||||||
|
final List<String> encryptionServerToClient;
|
||||||
|
final List<String> macClientToServer;
|
||||||
|
final List<String> macServerToClient;
|
||||||
|
final List<String> compressionClientToServer;
|
||||||
|
final List<String> compressionServerToClient;
|
||||||
|
final List<String> languagesClientToServer;
|
||||||
|
final List<String> languagesServerToClient;
|
||||||
|
final bool firstKexPacketFollows;
|
||||||
|
|
||||||
|
SSH_Message_KexInit({
|
||||||
|
required this.kexAlgorithms,
|
||||||
|
required this.serverHostKeyAlgorithms,
|
||||||
|
required this.encryptionClientToServer,
|
||||||
|
required this.encryptionServerToClient,
|
||||||
|
required this.macClientToServer,
|
||||||
|
required this.macServerToClient,
|
||||||
|
required this.compressionClientToServer,
|
||||||
|
required this.compressionServerToClient,
|
||||||
|
this.languagesClientToServer = const [],
|
||||||
|
this.languagesServerToClient = const [],
|
||||||
|
required this.firstKexPacketFollows,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexInit.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message id
|
||||||
|
reader.skip(16); // skip cookie
|
||||||
|
final kexAlgorithms = reader.readNameList();
|
||||||
|
final serverHostKeyAlgorithms = reader.readNameList();
|
||||||
|
final encryptionClientToServer = reader.readNameList();
|
||||||
|
final encryptionServerToClient = reader.readNameList();
|
||||||
|
final macClientToServer = reader.readNameList();
|
||||||
|
final macServerToClient = reader.readNameList();
|
||||||
|
final compressionClientToServer = reader.readNameList();
|
||||||
|
final compressionServerToClient = reader.readNameList();
|
||||||
|
final languagesClientToServer = reader.readNameList();
|
||||||
|
final languagesServerToClient = reader.readNameList();
|
||||||
|
final firstKexPacketFollows = reader.readBool();
|
||||||
|
|
||||||
|
return SSH_Message_KexInit(
|
||||||
|
firstKexPacketFollows: firstKexPacketFollows,
|
||||||
|
kexAlgorithms: kexAlgorithms,
|
||||||
|
serverHostKeyAlgorithms: serverHostKeyAlgorithms,
|
||||||
|
encryptionClientToServer: encryptionClientToServer,
|
||||||
|
encryptionServerToClient: encryptionServerToClient,
|
||||||
|
macClientToServer: macClientToServer,
|
||||||
|
macServerToClient: macServerToClient,
|
||||||
|
compressionClientToServer: compressionClientToServer,
|
||||||
|
compressionServerToClient: compressionServerToClient,
|
||||||
|
languagesClientToServer: languagesClientToServer,
|
||||||
|
languagesServerToClient: languagesServerToClient,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeBytes(randomBytes(16));
|
||||||
|
writer.writeNameList(kexAlgorithms);
|
||||||
|
writer.writeNameList(serverHostKeyAlgorithms);
|
||||||
|
writer.writeNameList(encryptionClientToServer);
|
||||||
|
writer.writeNameList(encryptionServerToClient);
|
||||||
|
writer.writeNameList(macClientToServer);
|
||||||
|
writer.writeNameList(macServerToClient);
|
||||||
|
writer.writeNameList(compressionClientToServer);
|
||||||
|
writer.writeNameList(compressionServerToClient);
|
||||||
|
writer.writeNameList(languagesClientToServer);
|
||||||
|
writer.writeNameList(languagesServerToClient);
|
||||||
|
writer.writeBool(firstKexPacketFollows);
|
||||||
|
writer.writeUint32(0); // reserved
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexInit(kexAlgorithms: $kexAlgorithms, serverHostKeyAlgorithms: $serverHostKeyAlgorithms, encryptionClientToServer: $encryptionClientToServer, encryptionServerToClient: $encryptionServerToClient, macClientToServer: $macClientToServer, macServerToClient: $macServerToClient, compressionClientToServer: $compressionClientToServer, compressionServerToClient: $compressionServerToClient, languagesClientToServer: $languagesClientToServer, languagesServerToClient: $languagesServerToClient, firstKexPacketFollows: $firstKexPacketFollows)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_NewKeys implements SSHMessage {
|
||||||
|
static const int messageId = 21;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_NewKeys()';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_Init implements SSHMessage {
|
||||||
|
static const messageId = 30;
|
||||||
|
|
||||||
|
/// Client generates a random number x (1 < x < q) and computes e = g^x mod p
|
||||||
|
final BigInt e;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_Init({required this.e});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_Init.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final e = reader.readMpint();
|
||||||
|
return SSH_Message_KexDH_Init(e: e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeMpint(e);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexDH_Init(e: $e)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_Reply implements SSHMessage {
|
||||||
|
static const messageId = 31;
|
||||||
|
|
||||||
|
/// server public host key and certificates (K_S)
|
||||||
|
final Uint8List hostPublicKey;
|
||||||
|
|
||||||
|
/// Server generates a random number y (0 < y < q) and computes f = g^y mod p.
|
||||||
|
final BigInt f;
|
||||||
|
|
||||||
|
/// The signature on the exchange hash H
|
||||||
|
final Uint8List signature;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_Reply({
|
||||||
|
required this.hostPublicKey,
|
||||||
|
required this.f,
|
||||||
|
required this.signature,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_Reply.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final publicKey = reader.readString();
|
||||||
|
final f = reader.readMpint();
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSH_Message_KexDH_Reply(
|
||||||
|
hostPublicKey: publicKey,
|
||||||
|
f: f,
|
||||||
|
signature: signature,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeString(hostPublicKey);
|
||||||
|
writer.writeMpint(f);
|
||||||
|
writer.writeString(signature);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexDH_Reply(hostPublicKey: $hostPublicKey, f: $f, signature: $signature)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_GexRequest implements SSHMessage {
|
||||||
|
static const messageId = 34;
|
||||||
|
|
||||||
|
final int minN;
|
||||||
|
final int preferredN;
|
||||||
|
final int maxN;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_GexRequest({
|
||||||
|
required this.minN,
|
||||||
|
required this.preferredN,
|
||||||
|
required this.maxN,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_GexRequest.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final minN = reader.readUint32();
|
||||||
|
final preferredN = reader.readUint32();
|
||||||
|
final maxN = reader.readUint32();
|
||||||
|
return SSH_Message_KexDH_GexRequest(
|
||||||
|
minN: minN,
|
||||||
|
preferredN: preferredN,
|
||||||
|
maxN: maxN,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUint32(minN);
|
||||||
|
writer.writeUint32(preferredN);
|
||||||
|
writer.writeUint32(maxN);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexDH_GexRequest(minN: $minN, preferredN: $preferredN, maxN: $maxN)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_GexGroup extends SSHMessage {
|
||||||
|
static const messageId = 31;
|
||||||
|
|
||||||
|
final BigInt p;
|
||||||
|
final BigInt g;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_GexGroup({
|
||||||
|
required this.p,
|
||||||
|
required this.g,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_GexGroup.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final p = reader.readMpint();
|
||||||
|
final g = reader.readMpint();
|
||||||
|
return SSH_Message_KexDH_GexGroup(p: p, g: g);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeMpint(p);
|
||||||
|
writer.writeMpint(g);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(p: $p, g: $g)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_GexInit implements SSHMessage {
|
||||||
|
static const messageId = 32;
|
||||||
|
|
||||||
|
/// Client generates a random number x (1 < x < q) and computes e = g^x mod p
|
||||||
|
final BigInt e;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_GexInit({required this.e});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_GexInit.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final e = reader.readMpint();
|
||||||
|
return SSH_Message_KexDH_GexInit(e: e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeMpint(e);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexDH_Init(e: $e)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexDH_GexReply implements SSH_Message_KexDH_Reply {
|
||||||
|
static const messageId = 33;
|
||||||
|
|
||||||
|
/// server public host key and certificates (K_S)
|
||||||
|
@override
|
||||||
|
final Uint8List hostPublicKey;
|
||||||
|
|
||||||
|
/// Server generates a random number y (0 < y < q) and computes f = g^y mod p.
|
||||||
|
@override
|
||||||
|
final BigInt f;
|
||||||
|
|
||||||
|
/// The signature on the exchange hash H
|
||||||
|
@override
|
||||||
|
final Uint8List signature;
|
||||||
|
|
||||||
|
SSH_Message_KexDH_GexReply({
|
||||||
|
required this.hostPublicKey,
|
||||||
|
required this.f,
|
||||||
|
required this.signature,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexDH_GexReply.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final publicKey = reader.readString();
|
||||||
|
final f = reader.readMpint();
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSH_Message_KexDH_GexReply(
|
||||||
|
hostPublicKey: publicKey,
|
||||||
|
f: f,
|
||||||
|
signature: signature,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeString(hostPublicKey);
|
||||||
|
writer.writeMpint(f);
|
||||||
|
writer.writeString(signature);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(hostPublicKey: $hostPublicKey, f: $f, signature: $signature)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_KexECDH_Init implements SSHMessage {
|
||||||
|
static const messageId = 30;
|
||||||
|
|
||||||
|
/// Client generates a random number x (1 < x < q) and computes e = g^x mod p
|
||||||
|
final Uint8List ecdhPublicKey;
|
||||||
|
|
||||||
|
SSH_Message_KexECDH_Init(this.ecdhPublicKey);
|
||||||
|
|
||||||
|
factory SSH_Message_KexECDH_Init.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final publicKey = reader.readString();
|
||||||
|
return SSH_Message_KexECDH_Init(publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeString(ecdhPublicKey);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexECDH_Init(publicKey: ${hex.encode(ecdhPublicKey)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_KexECDH_Reply implements SSHMessage {
|
||||||
|
static const messageId = 31;
|
||||||
|
|
||||||
|
/// Server public host key and certificates (K_S)
|
||||||
|
final Uint8List hostPublicKey;
|
||||||
|
|
||||||
|
/// Server's ephemeral public key octet string (Q_S)
|
||||||
|
final Uint8List ecdhPublicKey;
|
||||||
|
|
||||||
|
/// The signature on the exchange hash H
|
||||||
|
final Uint8List signature;
|
||||||
|
|
||||||
|
SSH_Message_KexECDH_Reply({
|
||||||
|
required this.hostPublicKey,
|
||||||
|
required this.ecdhPublicKey,
|
||||||
|
required this.signature,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_KexECDH_Reply.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1); // skip message number
|
||||||
|
final hostPublicKey = reader.readString();
|
||||||
|
final ecdhPublicKey = reader.readString();
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSH_Message_KexECDH_Reply(
|
||||||
|
ecdhPublicKey: ecdhPublicKey,
|
||||||
|
hostPublicKey: hostPublicKey,
|
||||||
|
signature: signature,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeString(ecdhPublicKey);
|
||||||
|
writer.writeString(hostPublicKey);
|
||||||
|
writer.writeString(signature);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_KexECDH_Reply(hostPublicKey: ${hex.encode(hostPublicKey)}, ecdhPublicKey: ${hex.encode(ecdhPublicKey)}, signature: ${hex.encode(signature)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Global_Request extends SSHMessage {
|
||||||
|
static const messageId = 80;
|
||||||
|
|
||||||
|
final String requestName;
|
||||||
|
final bool wantReply;
|
||||||
|
|
||||||
|
/// "tcpip-forward" and "cancel-tcpip-forward" request specific data
|
||||||
|
final String? bindAddress;
|
||||||
|
final int? bindPort;
|
||||||
|
|
||||||
|
// // "hostkeys-00@openssh.com" request specific data.
|
||||||
|
// final List<SSHHostKey>? hostKeys;
|
||||||
|
|
||||||
|
SSH_Message_Global_Request({
|
||||||
|
required this.requestName,
|
||||||
|
required this.wantReply,
|
||||||
|
this.bindAddress,
|
||||||
|
this.bindPort,
|
||||||
|
// this.hostKeys,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Request connections to the other side be forwarded to the local side
|
||||||
|
factory SSH_Message_Global_Request.tcpipForward(
|
||||||
|
String bindAddress,
|
||||||
|
int bindPort,
|
||||||
|
) {
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: 'tcpip-forward',
|
||||||
|
wantReply: true,
|
||||||
|
bindAddress: bindAddress,
|
||||||
|
bindPort: bindPort,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request cancellation of a port forwarding
|
||||||
|
factory SSH_Message_Global_Request.cancelTcpipForward({
|
||||||
|
required String bindAddress,
|
||||||
|
required int bindPort,
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: 'cancel-tcpip-forward',
|
||||||
|
wantReply: true,
|
||||||
|
bindAddress: bindAddress,
|
||||||
|
bindPort: bindPort,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// /// Send additional host keys after authenticated.
|
||||||
|
// factory SSH_Message_Global_Request.hostKeys({
|
||||||
|
// required List<SSHHostKey> hostKeys,
|
||||||
|
// }) {
|
||||||
|
// return SSH_Message_Global_Request(
|
||||||
|
// requestName: 'hostkeys-00@openssh.com',
|
||||||
|
// wantReply: false,
|
||||||
|
// hostKeys: hostKeys,
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
|
||||||
|
factory SSH_Message_Global_Request.keepAlive() {
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: 'keepalive@openssh.com',
|
||||||
|
wantReply: true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Global_Request.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final requestName = reader.readUtf8();
|
||||||
|
final wantReply = reader.readBool();
|
||||||
|
switch (requestName) {
|
||||||
|
case 'tcpip-forward':
|
||||||
|
final bindAddress = reader.readUtf8();
|
||||||
|
final bindPort = reader.readUint32();
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: requestName,
|
||||||
|
wantReply: wantReply,
|
||||||
|
bindAddress: bindAddress,
|
||||||
|
bindPort: bindPort,
|
||||||
|
);
|
||||||
|
case 'cancel-tcpip-forward':
|
||||||
|
final bindAddress = reader.readUtf8();
|
||||||
|
final bindPort = reader.readUint32();
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: requestName,
|
||||||
|
wantReply: wantReply,
|
||||||
|
bindAddress: bindAddress,
|
||||||
|
bindPort: bindPort,
|
||||||
|
);
|
||||||
|
// case 'hostkeys-00@openssh.com':
|
||||||
|
// final hostKeys = reader.readStringList();
|
||||||
|
// return SSH_Message_Global_Request(
|
||||||
|
// requestName: requestName,
|
||||||
|
// wantReply: wantReply,
|
||||||
|
// hostKeys: _parseHostKeys(hostKeys),
|
||||||
|
// );
|
||||||
|
default:
|
||||||
|
return SSH_Message_Global_Request(
|
||||||
|
requestName: requestName,
|
||||||
|
wantReply: wantReply,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(requestName);
|
||||||
|
writer.writeBool(wantReply);
|
||||||
|
switch (requestName) {
|
||||||
|
case 'tcpip-forward':
|
||||||
|
writer.writeUtf8(bindAddress!);
|
||||||
|
writer.writeUint32(bindPort!);
|
||||||
|
break;
|
||||||
|
case 'cancel-tcpip-forward':
|
||||||
|
writer.writeUtf8(bindAddress!);
|
||||||
|
writer.writeUint32(bindPort!);
|
||||||
|
break;
|
||||||
|
// case 'hostkeys-00@openssh.com':
|
||||||
|
// for (var hostkey in _encodeHostKeys(hostKeys!)) {
|
||||||
|
// writer.writeString(hostkey);
|
||||||
|
// }
|
||||||
|
// break;
|
||||||
|
}
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static List<SSHHostKey> _parseHostKeys(List<Uint8List> pairs) {
|
||||||
|
// final result = <SSHHostKey>[];
|
||||||
|
// for (final pair in pairs) {
|
||||||
|
// final reader = SSHMessageReader(pair);
|
||||||
|
// final type = reader.readUtf8();
|
||||||
|
// final key = reader.readString();
|
||||||
|
// result.add(SSHHostKey(type, key));
|
||||||
|
// }
|
||||||
|
// return result;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// static List<Uint8List> _encodeHostKeys(List<SSHHostKey> hostKeys) {
|
||||||
|
// final result = <Uint8List>[];
|
||||||
|
// for (final hostKey in hostKeys) {
|
||||||
|
// final writer = SSHMessageWriter();
|
||||||
|
// writer.writeUtf8(hostKey.type);
|
||||||
|
// writer.writeString(hostKey.key);
|
||||||
|
// result.add(writer.takeBytes());
|
||||||
|
// }
|
||||||
|
// return result;
|
||||||
|
// }
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
switch (requestName) {
|
||||||
|
case 'tcpip-forward':
|
||||||
|
return 'SSH_Message_Global_Request(requestName: $requestName, wantReply: $wantReply, bindAddress: $bindAddress, bindPort: $bindPort)';
|
||||||
|
case 'cancel-tcpip-forward':
|
||||||
|
return 'SSH_Message_Global_Request(requestName: $requestName, wantReply: $wantReply, bindAddress: $bindAddress, bindPort: $bindPort)';
|
||||||
|
// case 'hostkeys-00@openssh.com':
|
||||||
|
// return 'SSH_Message_Global_Request(requestName: $requestName, wantReply: $wantReply, hostKeys: $hostKeys)';
|
||||||
|
default:
|
||||||
|
return 'SSH_Message_Global_Request(requestName: $requestName, wantReply: $wantReply)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Request_Success extends SSHMessage {
|
||||||
|
static const messageId = 81;
|
||||||
|
|
||||||
|
final Uint8List requestData;
|
||||||
|
|
||||||
|
SSH_Message_Request_Success(this.requestData);
|
||||||
|
|
||||||
|
factory SSH_Message_Request_Success.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final requestData = reader.readToEnd();
|
||||||
|
return SSH_Message_Request_Success(requestData);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeBytes(requestData);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Request_Success(requestData: ${hex.encode(requestData)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Indicates that the recipient does not recognize or support the request.
|
||||||
|
class SSH_Message_Request_Failure extends SSHMessage {
|
||||||
|
static const messageId = 82;
|
||||||
|
|
||||||
|
SSH_Message_Request_Failure();
|
||||||
|
|
||||||
|
factory SSH_Message_Request_Failure.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
return SSH_Message_Request_Failure();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Request_Failure()';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Service_Request implements SSHMessage {
|
||||||
|
static const messageId = 5;
|
||||||
|
|
||||||
|
final String serviceName;
|
||||||
|
|
||||||
|
SSH_Message_Service_Request(this.serviceName);
|
||||||
|
|
||||||
|
factory SSH_Message_Service_Request.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final serviceName = reader.readUtf8();
|
||||||
|
return SSH_Message_Service_Request(serviceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(serviceName);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Service_Request{serviceName: $serviceName}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Service_Accept implements SSHMessage {
|
||||||
|
static const messageId = 6;
|
||||||
|
|
||||||
|
final String serviceName;
|
||||||
|
|
||||||
|
SSH_Message_Service_Accept(this.serviceName);
|
||||||
|
|
||||||
|
factory SSH_Message_Service_Accept.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final serviceName = reader.readUtf8();
|
||||||
|
return SSH_Message_Service_Accept(serviceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(serviceName);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Service_Accept{serviceName: $serviceName}';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
// ignore_for_file: camel_case_types
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_userauth.dart';
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_Request extends SSHMessage {
|
||||||
|
static const messageId = 50;
|
||||||
|
|
||||||
|
final String user;
|
||||||
|
final String serviceName;
|
||||||
|
final String methodName;
|
||||||
|
|
||||||
|
/* 'password' method specific fields */
|
||||||
|
|
||||||
|
final String? oldPassword;
|
||||||
|
final String? password;
|
||||||
|
|
||||||
|
/* 'publickey' method specific fields */
|
||||||
|
|
||||||
|
final String? publicKeyAlgorithm;
|
||||||
|
final Uint8List? publicKey;
|
||||||
|
final Uint8List? signature;
|
||||||
|
|
||||||
|
/* 'publickey' method specific fields */
|
||||||
|
|
||||||
|
final String? languageTag;
|
||||||
|
final String? submethods;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_Request({
|
||||||
|
required this.user,
|
||||||
|
required this.serviceName,
|
||||||
|
required this.methodName,
|
||||||
|
this.oldPassword,
|
||||||
|
this.password,
|
||||||
|
this.publicKeyAlgorithm,
|
||||||
|
this.publicKey,
|
||||||
|
this.signature,
|
||||||
|
this.languageTag,
|
||||||
|
this.submethods,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.password({
|
||||||
|
required String user,
|
||||||
|
required String password,
|
||||||
|
String serviceName = 'ssh-connection',
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Userauth_Request(
|
||||||
|
serviceName: serviceName,
|
||||||
|
user: user,
|
||||||
|
password: password,
|
||||||
|
methodName: 'password',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.newPassword({
|
||||||
|
required String user,
|
||||||
|
required String oldPassword,
|
||||||
|
required String newPassword,
|
||||||
|
String serviceName = 'ssh-connection',
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Userauth_Request(
|
||||||
|
serviceName: serviceName,
|
||||||
|
user: user,
|
||||||
|
oldPassword: oldPassword,
|
||||||
|
password: newPassword,
|
||||||
|
methodName: 'password',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.publicKey({
|
||||||
|
required String username,
|
||||||
|
required String publicKeyAlgorithm,
|
||||||
|
required Uint8List publicKey,
|
||||||
|
required Uint8List? signature,
|
||||||
|
String serviceName = 'ssh-connection',
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Userauth_Request(
|
||||||
|
serviceName: serviceName,
|
||||||
|
user: username,
|
||||||
|
publicKeyAlgorithm: publicKeyAlgorithm,
|
||||||
|
publicKey: publicKey,
|
||||||
|
signature: signature,
|
||||||
|
methodName: 'publickey',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.keyboardInteractive({
|
||||||
|
required String user,
|
||||||
|
String languageTag = '',
|
||||||
|
String submethods = '',
|
||||||
|
String serviceName = 'ssh-connection',
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Userauth_Request(
|
||||||
|
serviceName: serviceName,
|
||||||
|
user: user,
|
||||||
|
languageTag: languageTag,
|
||||||
|
submethods: submethods,
|
||||||
|
methodName: 'keyboard-interactive',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.none({
|
||||||
|
required String user,
|
||||||
|
String serviceName = 'ssh-connection',
|
||||||
|
}) {
|
||||||
|
return SSH_Message_Userauth_Request(
|
||||||
|
serviceName: serviceName,
|
||||||
|
user: user,
|
||||||
|
methodName: 'none',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Request.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final user = reader.readUtf8();
|
||||||
|
final serviceName = reader.readUtf8();
|
||||||
|
final methodName = reader.readUtf8();
|
||||||
|
switch (methodName) {
|
||||||
|
case 'password':
|
||||||
|
final hasNewPassword = reader.readBool();
|
||||||
|
final password = reader.readUtf8();
|
||||||
|
if (hasNewPassword) {
|
||||||
|
final oldPassword = reader.readUtf8();
|
||||||
|
return SSH_Message_Userauth_Request.newPassword(
|
||||||
|
user: user,
|
||||||
|
oldPassword: oldPassword,
|
||||||
|
newPassword: password,
|
||||||
|
serviceName: serviceName,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return SSH_Message_Userauth_Request.password(
|
||||||
|
user: user,
|
||||||
|
password: password,
|
||||||
|
serviceName: serviceName,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'publickey':
|
||||||
|
final publicKeyAlgorithm = reader.readUtf8();
|
||||||
|
final publicKey = reader.readString();
|
||||||
|
final signature = reader.readString();
|
||||||
|
return SSH_Message_Userauth_Request.publicKey(
|
||||||
|
username: user,
|
||||||
|
serviceName: serviceName,
|
||||||
|
publicKeyAlgorithm: publicKeyAlgorithm,
|
||||||
|
publicKey: publicKey,
|
||||||
|
signature: signature,
|
||||||
|
);
|
||||||
|
case 'keyboard-interactive':
|
||||||
|
final languageTag = reader.readUtf8();
|
||||||
|
final submethods = reader.readUtf8();
|
||||||
|
return SSH_Message_Userauth_Request.keyboardInteractive(
|
||||||
|
user: user,
|
||||||
|
serviceName: serviceName,
|
||||||
|
languageTag: languageTag,
|
||||||
|
submethods: submethods,
|
||||||
|
);
|
||||||
|
case 'none':
|
||||||
|
return SSH_Message_Userauth_Request.none(
|
||||||
|
user: user,
|
||||||
|
serviceName: serviceName,
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
throw UnimplementedError('Unrecognized method name: $methodName');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(user);
|
||||||
|
writer.writeUtf8(serviceName);
|
||||||
|
writer.writeUtf8(methodName);
|
||||||
|
switch (methodName) {
|
||||||
|
case 'password':
|
||||||
|
if (oldPassword != null) {
|
||||||
|
writer.writeBool(true);
|
||||||
|
writer.writeUtf8(oldPassword!);
|
||||||
|
writer.writeUtf8(password!);
|
||||||
|
} else {
|
||||||
|
writer.writeBool(false);
|
||||||
|
writer.writeUtf8(password!);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'publickey':
|
||||||
|
writer.writeBool(signature != null);
|
||||||
|
writer.writeUtf8(publicKeyAlgorithm!);
|
||||||
|
writer.writeString(publicKey!);
|
||||||
|
if (signature != null) writer.writeString(signature!);
|
||||||
|
break;
|
||||||
|
case 'keyboard-interactive':
|
||||||
|
writer.writeUtf8(languageTag!);
|
||||||
|
writer.writeUtf8(submethods!);
|
||||||
|
break;
|
||||||
|
case 'none':
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw UnimplementedError('Unrecognized method name: $methodName');
|
||||||
|
}
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Userauth_Request(user: $user, serviceName: $serviceName, methodName: $methodName)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_Failure extends SSHMessage {
|
||||||
|
static const messageId = 51;
|
||||||
|
|
||||||
|
final List<String> methodsLeft;
|
||||||
|
final bool partialSuccess;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_Failure({
|
||||||
|
required this.methodsLeft,
|
||||||
|
this.partialSuccess = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Failure.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final methodsLeft = reader.readNameList();
|
||||||
|
final partialSuccess = reader.readBool();
|
||||||
|
return SSH_Message_Userauth_Failure(
|
||||||
|
methodsLeft: methodsLeft,
|
||||||
|
partialSuccess: partialSuccess,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeNameList(methodsLeft);
|
||||||
|
writer.writeBool(partialSuccess);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Userauth_Failure(methodsLeft: $methodsLeft, partialSuccess: $partialSuccess)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_Success extends SSHMessage {
|
||||||
|
static const messageId = 52;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_Success();
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Success.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
return SSH_Message_Userauth_Success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Userauth_Success()';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_Banner extends SSHMessage {
|
||||||
|
static const messageId = 53;
|
||||||
|
|
||||||
|
final String message;
|
||||||
|
final String language;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_Banner({
|
||||||
|
required this.message,
|
||||||
|
this.language = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Banner.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final message = reader.readUtf8();
|
||||||
|
final language = reader.readUtf8();
|
||||||
|
return SSH_Message_Userauth_Banner(
|
||||||
|
message: message,
|
||||||
|
language: language,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(message);
|
||||||
|
writer.writeUtf8(language);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Userauth_Banner(message: $message, language: $language)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_Passwd_ChangeReq extends SSHMessage {
|
||||||
|
static const messageId = 60;
|
||||||
|
|
||||||
|
final String prompt;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_Passwd_ChangeReq({
|
||||||
|
required this.prompt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_Passwd_ChangeReq.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final prompt = reader.readUtf8();
|
||||||
|
return SSH_Message_Userauth_Passwd_ChangeReq(
|
||||||
|
prompt: prompt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(prompt);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSH_Message_Userauth_Password_Change_Request(prompt: $prompt)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_InfoRequest implements SSHMessage {
|
||||||
|
static const messageId = 60;
|
||||||
|
|
||||||
|
final String name;
|
||||||
|
final String instruction;
|
||||||
|
final String lang;
|
||||||
|
final List<SSHUserInfoPrompt> prompts;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_InfoRequest({
|
||||||
|
required this.name,
|
||||||
|
required this.instruction,
|
||||||
|
required this.lang,
|
||||||
|
required this.prompts,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_InfoRequest.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final name = reader.readUtf8();
|
||||||
|
final instruction = reader.readUtf8();
|
||||||
|
final lang = reader.readUtf8();
|
||||||
|
|
||||||
|
final prompts = <SSHUserInfoPrompt>[];
|
||||||
|
final promptCount = reader.readUint32();
|
||||||
|
for (var i = 0; i < promptCount; i++) {
|
||||||
|
final prompt = reader.readUtf8();
|
||||||
|
final echo = reader.readBool();
|
||||||
|
prompts.add(SSHUserInfoPrompt(prompt, echo));
|
||||||
|
}
|
||||||
|
|
||||||
|
return SSH_Message_Userauth_InfoRequest(
|
||||||
|
name: name,
|
||||||
|
instruction: instruction,
|
||||||
|
lang: lang,
|
||||||
|
prompts: prompts,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUtf8(name);
|
||||||
|
writer.writeUtf8(instruction);
|
||||||
|
writer.writeUtf8(lang);
|
||||||
|
writer.writeUint32(prompts.length);
|
||||||
|
for (var prompt in prompts) {
|
||||||
|
writer.writeUtf8(prompt.promptText);
|
||||||
|
writer.writeBool(prompt.echo);
|
||||||
|
}
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(name: $name, instruction: $instruction, lang: $lang, prompts: $prompts)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSH_Message_Userauth_InfoResponse implements SSHMessage {
|
||||||
|
static const messageId = 61;
|
||||||
|
|
||||||
|
final List<String> responses;
|
||||||
|
|
||||||
|
SSH_Message_Userauth_InfoResponse({
|
||||||
|
required this.responses,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SSH_Message_Userauth_InfoResponse.decode(Uint8List bytes) {
|
||||||
|
final reader = SSHMessageReader(bytes);
|
||||||
|
reader.skip(1);
|
||||||
|
final responseCount = reader.readUint32();
|
||||||
|
final responses = <String>[];
|
||||||
|
for (var i = 0; i < responseCount; i++) {
|
||||||
|
responses.add(reader.readUtf8());
|
||||||
|
}
|
||||||
|
return SSH_Message_Userauth_InfoResponse(
|
||||||
|
responses: responses,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint8(messageId);
|
||||||
|
writer.writeUint32(responses.length);
|
||||||
|
for (var response in responses) {
|
||||||
|
writer.writeUtf8(response);
|
||||||
|
}
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(responses: $responses)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+723
@@ -0,0 +1,723 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_errors.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_file_attrs.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_file_open_mode.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_name.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_packet.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_packet_ext.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_request_id.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_statvfs.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_stream_io.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_channel.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_transport.dart';
|
||||||
|
import 'package:dartssh2/src/utils/chunk_buffer.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
const _kVersion = 3;
|
||||||
|
|
||||||
|
class SftpClient {
|
||||||
|
final SSHChannel _channel;
|
||||||
|
|
||||||
|
final SSHPrintHandler? printDebug;
|
||||||
|
|
||||||
|
final SSHPrintHandler? printTrace;
|
||||||
|
|
||||||
|
SftpClient(this._channel, {this.printDebug, this.printTrace}) {
|
||||||
|
_startHandshake();
|
||||||
|
_channel.stream.listen(_handleData);
|
||||||
|
}
|
||||||
|
|
||||||
|
final _buffer = ChunkBuffer();
|
||||||
|
|
||||||
|
final _handshake = Completer<SftpHandsake>();
|
||||||
|
|
||||||
|
final _done = Completer<void>();
|
||||||
|
|
||||||
|
final _requestId = SftpRequestId();
|
||||||
|
|
||||||
|
final _replyWaiters = <int, Completer<SftpResponsePacket>>{};
|
||||||
|
|
||||||
|
/// The handshake information received from the server.
|
||||||
|
Future<SftpHandsake> get handshake => _handshake.future;
|
||||||
|
|
||||||
|
/// Gets the attributes of the file at [path].
|
||||||
|
Future<SftpFileAttrs> stat(String path, {bool followLink = true}) async {
|
||||||
|
final reply = followLink ? await _sendStat(path) : await _sendLStat(path);
|
||||||
|
if (reply is SftpAttrsPacket) return reply.attrs;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the attributes of the file at [path].
|
||||||
|
Future<void> setStat(String path, SftpFileAttrs attrs) async {
|
||||||
|
final reply = await _sendSetStat(path, attrs);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens a file for reading or/and writing.
|
||||||
|
Future<SftpFile> open(
|
||||||
|
String path, {
|
||||||
|
SftpFileOpenMode mode = SftpFileOpenMode.read,
|
||||||
|
}) async {
|
||||||
|
final reply = await _sendOpen(path, mode, SftpFileAttrs());
|
||||||
|
if (reply is SftpHandlePacket) return SftpFile(this, reply.handle);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the items of a directory. Returns an [Stream] of [SftpName] chunks.
|
||||||
|
/// Use [listdir] instead of this unless the directory contains a large number
|
||||||
|
/// of items.
|
||||||
|
Stream<List<SftpName>> readdir(String path) async* {
|
||||||
|
final dir = await _opendir(path);
|
||||||
|
while (true) {
|
||||||
|
final names = await _readdir(dir);
|
||||||
|
if (names == null) break;
|
||||||
|
yield names;
|
||||||
|
}
|
||||||
|
await _close(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List the items of a directory. This is a convenience method wrapping
|
||||||
|
/// [readdir].
|
||||||
|
Future<List<SftpName>> listdir(String path) async {
|
||||||
|
final result = <SftpName>[];
|
||||||
|
await for (final names in readdir(path)) {
|
||||||
|
result.addAll(names);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a file whose name is [filename]. This can only be used to remove
|
||||||
|
/// files. Use [rmdir] to remove a directory.
|
||||||
|
Future<void> remove(String filename) async {
|
||||||
|
final reply = await _sendRemove(filename);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes a directory at the given [path].
|
||||||
|
Future<void> mkdir(String path, [SftpFileAttrs? attrs]) async {
|
||||||
|
final reply = await _sendMakeDir(path, attrs ?? SftpFileAttrs());
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a directory whose name is [dirname]. This can only be used to
|
||||||
|
/// remove directories. Use [remove] to remove a file.
|
||||||
|
/// This will fail if the directory is not empty.
|
||||||
|
Future<void> rmdir(String dirname) async {
|
||||||
|
final reply = await _sendRemoveDir(dirname);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the absolute path of [path].
|
||||||
|
Future<String> absolute(String path) async {
|
||||||
|
final reply = await _sendRealPath(path);
|
||||||
|
if (reply is SftpNamePacket) return reply.names.first.filename;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renames a file or directory from [oldPath] to [newPath].
|
||||||
|
Future<void> rename(String oldPath, String newPath) async {
|
||||||
|
final reply = await _sendRename(oldPath, newPath);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the target of a symbolic link.
|
||||||
|
Future<String> readlink(String path) async {
|
||||||
|
final reply = await _sendReadLink(path);
|
||||||
|
if (reply is SftpNamePacket) return reply.names.first.filename;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a symbolic link at [targetPath] that points to [linkPath].
|
||||||
|
Future<void> link(String linkPath, String targetPath) async {
|
||||||
|
final reply = await _sendSymlink(linkPath, targetPath);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the information about a mounted filesystem. [path] is the pathname of
|
||||||
|
/// any file within the mounted filesystem.
|
||||||
|
///
|
||||||
|
/// **Note**: This is an extension to the SFTP protocol, supported by most
|
||||||
|
/// openssh servers. A [SftpExtensionError] is thrown if the server does not
|
||||||
|
/// support this extension.
|
||||||
|
///
|
||||||
|
/// See also:
|
||||||
|
///
|
||||||
|
/// - [SftpFile.statvfs] which requires an open [SftpFile] instance instead of
|
||||||
|
/// a path.
|
||||||
|
Future<SftpStatVfs> statvfs(String path) async {
|
||||||
|
await _checkExtension('statvfs@openssh.com', '2');
|
||||||
|
final payload = SftpStatVfsRequest(path: path);
|
||||||
|
final reply = await _sendExtended(payload);
|
||||||
|
if (reply is SftpStatusPacket) throw SftpStatusError.fromStatus(reply);
|
||||||
|
if (reply is! SftpExtendedReplyPacket) throw SftpError('Unexpected reply');
|
||||||
|
final stat = SftpStatVfsReply.decode(reply.payload);
|
||||||
|
return SftpStatVfs.fromReply(stat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close the sftp session.
|
||||||
|
void close() {
|
||||||
|
for (var waiter in _replyWaiters.values) {
|
||||||
|
waiter.completeError(SftpAbortError("Connection closed"));
|
||||||
|
}
|
||||||
|
_replyWaiters.clear();
|
||||||
|
_done.complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _closeError(Object error, [StackTrace? stackTrace]) {
|
||||||
|
stackTrace ??= StackTrace.current;
|
||||||
|
for (var waiter in _replyWaiters.values) {
|
||||||
|
waiter.completeError(error, stackTrace);
|
||||||
|
}
|
||||||
|
_replyWaiters.clear();
|
||||||
|
_done.completeError(error, stackTrace);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _startHandshake() {
|
||||||
|
_sendPacket(SftpInitPacket(_kVersion));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a directory and return the handle.
|
||||||
|
Future<Uint8List> _opendir(String path) async {
|
||||||
|
final reply = await _sendOpenDir(path);
|
||||||
|
if (reply is SftpHandlePacket) return reply.handle;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the next bunch of entries from the directory. Returns `null` when
|
||||||
|
/// there are no more entries.
|
||||||
|
Future<List<SftpName>?> _readdir(Uint8List handle) async {
|
||||||
|
final reply = await _sendReadDir(handle);
|
||||||
|
if (reply is SftpNamePacket) return reply.names;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _close(Uint8List handle) async {
|
||||||
|
final reply = await _sendClose(handle);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendPacket(SftpPacket packet) {
|
||||||
|
printTrace?.call('-> $_channel: $packet');
|
||||||
|
final data = packet.encode();
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUint32(data.length);
|
||||||
|
writer.writeBytes(data);
|
||||||
|
_channel.addData(writer.takeBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendOpen(
|
||||||
|
String path,
|
||||||
|
SftpFileOpenMode mode,
|
||||||
|
SftpFileAttrs attrs,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpOpenPacket(_requestId.next, path, mode.flag, attrs);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendClose(Uint8List handle) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpClosePacket(_requestId.next, handle);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendRead(
|
||||||
|
Uint8List handle,
|
||||||
|
int offset,
|
||||||
|
int length,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpReadPacket(
|
||||||
|
requestId: _requestId.next,
|
||||||
|
handle: handle,
|
||||||
|
offset: offset,
|
||||||
|
length: length,
|
||||||
|
);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendWrite(
|
||||||
|
Uint8List handle,
|
||||||
|
int offset,
|
||||||
|
Uint8List data,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpWritePacket(
|
||||||
|
requestId: _requestId.next,
|
||||||
|
handle: handle,
|
||||||
|
offset: offset,
|
||||||
|
data: data,
|
||||||
|
);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendLStat(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpLStatPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendFStat(Uint8List handle) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpFStatPacket(_requestId.next, handle);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendSetStat(
|
||||||
|
String path,
|
||||||
|
SftpFileAttrs attrs,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpSetStatPacket(_requestId.next, path, attrs);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendFSetStat(
|
||||||
|
Uint8List handle,
|
||||||
|
SftpFileAttrs attrs,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpFSetStatPacket(_requestId.next, handle, attrs);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendOpenDir(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpOpenDirPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendReadDir(Uint8List handle) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpReadDirPacket(_requestId.next, handle);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendRemove(String filename) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpRemovePacket(_requestId.next, filename);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendMakeDir(
|
||||||
|
String path,
|
||||||
|
SftpFileAttrs attrs,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpMkdirPacket(_requestId.next, path, attrs);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendRemoveDir(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpRmdirPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendRealPath(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpRealpathPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendStat(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpStatPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendRename(
|
||||||
|
String oldPath,
|
||||||
|
String newPath,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpRenamePacket(_requestId.next, oldPath, newPath);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendReadLink(String path) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpReadlinkPacket(_requestId.next, path);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendSymlink(
|
||||||
|
String linkPath,
|
||||||
|
String targetPath,
|
||||||
|
) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpSymlinkPacket(_requestId.next, linkPath, targetPath);
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _sendExtended(SftpExtendedRequest payload) async {
|
||||||
|
await handshake;
|
||||||
|
final request = SftpExtendedPacket(_requestId.next, payload.encode());
|
||||||
|
_sendPacket(request);
|
||||||
|
return await _waitReply(request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _dispatchReply(SftpResponsePacket packet) {
|
||||||
|
final completer = _replyWaiters.remove(packet.requestId);
|
||||||
|
completer?.complete(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpResponsePacket> _waitReply(int requestId) {
|
||||||
|
final completer = Completer<SftpResponsePacket>();
|
||||||
|
_replyWaiters[requestId] = completer;
|
||||||
|
return completer.future;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _checkExtension(String name, String version) async {
|
||||||
|
final handshake = await this.handshake;
|
||||||
|
final extensionVersion = handshake.extensions[name];
|
||||||
|
if (extensionVersion == null) {
|
||||||
|
throw SftpExtensionUnsupportedError(name);
|
||||||
|
}
|
||||||
|
if (extensionVersion != version) {
|
||||||
|
throw SftpExtensionVersionMismatchError(name, extensionVersion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleData(SSHChannelData data) {
|
||||||
|
_buffer.add(data.bytes);
|
||||||
|
_handlePackets();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handlePackets() {
|
||||||
|
const lengthHeader = 4; // 4 bytes packet length header
|
||||||
|
while (_buffer.length >= lengthHeader) {
|
||||||
|
final length = _buffer.byteData.getUint32(0);
|
||||||
|
if (_buffer.length < lengthHeader + length) break;
|
||||||
|
final packet = _buffer.consume(lengthHeader + length);
|
||||||
|
final payload = Uint8List.sublistView(packet, lengthHeader);
|
||||||
|
_handlePacket(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handlePacket(Uint8List payload) {
|
||||||
|
final type = payload[0];
|
||||||
|
switch (type) {
|
||||||
|
case SftpVersionPacket.packetType:
|
||||||
|
return _handleVersionPacket(payload);
|
||||||
|
case SftpStatusPacket.packetType:
|
||||||
|
return _handleStatusPacket(payload);
|
||||||
|
case SftpHandlePacket.packetType:
|
||||||
|
return _handleHandlePacket(payload);
|
||||||
|
case SftpDataPacket.packetType:
|
||||||
|
return _handleDataPacket(payload);
|
||||||
|
case SftpNamePacket.packetType:
|
||||||
|
return _handleNamePacket(payload);
|
||||||
|
case SftpAttrsPacket.packetType:
|
||||||
|
return _handleAttrsPacket(payload);
|
||||||
|
case SftpExtendedReplyPacket.packetType:
|
||||||
|
return _handleExtendedReplyPacket(payload);
|
||||||
|
default:
|
||||||
|
printDebug?.call('SftpClient._handlePacket: unknown packet: $type');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleVersionPacket(Uint8List payload) {
|
||||||
|
final packet = SftpVersionPacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
|
||||||
|
if (packet.version == _kVersion) {
|
||||||
|
final handshake = SftpHandsake(packet.version, packet.extensions);
|
||||||
|
return _handshake.complete(handshake);
|
||||||
|
}
|
||||||
|
|
||||||
|
final error = SftpError('Version mismatch: ${packet.version}');
|
||||||
|
_handshake.completeError(error, StackTrace.current);
|
||||||
|
_closeError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleStatusPacket(Uint8List payload) {
|
||||||
|
final packet = SftpStatusPacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleHandlePacket(Uint8List payload) {
|
||||||
|
final packet = SftpHandlePacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleNamePacket(Uint8List payload) {
|
||||||
|
final packet = SftpNamePacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleDataPacket(Uint8List payload) {
|
||||||
|
final packet = SftpDataPacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: len=${packet.data.length}');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleAttrsPacket(Uint8List payload) {
|
||||||
|
final packet = SftpAttrsPacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleExtendedReplyPacket(Uint8List payload) {
|
||||||
|
final packet = SftpExtendedReplyPacket.decode(payload);
|
||||||
|
printTrace?.call('<- $_channel: $packet');
|
||||||
|
_dispatchReply(packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpFile {
|
||||||
|
final Uint8List _handle;
|
||||||
|
|
||||||
|
final SftpClient _client;
|
||||||
|
|
||||||
|
SftpFile(this._client, this._handle);
|
||||||
|
|
||||||
|
var _isClosed = false;
|
||||||
|
|
||||||
|
bool get isClosed => _isClosed;
|
||||||
|
|
||||||
|
Future<void> close() async {
|
||||||
|
if (_isClosed) return;
|
||||||
|
_isClosed = true;
|
||||||
|
await _client._close(_handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SftpFileAttrs> stat() async {
|
||||||
|
_mustNotBeClosed();
|
||||||
|
final reply = await _client._sendFStat(_handle);
|
||||||
|
if (reply is SftpAttrsPacket) return reply.attrs;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
throw SftpStatusError.fromStatus(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setStat(SftpFileAttrs attrs) async {
|
||||||
|
_mustNotBeClosed();
|
||||||
|
final reply = await _client._sendFSetStat(_handle, attrs);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads at most [count] bytes from the file starting at [offset]. If
|
||||||
|
/// [length] is null, reads until end of file. Returns a [Stream] of chunks.
|
||||||
|
/// [onProgress] is called with the total number of bytes already read.
|
||||||
|
/// Use [readBytes] if you want a single Uint8List.
|
||||||
|
Stream<Uint8List> read({
|
||||||
|
int? length,
|
||||||
|
int offset = 0,
|
||||||
|
void Function(int bytesRead)? onProgress,
|
||||||
|
}) async* {
|
||||||
|
const chunkSize = 16 * 1024;
|
||||||
|
const maxBytesOnTheWire = chunkSize * 64;
|
||||||
|
|
||||||
|
// Get the file size if not specified.
|
||||||
|
if (length == null) {
|
||||||
|
final fileStat = await stat();
|
||||||
|
final fileSize = fileStat.size;
|
||||||
|
|
||||||
|
if (fileSize == null) {
|
||||||
|
throw SftpError('Can not get file size');
|
||||||
|
}
|
||||||
|
|
||||||
|
length = fileSize - offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length == 0) return;
|
||||||
|
|
||||||
|
if (length < 0) {
|
||||||
|
throw SftpError('Length must be positive: $length');
|
||||||
|
}
|
||||||
|
|
||||||
|
final streamController = StreamController<Uint8List>();
|
||||||
|
|
||||||
|
var bytessRecieved = 0;
|
||||||
|
var bytessRequested = 0;
|
||||||
|
// 补丁:length 为 int?,await 之后无法类型提升,复制为非空局部变量
|
||||||
|
final totalLength = length;
|
||||||
|
|
||||||
|
Future<void> readChunk(int chunkStart) async {
|
||||||
|
final chunkEnd = min(chunkStart + chunkSize, offset + length!);
|
||||||
|
final chunkLength = chunkEnd - chunkStart;
|
||||||
|
|
||||||
|
bytessRequested += chunkLength;
|
||||||
|
|
||||||
|
late final Uint8List? chunk;
|
||||||
|
|
||||||
|
try {
|
||||||
|
chunk = await _readChunk(chunkLength, chunkStart);
|
||||||
|
} catch (e, st) {
|
||||||
|
if (!streamController.isClosed) {
|
||||||
|
streamController.addError(e, st);
|
||||||
|
streamController.close();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chunk == null) {
|
||||||
|
streamController.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
streamController.add(chunk);
|
||||||
|
bytessRecieved += chunkLength;
|
||||||
|
|
||||||
|
if (onProgress != null) onProgress(bytessRecieved);
|
||||||
|
|
||||||
|
if (totalLength != null && bytessRecieved >= totalLength) {
|
||||||
|
streamController.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void scheduleRead() {
|
||||||
|
if (streamController.isPaused || streamController.isClosed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (bytessRequested < length!) {
|
||||||
|
final bytesOnTheWire = bytessRequested - bytessRecieved;
|
||||||
|
if (bytesOnTheWire >= maxBytesOnTheWire) return;
|
||||||
|
readChunk(bytessRequested + offset).then((_) => scheduleRead());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
streamController.onListen = scheduleRead;
|
||||||
|
streamController.onResume = scheduleRead;
|
||||||
|
|
||||||
|
yield* streamController.stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads at most [length] bytes from the file starting at [offset]. If
|
||||||
|
/// [length] is null, reads until end of the file.
|
||||||
|
/// Use [read] if you want to stream large file in chunks.
|
||||||
|
Future<Uint8List> readBytes({int? length, int offset = 0}) async {
|
||||||
|
final buffer = BytesBuilder(copy: false);
|
||||||
|
await for (final chunk in read(length: length, offset: offset)) {
|
||||||
|
buffer.add(chunk);
|
||||||
|
}
|
||||||
|
return buffer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes [stream] to the file starting at [offset].
|
||||||
|
///
|
||||||
|
/// Returns a [SftpFileWriter] that can be used to control the write
|
||||||
|
/// operation or wait for it to complete.
|
||||||
|
SftpFileWriter write(
|
||||||
|
Stream<Uint8List> stream, {
|
||||||
|
int offset = 0,
|
||||||
|
void Function(int total)? onProgress,
|
||||||
|
}) {
|
||||||
|
return SftpFileWriter(this, stream, offset, onProgress);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes [data] to the file starting at [offset].
|
||||||
|
Future<void> writeBytes(Uint8List data, {int offset = 0}) async {
|
||||||
|
const maxChunkSize = 16 * 1024;
|
||||||
|
var bytesSent = 0;
|
||||||
|
final futures = <Future<void>>[];
|
||||||
|
while (bytesSent < data.length) {
|
||||||
|
final chunkSize = min(data.length - bytesSent, maxChunkSize);
|
||||||
|
final chunkBegin = bytesSent;
|
||||||
|
final chunkEnd = chunkBegin + chunkSize;
|
||||||
|
final chunk = Uint8List.sublistView(data, chunkBegin, chunkEnd);
|
||||||
|
futures.add(_writeChunk(chunk, offset: offset + bytesSent));
|
||||||
|
bytesSent += chunkSize;
|
||||||
|
}
|
||||||
|
await Future.wait(futures);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets filesystem statistics that this file is on.
|
||||||
|
///
|
||||||
|
/// **Note**: This is an extension to the SFTP protocol, supported by most
|
||||||
|
/// openssh servers. A [SftpExtensionError] is thrown if the server does not
|
||||||
|
/// support this extension.
|
||||||
|
///
|
||||||
|
/// See also:
|
||||||
|
///
|
||||||
|
/// * [SftpClient.statvfs] which takes a path instead of a file handle as
|
||||||
|
/// argument.
|
||||||
|
Future<SftpStatVfs> statvfs() async {
|
||||||
|
_mustNotBeClosed();
|
||||||
|
await _client._checkExtension('fstatvfs@openssh.com', '2');
|
||||||
|
final payload = SftpFstatVfsRequest(handle: _handle);
|
||||||
|
final reply = await _client._sendExtended(payload);
|
||||||
|
if (reply is SftpStatusPacket) throw SftpStatusError.fromStatus(reply);
|
||||||
|
if (reply is! SftpExtendedReplyPacket) throw SftpError('Unexpected reply');
|
||||||
|
final stat = SftpStatVfsReply.decode(reply.payload);
|
||||||
|
return SftpStatVfs.fromReply(stat);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _writeChunk(Uint8List data, {int offset = 0}) async {
|
||||||
|
// print('_writeChunk: offset=$offset');
|
||||||
|
_mustNotBeClosed();
|
||||||
|
final reply = await _client._sendWrite(_handle, offset, data);
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Uint8List?> _readChunk(int length, [int offset = 0]) async {
|
||||||
|
_mustNotBeClosed();
|
||||||
|
final reply = await _client._sendRead(_handle, offset, length);
|
||||||
|
if (reply is SftpDataPacket) return reply.data;
|
||||||
|
if (reply is! SftpStatusPacket) throw SftpError('Unexpected reply');
|
||||||
|
SftpStatusError.check(reply);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _mustNotBeClosed() {
|
||||||
|
if (isClosed) throw SftpError('File is closed');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'SftpFile(0x${hex.encode(_handle)})';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handsake information received from the server.
|
||||||
|
class SftpHandsake {
|
||||||
|
final int version;
|
||||||
|
|
||||||
|
final Map<String, String> extensions;
|
||||||
|
|
||||||
|
SftpHandsake(this.version, this.extensions);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'SftpHandsake($version, $extensions)';
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import 'package:dartssh2/src/sftp/sftp_packet.dart';
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_status_code.dart';
|
||||||
|
|
||||||
|
class SftpError {
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SftpError(this.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpError: $message';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpAbortError implements SftpError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SftpAbortError(this.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpAbortError: $message';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpStatusError implements SftpError {
|
||||||
|
final int code;
|
||||||
|
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SftpStatusError(this.code, this.message);
|
||||||
|
|
||||||
|
SftpStatusError.fromStatus(SftpStatusPacket status)
|
||||||
|
: code = status.code,
|
||||||
|
message = status.message;
|
||||||
|
|
||||||
|
static void check(SftpStatusPacket status) {
|
||||||
|
if (status.code != SftpStatusCode.ok && status.code != SftpStatusCode.eof) {
|
||||||
|
throw SftpStatusError.fromStatus(status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpStatusError: $message(code $code)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* sealed */ abstract class SftpExtensionError implements SftpError {}
|
||||||
|
|
||||||
|
class SftpExtensionUnsupportedError implements SftpExtensionError {
|
||||||
|
final String extension;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get message => 'Extension "$extension" is not supported';
|
||||||
|
|
||||||
|
SftpExtensionUnsupportedError(this.extension);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpExtensionUnsupportedError: $message';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpExtensionVersionMismatchError implements SftpExtensionError {
|
||||||
|
final String extension;
|
||||||
|
|
||||||
|
final String version;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get message =>
|
||||||
|
'Extension "$extension" of version $version is not supported';
|
||||||
|
|
||||||
|
SftpExtensionVersionMismatchError(this.extension, this.version);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpExtensionVersionMismatchError: $message';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import 'package:dartssh2/src/utils/int.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
abstract class _Flags {
|
||||||
|
static const size = 0x00000001;
|
||||||
|
static const uidgid = 0x00000002;
|
||||||
|
static const permissions = 0x00000004;
|
||||||
|
static const acmodtime = 0x00000008;
|
||||||
|
static const extended = 0x80000000;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class _PermissionFlags {
|
||||||
|
/// 0400
|
||||||
|
static const userRead = 1 << 8;
|
||||||
|
|
||||||
|
/// 0200
|
||||||
|
static const userWrite = 1 << 7;
|
||||||
|
|
||||||
|
/// 0100
|
||||||
|
static const userExecute = 1 << 6;
|
||||||
|
|
||||||
|
/// 0040
|
||||||
|
static const groupRead = 1 << 5;
|
||||||
|
|
||||||
|
/// 0020
|
||||||
|
static const groupWrite = 1 << 4;
|
||||||
|
|
||||||
|
/// 0010
|
||||||
|
static const groupExecute = 1 << 3;
|
||||||
|
|
||||||
|
/// 0004
|
||||||
|
static const otherRead = 1 << 2;
|
||||||
|
|
||||||
|
/// 0002
|
||||||
|
static const otherWrite = 1 << 1;
|
||||||
|
|
||||||
|
/// 0001
|
||||||
|
static const otherExecute = 1 << 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class _ModeFlags {
|
||||||
|
/// 0010000
|
||||||
|
static const isPipe = 1 << 12;
|
||||||
|
|
||||||
|
/// 0020000
|
||||||
|
static const isCharacterDevice = 1 << 13;
|
||||||
|
|
||||||
|
/// 0040000
|
||||||
|
static const isDirectory = 1 << 14;
|
||||||
|
|
||||||
|
/// 0060000
|
||||||
|
static const isBlockDevice = (1 << 14) + (1 << 13);
|
||||||
|
|
||||||
|
/// 0100000
|
||||||
|
static const isRegularFile = 1 << 15;
|
||||||
|
|
||||||
|
/// 0120000
|
||||||
|
static const isSymbolicLink = (1 << 15) + (1 << 13);
|
||||||
|
|
||||||
|
/// 0140000
|
||||||
|
static const isSocket = (1 << 15) + (1 << 14);
|
||||||
|
|
||||||
|
/// 0160000
|
||||||
|
static const isWhiteout = (1 << 15) + (1 << 14) + (1 << 13);
|
||||||
|
|
||||||
|
/// 0170000
|
||||||
|
static const mask = (1 << 15) + (1 << 14) + (1 << 13) + (1 << 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
extension _IntFlag on int {
|
||||||
|
bool has(int flag) => (this & flag) == flag;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SftpFileType {
|
||||||
|
unknown,
|
||||||
|
regularFile,
|
||||||
|
directory,
|
||||||
|
symbolicLink,
|
||||||
|
blockDevice,
|
||||||
|
characterDevice,
|
||||||
|
pipe,
|
||||||
|
socket,
|
||||||
|
whiteout,
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpFileMode {
|
||||||
|
factory SftpFileMode({
|
||||||
|
bool userRead = true,
|
||||||
|
bool userWrite = true,
|
||||||
|
bool userExecute = true,
|
||||||
|
bool groupRead = true,
|
||||||
|
bool groupWrite = true,
|
||||||
|
bool groupExecute = true,
|
||||||
|
bool otherRead = true,
|
||||||
|
bool otherWrite = true,
|
||||||
|
bool otherExecute = true,
|
||||||
|
}) {
|
||||||
|
var flags = 0;
|
||||||
|
if (userRead) flags |= _PermissionFlags.userRead;
|
||||||
|
if (userWrite) flags |= _PermissionFlags.userWrite;
|
||||||
|
if (userExecute) flags |= _PermissionFlags.userExecute;
|
||||||
|
if (groupRead) flags |= _PermissionFlags.groupRead;
|
||||||
|
if (groupWrite) flags |= _PermissionFlags.groupWrite;
|
||||||
|
if (groupExecute) flags |= _PermissionFlags.groupExecute;
|
||||||
|
if (otherRead) flags |= _PermissionFlags.otherRead;
|
||||||
|
if (otherWrite) flags |= _PermissionFlags.otherWrite;
|
||||||
|
if (otherExecute) flags |= _PermissionFlags.otherExecute;
|
||||||
|
return SftpFileMode.value(flags);
|
||||||
|
}
|
||||||
|
|
||||||
|
const SftpFileMode.value(this.value);
|
||||||
|
|
||||||
|
final int value;
|
||||||
|
|
||||||
|
bool get userRead => value.has(_PermissionFlags.userRead);
|
||||||
|
bool get userWrite => value.has(_PermissionFlags.userWrite);
|
||||||
|
bool get userExecute => value.has(_PermissionFlags.userExecute);
|
||||||
|
|
||||||
|
bool get groupRead => value.has(_PermissionFlags.groupRead);
|
||||||
|
bool get groupWrite => value.has(_PermissionFlags.groupWrite);
|
||||||
|
bool get groupExecute => value.has(_PermissionFlags.groupExecute);
|
||||||
|
|
||||||
|
bool get otherRead => value.has(_PermissionFlags.otherRead);
|
||||||
|
bool get otherWrite => value.has(_PermissionFlags.otherWrite);
|
||||||
|
bool get otherExecute => value.has(_PermissionFlags.otherExecute);
|
||||||
|
|
||||||
|
SftpFileType get type {
|
||||||
|
var type = value & _ModeFlags.mask;
|
||||||
|
switch (type) {
|
||||||
|
case _ModeFlags.isPipe:
|
||||||
|
return SftpFileType.pipe;
|
||||||
|
case _ModeFlags.isCharacterDevice:
|
||||||
|
return SftpFileType.characterDevice;
|
||||||
|
case _ModeFlags.isDirectory:
|
||||||
|
return SftpFileType.directory;
|
||||||
|
case _ModeFlags.isBlockDevice:
|
||||||
|
return SftpFileType.blockDevice;
|
||||||
|
case _ModeFlags.isRegularFile:
|
||||||
|
return SftpFileType.regularFile;
|
||||||
|
case _ModeFlags.isSymbolicLink:
|
||||||
|
return SftpFileType.symbolicLink;
|
||||||
|
case _ModeFlags.isSocket:
|
||||||
|
return SftpFileType.socket;
|
||||||
|
case _ModeFlags.isWhiteout:
|
||||||
|
return SftpFileType.whiteout;
|
||||||
|
default:
|
||||||
|
return SftpFileType.unknown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(${value.toOctal()})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SftpFileAttrs {
|
||||||
|
/// The size of the file in bytes.
|
||||||
|
final int? size;
|
||||||
|
|
||||||
|
/// The user ID of the file.
|
||||||
|
final int? userID;
|
||||||
|
|
||||||
|
/// The group ID of the file.
|
||||||
|
final int? groupID;
|
||||||
|
|
||||||
|
/// The mode of the file, including file type and permissions.
|
||||||
|
final SftpFileMode? mode;
|
||||||
|
|
||||||
|
/// The access time of the file in seconds since the epoch.
|
||||||
|
final int? accessTime;
|
||||||
|
|
||||||
|
/// The modification time of the file in seconds since the epoch.
|
||||||
|
final int? modifyTime;
|
||||||
|
|
||||||
|
/// The extended attributes of the file.
|
||||||
|
final Map<String, String>? extended;
|
||||||
|
|
||||||
|
SftpFileAttrs({
|
||||||
|
this.size,
|
||||||
|
this.userID,
|
||||||
|
this.groupID,
|
||||||
|
this.mode,
|
||||||
|
this.accessTime,
|
||||||
|
this.modifyTime,
|
||||||
|
this.extended,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SftpFileAttrs.readFrom(SSHMessageReader reader) {
|
||||||
|
final flags = reader.readUint32();
|
||||||
|
final size = flags.has(_Flags.size) ? reader.readUint64() : null;
|
||||||
|
final uid = flags.has(_Flags.uidgid) ? reader.readUint32() : null;
|
||||||
|
final gid = flags.has(_Flags.uidgid) ? reader.readUint32() : null;
|
||||||
|
final perms = flags.has(_Flags.permissions) ? reader.readUint32() : null;
|
||||||
|
final atime = flags.has(_Flags.acmodtime) ? reader.readUint32() : null;
|
||||||
|
final mtime = flags.has(_Flags.acmodtime) ? reader.readUint32() : null;
|
||||||
|
|
||||||
|
final extended = flags.has(_Flags.extended) ? <String, String>{} : null;
|
||||||
|
if (extended != null) {
|
||||||
|
final count = reader.readUint32();
|
||||||
|
for (var i = 0; i < count; i++) {
|
||||||
|
final key = reader.readUtf8();
|
||||||
|
final value = reader.readUtf8();
|
||||||
|
extended[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SftpFileAttrs(
|
||||||
|
size: size,
|
||||||
|
userID: uid,
|
||||||
|
groupID: gid,
|
||||||
|
mode: perms != null ? SftpFileMode.value(perms) : null,
|
||||||
|
accessTime: atime,
|
||||||
|
modifyTime: mtime,
|
||||||
|
extended: extended,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the file is a regular file. See [type].
|
||||||
|
bool get isDirectory => mode?.type == SftpFileType.directory;
|
||||||
|
|
||||||
|
/// Whether the file is a symbolic link. See [type].
|
||||||
|
bool get isFile => mode?.type == SftpFileType.regularFile;
|
||||||
|
|
||||||
|
/// Whether the file is a symbolic link. See [type].
|
||||||
|
bool get isSymbolicLink => mode?.type == SftpFileType.symbolicLink;
|
||||||
|
|
||||||
|
/// Whether the file is a block device. See [type].
|
||||||
|
bool get isBlockDevice => mode?.type == SftpFileType.blockDevice;
|
||||||
|
|
||||||
|
/// Whether the file is a character device. See [type].
|
||||||
|
bool get isCharacterDevice => mode?.type == SftpFileType.characterDevice;
|
||||||
|
|
||||||
|
/// Whether the file is a pipe. See [type].
|
||||||
|
bool get isPipe => mode?.type == SftpFileType.pipe;
|
||||||
|
|
||||||
|
/// Whether the file is a socket. See [type].
|
||||||
|
bool get isSocket => mode?.type == SftpFileType.socket;
|
||||||
|
|
||||||
|
/// Whether the file is a whiteout. See [type].
|
||||||
|
bool get isWhiteout => mode?.type == SftpFileType.whiteout;
|
||||||
|
|
||||||
|
/// Shortcut for [mode]?.type
|
||||||
|
SftpFileType? get type => mode?.type;
|
||||||
|
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
var flags = 0;
|
||||||
|
if (size != null) flags |= _Flags.size;
|
||||||
|
if (userID != null) flags |= _Flags.uidgid;
|
||||||
|
if (groupID != null) flags |= _Flags.uidgid;
|
||||||
|
if (mode != null) flags |= _Flags.permissions;
|
||||||
|
if (accessTime != null) flags |= _Flags.acmodtime;
|
||||||
|
if (modifyTime != null) flags |= _Flags.acmodtime;
|
||||||
|
if (extended != null) flags |= _Flags.extended;
|
||||||
|
|
||||||
|
writer.writeUint32(flags);
|
||||||
|
if (size != null) writer.writeUint64(size!);
|
||||||
|
if (userID != null) writer.writeUint32(userID!);
|
||||||
|
if (groupID != null) writer.writeUint32(groupID!);
|
||||||
|
if (mode != null) writer.writeUint32(mode!.value);
|
||||||
|
if (accessTime != null) writer.writeUint32(accessTime!);
|
||||||
|
if (modifyTime != null) writer.writeUint32(modifyTime!);
|
||||||
|
|
||||||
|
if (extended != null) {
|
||||||
|
writer.writeUint32(extended!.length);
|
||||||
|
for (var pair in extended!.entries) {
|
||||||
|
writer.writeUtf8(pair.key);
|
||||||
|
writer.writeUtf8(pair.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
final props = <String>[];
|
||||||
|
if (size != null) props.add('size: $size');
|
||||||
|
if (userID != null) props.add('uid: $userID');
|
||||||
|
if (groupID != null) props.add('gid: $groupID');
|
||||||
|
if (mode != null) props.add('mode: otc($mode)');
|
||||||
|
if (accessTime != null) props.add('atime: $accessTime');
|
||||||
|
if (modifyTime != null) props.add('mtime: $modifyTime');
|
||||||
|
if (extended != null) props.add('extended: $extended');
|
||||||
|
return 'SftpFileAttrs(${props.join(', ')})';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
class SftpFileOpenMode {
|
||||||
|
/// Open the file for reading.
|
||||||
|
static const read = SftpFileOpenMode._(1 << 0);
|
||||||
|
|
||||||
|
/// Open the file for writing.
|
||||||
|
/// If both this and [read] are specified, the file is opened for both reading
|
||||||
|
/// and writing.
|
||||||
|
static const write = SftpFileOpenMode._(1 << 1);
|
||||||
|
|
||||||
|
/// Force all writes to append data at the end of the file.
|
||||||
|
static const append = SftpFileOpenMode._(1 << 2);
|
||||||
|
|
||||||
|
/// If this flag is specified, then a new file will be created if one
|
||||||
|
/// does not already exist (if [truncate] is specified, the new file will
|
||||||
|
/// be truncated to zero length if it previously exists).
|
||||||
|
static const create = SftpFileOpenMode._(1 << 3);
|
||||||
|
|
||||||
|
/// Forces an existing file with the same name to be truncated to zero
|
||||||
|
/// length when creating a file by specifying [create]. [create] MUST also be
|
||||||
|
/// specified if this flag is used.
|
||||||
|
static const truncate = SftpFileOpenMode._(1 << 4);
|
||||||
|
|
||||||
|
/// Causes the request to fail if the named file already exists.
|
||||||
|
/// [create] MUST also be specified if this flag is used.
|
||||||
|
static const exclusive = SftpFileOpenMode._(1 << 5);
|
||||||
|
|
||||||
|
/// Internal integer flag representing the file open mode.
|
||||||
|
final int flag;
|
||||||
|
|
||||||
|
/// Private constructor used to create instances of [SftpFileOpenMode] with specific flags.
|
||||||
|
///
|
||||||
|
/// This constructor is marked as private (`._`) to restrict direct instantiation and ensure
|
||||||
|
/// that only predefined modes like [read], [write], etc., can be used.
|
||||||
|
const SftpFileOpenMode._(this.flag);
|
||||||
|
|
||||||
|
/// Overloads the bitwise OR operator `|` for the `SftpFileOpenMode` class.
|
||||||
|
///
|
||||||
|
/// This operator allows combining two `SftpFileOpenMode` instances by performing
|
||||||
|
/// a bitwise OR operation on their respective flags. The result is a new
|
||||||
|
/// `SftpFileOpenMode` instance that represents the combined flags of both modes.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// SftpFileOpenMode readMode = SftpFileOpenMode.read;
|
||||||
|
/// SftpFileOpenMode writeMode = SftpFileOpenMode.write;
|
||||||
|
///
|
||||||
|
/// SftpFileOpenMode combinedMode = readMode | writeMode;
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// In the example above, the `combinedMode` will contain the flags of both
|
||||||
|
/// `readMode` and `writeMode`.
|
||||||
|
///
|
||||||
|
/// - Parameter [other]: Another instance of `SftpFileOpenMode` to combine with.
|
||||||
|
/// - Returns: A new `SftpFileOpenMode` instance containing the combined flags.
|
||||||
|
SftpFileOpenMode operator |(SftpFileOpenMode other) =>
|
||||||
|
SftpFileOpenMode._(flag | other.flag);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import 'package:dartssh2/src/sftp/sftp_file_attrs.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
class SftpName {
|
||||||
|
final String filename;
|
||||||
|
|
||||||
|
final String longname;
|
||||||
|
|
||||||
|
final SftpFileAttrs attr;
|
||||||
|
|
||||||
|
SftpName({
|
||||||
|
required this.filename,
|
||||||
|
required this.longname,
|
||||||
|
required this.attr,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SftpName.readFrom(SSHMessageReader reader) {
|
||||||
|
final filename = reader.readUtf8();
|
||||||
|
final longname = reader.readUtf8();
|
||||||
|
final attr = SftpFileAttrs.readFrom(reader);
|
||||||
|
return SftpName(
|
||||||
|
filename: filename,
|
||||||
|
longname: longname,
|
||||||
|
attr: attr,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeUtf8(filename);
|
||||||
|
writer.writeUtf8(longname);
|
||||||
|
attr.writeTo(writer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpName(filename: $filename, longname: $longname, attr: $attr)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+1042
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,135 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_packet.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
/// Represents the payload of an extended request. Should be wrapped in a
|
||||||
|
/// [SftpExtendedPacket] before being sent.
|
||||||
|
abstract class SftpExtendedRequest {
|
||||||
|
/// The name to identify the extended request.
|
||||||
|
///
|
||||||
|
/// This string is encoded as the first field of the extended request body.
|
||||||
|
String get name;
|
||||||
|
|
||||||
|
/// Writes the extended request body to the [writer].
|
||||||
|
void writeTo(SSHMessageWriter writer);
|
||||||
|
|
||||||
|
/// Encodes the extended request body including the name.
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(name);
|
||||||
|
writeTo(writer);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the payload of an extended reply. Should be wrapped in a
|
||||||
|
/// [SftpExtendedReplyPacket] before being sent.
|
||||||
|
abstract class SftpExtendedReply {}
|
||||||
|
|
||||||
|
/// This request correspond to the statvfs POSIX system interface.
|
||||||
|
class SftpStatVfsRequest extends SftpExtendedRequest {
|
||||||
|
SftpStatVfsRequest({required this.path});
|
||||||
|
|
||||||
|
@override
|
||||||
|
final String name = 'statvfs@openssh.com';
|
||||||
|
|
||||||
|
final String path;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeUtf8(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This request correspond to the fstatvfs POSIX system interface.
|
||||||
|
class SftpFstatVfsRequest extends SftpExtendedRequest {
|
||||||
|
SftpFstatVfsRequest({required this.handle});
|
||||||
|
|
||||||
|
@override
|
||||||
|
final String name = 'fstatvfs@openssh.com';
|
||||||
|
|
||||||
|
final Uint8List handle;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeString(handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// uint64 f_bsize /* file system block size */
|
||||||
|
/// uint64 f_frsize /* fundamental fs block size */
|
||||||
|
/// uint64 f_blocks /* number of blocks (unit f_frsize) */
|
||||||
|
/// uint64 f_bfree /* free blocks in file system */
|
||||||
|
/// uint64 f_bavail /* free blocks for non-root */
|
||||||
|
/// uint64 f_files /* total file inodes */
|
||||||
|
/// uint64 f_ffree /* free file inodes */
|
||||||
|
/// uint64 f_favail /* free file inodes for to non-root */
|
||||||
|
/// uint64 f_fsid /* file system id */
|
||||||
|
/// uint64 f_flag /* bit mask of f_flag values */
|
||||||
|
/// uint64 f_namemax /* maximum filename length */
|
||||||
|
class SftpStatVfsReply {
|
||||||
|
SftpStatVfsReply({
|
||||||
|
required this.blockSize,
|
||||||
|
required this.fundamentalBlockSize,
|
||||||
|
required this.totalBlocks,
|
||||||
|
required this.freeBlocks,
|
||||||
|
required this.freeBlocksForNonRoot,
|
||||||
|
required this.totalInodes,
|
||||||
|
required this.freeInodes,
|
||||||
|
required this.freeInodesForNonRoot,
|
||||||
|
required this.fileSystemId,
|
||||||
|
required this.flag,
|
||||||
|
required this.maximumFilenameLength,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SftpStatVfsReply.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
return SftpStatVfsReply(
|
||||||
|
blockSize: reader.readUint64(),
|
||||||
|
fundamentalBlockSize: reader.readUint64(),
|
||||||
|
totalBlocks: reader.readUint64(),
|
||||||
|
freeBlocks: reader.readUint64(),
|
||||||
|
freeBlocksForNonRoot: reader.readUint64(),
|
||||||
|
totalInodes: reader.readUint64(),
|
||||||
|
freeInodes: reader.readUint64(),
|
||||||
|
freeInodesForNonRoot: reader.readUint64(),
|
||||||
|
fileSystemId: reader.readUint64(),
|
||||||
|
flag: reader.readUint64(),
|
||||||
|
maximumFilenameLength: reader.readUint64(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// file system block size
|
||||||
|
final int blockSize;
|
||||||
|
|
||||||
|
/// fundamental fs block size
|
||||||
|
final int fundamentalBlockSize;
|
||||||
|
|
||||||
|
/// number of blocks (unit f_frsize)
|
||||||
|
final int totalBlocks;
|
||||||
|
|
||||||
|
/// free blocks in file system
|
||||||
|
final int freeBlocks;
|
||||||
|
|
||||||
|
/// free blocks for non-root
|
||||||
|
final int freeBlocksForNonRoot;
|
||||||
|
|
||||||
|
/// total file inodes
|
||||||
|
final int totalInodes;
|
||||||
|
|
||||||
|
/// free file inodes
|
||||||
|
final int freeInodes;
|
||||||
|
|
||||||
|
/// free file inodes for to non-root
|
||||||
|
final int freeInodesForNonRoot;
|
||||||
|
|
||||||
|
/// file system id
|
||||||
|
final int fileSystemId;
|
||||||
|
|
||||||
|
/// bit mask of f_flag values
|
||||||
|
final int flag;
|
||||||
|
|
||||||
|
/// maximum filename length
|
||||||
|
final int maximumFilenameLength;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class SftpRequestId {
|
||||||
|
static const max = 0xFFFFFFFF;
|
||||||
|
|
||||||
|
var _id = 0;
|
||||||
|
|
||||||
|
int get next {
|
||||||
|
return _id++ % max;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
abstract class SftpStatusCode {
|
||||||
|
/// Indicates successful completion of the operation.
|
||||||
|
static const ok = 0;
|
||||||
|
|
||||||
|
/// indicates end-of-file condition; for [SftpReadPacket] it means that no
|
||||||
|
/// more data is available in the file, and for [SftpReadDirPacket] it
|
||||||
|
/// indicates that no more files are contained in the directory.
|
||||||
|
static const eof = 1;
|
||||||
|
|
||||||
|
/// Returned when a reference is made to a file which should exist
|
||||||
|
/// but doesn't.
|
||||||
|
static const noSuchFile = 2;
|
||||||
|
|
||||||
|
/// Returned when the authenticated user does not have sufficient
|
||||||
|
/// permissions to perform the operation.
|
||||||
|
static const permissionDenied = 3;
|
||||||
|
|
||||||
|
/// A generic catch-all error message; it should be returned if an
|
||||||
|
/// error occurs for which there is no more specific error code
|
||||||
|
/// defined.
|
||||||
|
static const failure = 4;
|
||||||
|
|
||||||
|
/// may be returned if a badly formatted packet or protocol
|
||||||
|
/// incompatibility is detected.
|
||||||
|
static const badMessage = 5;
|
||||||
|
|
||||||
|
/// A pseudo-error which indicates that the client has no
|
||||||
|
/// connection to the server (it can only be generated locally by the
|
||||||
|
/// client, and MUST NOT be returned by servers).
|
||||||
|
static const noConnection = 6;
|
||||||
|
|
||||||
|
/// A pseudo-error which indicates that the connection to the
|
||||||
|
/// server has been lost (it can only be generated locally by the
|
||||||
|
/// client, and MUST NOT be returned by servers).
|
||||||
|
static const connectionLost = 7;
|
||||||
|
|
||||||
|
/// Indicates that an attempt was made to perform an operation which
|
||||||
|
/// is not supported for the server (it may be generated locally by
|
||||||
|
/// the client if e.g. the version number exchange indicates that a
|
||||||
|
/// required feature is not supported by the server, or it may be
|
||||||
|
/// returned by the server if the server does not implement an
|
||||||
|
/// operation).
|
||||||
|
static const opUnsupported = 8;
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import 'package:dartssh2/src/sftp/sftp_packet_ext.dart';
|
||||||
|
|
||||||
|
/// Information about the file system. Corresponds to the `statvfs` system call
|
||||||
|
/// on POSIX systems.
|
||||||
|
class SftpStatVfs {
|
||||||
|
SftpStatVfs({
|
||||||
|
required this.blockSize,
|
||||||
|
required this.fundamentalBlockSize,
|
||||||
|
required this.totalBlocks,
|
||||||
|
required this.freeBlocks,
|
||||||
|
required this.freeBlocksForNonRoot,
|
||||||
|
required this.totalInodes,
|
||||||
|
required this.freeInodes,
|
||||||
|
required this.freeInodesForNonRoot,
|
||||||
|
required this.fileSystemId,
|
||||||
|
required this.isReadOnly,
|
||||||
|
required this.isNoSuid,
|
||||||
|
required this.maximumFilenameLength,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SftpStatVfs.fromReply(SftpStatVfsReply reply) {
|
||||||
|
const statVfsFlagReadOnly = 0x01;
|
||||||
|
const statVfsFlagNoSuid = 0x02;
|
||||||
|
|
||||||
|
return SftpStatVfs(
|
||||||
|
blockSize: reply.blockSize,
|
||||||
|
fundamentalBlockSize: reply.fundamentalBlockSize,
|
||||||
|
totalBlocks: reply.totalBlocks,
|
||||||
|
freeBlocks: reply.freeBlocks,
|
||||||
|
freeBlocksForNonRoot: reply.freeBlocksForNonRoot,
|
||||||
|
totalInodes: reply.totalInodes,
|
||||||
|
freeInodes: reply.freeInodes,
|
||||||
|
freeInodesForNonRoot: reply.freeInodesForNonRoot,
|
||||||
|
fileSystemId: reply.fileSystemId,
|
||||||
|
isReadOnly: reply.flag & statVfsFlagReadOnly != 0,
|
||||||
|
isNoSuid: reply.flag & statVfsFlagNoSuid != 0,
|
||||||
|
maximumFilenameLength: reply.maximumFilenameLength,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// file system block size
|
||||||
|
final int blockSize;
|
||||||
|
|
||||||
|
/// fundamental fs block size
|
||||||
|
final int fundamentalBlockSize;
|
||||||
|
|
||||||
|
/// number of blocks (unit f_frsize)
|
||||||
|
final int totalBlocks;
|
||||||
|
|
||||||
|
/// free blocks in file system
|
||||||
|
final int freeBlocks;
|
||||||
|
|
||||||
|
/// free blocks for non-root
|
||||||
|
final int freeBlocksForNonRoot;
|
||||||
|
|
||||||
|
/// total file inodes
|
||||||
|
final int totalInodes;
|
||||||
|
|
||||||
|
/// free file inodes
|
||||||
|
final int freeInodes;
|
||||||
|
|
||||||
|
/// free file inodes for to non-root
|
||||||
|
final int freeInodesForNonRoot;
|
||||||
|
|
||||||
|
/// file system id
|
||||||
|
final int fileSystemId;
|
||||||
|
|
||||||
|
/// Whether the file system is read-only.
|
||||||
|
final bool isReadOnly;
|
||||||
|
|
||||||
|
/// Whether the file system supports the setuid and setgid file mode bits.
|
||||||
|
final bool isNoSuid;
|
||||||
|
|
||||||
|
/// maximum filename length
|
||||||
|
final int maximumFilenameLength;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SftpStatVfs{'
|
||||||
|
'blockSize: $blockSize, '
|
||||||
|
'fundamentalBlockSize: $fundamentalBlockSize, '
|
||||||
|
'totalBlocks: $totalBlocks, '
|
||||||
|
'freeBlocks: $freeBlocks, '
|
||||||
|
'freeBlocksForNonRoot: $freeBlocksForNonRoot, '
|
||||||
|
'totalInodes: $totalInodes, '
|
||||||
|
'freeInodes: $freeInodes, '
|
||||||
|
'freeInodesForNonRoot: $freeInodesForNonRoot, '
|
||||||
|
'fileSystemId: $fileSystemId, '
|
||||||
|
'isReadOnly: $isReadOnly, '
|
||||||
|
'isNoSuid: $isNoSuid, '
|
||||||
|
'maximumFilenameLength: $maximumFilenameLength'
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/sftp/sftp_client.dart';
|
||||||
|
import 'package:dartssh2/src/utils/stream.dart';
|
||||||
|
|
||||||
|
/// The amount of data to send in a single SFTP packet.
|
||||||
|
///
|
||||||
|
/// From the SFTP spec it's safe to send up to 32KB of data in a single packet.
|
||||||
|
/// To strike a balance between capability and performance, we choose 16KB.
|
||||||
|
const chunkSize = 16 * 1024;
|
||||||
|
|
||||||
|
/// The maximum amount of data that can be sent to the remote host without
|
||||||
|
/// receiving an acknowledgement.
|
||||||
|
const maxBytesOnTheWire = chunkSize * 64;
|
||||||
|
|
||||||
|
/// Holds the state of a streaming write operation from [stream] to [file].
|
||||||
|
class SftpFileWriter with DoneFuture {
|
||||||
|
/// The remote file to write to.
|
||||||
|
final SftpFile file;
|
||||||
|
|
||||||
|
/// The stream of data to write to [file].
|
||||||
|
final Stream<Uint8List> stream;
|
||||||
|
|
||||||
|
/// The offset in [file] to start writing to.
|
||||||
|
final int offset;
|
||||||
|
|
||||||
|
/// Called when [bytes] of data have been successfully written to [file].
|
||||||
|
final Function(int bytes)? onProgress;
|
||||||
|
|
||||||
|
/// Creates a new [SftpFileWriter]. The upload process is started immediately
|
||||||
|
/// after construction.
|
||||||
|
SftpFileWriter(this.file, this.stream, this.offset, this.onProgress) {
|
||||||
|
_subscription =
|
||||||
|
stream.transform(MaxChunkSize(chunkSize)).listen(_handleLocalData);
|
||||||
|
|
||||||
|
_subscription.onDone(_handleLocalDone);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The subscription for [stream]. We use this to pause and resume the data
|
||||||
|
/// source.
|
||||||
|
late final StreamSubscription<Uint8List> _subscription;
|
||||||
|
|
||||||
|
final _doneCompleter = Completer<void>();
|
||||||
|
|
||||||
|
/// Bytes of data that have been sent to the remote host.
|
||||||
|
var _bytesSent = 0;
|
||||||
|
|
||||||
|
/// Bytes of data that have been acknowledged by the remote host.
|
||||||
|
var _bytesAcked = 0;
|
||||||
|
|
||||||
|
/// Number of bytes sent to the server but not yet acknowledged.
|
||||||
|
///
|
||||||
|
/// This number is used to pause the stream when it gets too high.
|
||||||
|
int get _bytesOnTheWire => _bytesSent - _bytesAcked;
|
||||||
|
|
||||||
|
/// Whether [stream] has emitted all of its data.
|
||||||
|
var _streamDone = false;
|
||||||
|
|
||||||
|
/// A [Future] that completes when:
|
||||||
|
///
|
||||||
|
/// - All data from [stream] has been written to [file]
|
||||||
|
/// - Or the write operation has been aborted by calling [abort].
|
||||||
|
@override
|
||||||
|
Future<void> get done => _doneCompleter.future;
|
||||||
|
|
||||||
|
/// The number of bytes that have been successfully written to [file].
|
||||||
|
int get progress => _bytesAcked;
|
||||||
|
|
||||||
|
/// Stops [stream] from emitting more data. Returns a [Future] that completes
|
||||||
|
/// when the underlying data source of [stream] has been successfully closed.
|
||||||
|
///
|
||||||
|
/// Calling [abort] will make [done] to complete immediately.
|
||||||
|
Future<void> abort() async {
|
||||||
|
_doneCompleter.complete();
|
||||||
|
await _subscription.cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pauses [stream] from emitting more data. It's safe to call this even if
|
||||||
|
/// the stream is already paused. Use [resume] to resume the operation.
|
||||||
|
void pause() {
|
||||||
|
if (!_subscription.isPaused) {
|
||||||
|
_subscription.pause();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resumes [stream] after it has been paused. It's safe to call this even if
|
||||||
|
/// the stream is not paused. Use [pause] to pause the operation.
|
||||||
|
void resume() {
|
||||||
|
_subscription.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles the incoming data chunks from the stream.
|
||||||
|
///
|
||||||
|
/// This function manages the flow control by pausing the stream if the
|
||||||
|
/// amount of unacknowledged data (`_bytesOnTheWire`) exceeds the
|
||||||
|
/// `maxBytesOnTheWire` limit. It then writes the data chunk to the remote file
|
||||||
|
/// at the appropriate offset, updates the counters, and triggers the
|
||||||
|
/// progress callback. Finally, it checks if all data has been acknowledged
|
||||||
|
/// and completes the operation if done.
|
||||||
|
Future<void> _handleLocalData(Uint8List chunk) async {
|
||||||
|
if (_bytesOnTheWire >= maxBytesOnTheWire) {
|
||||||
|
_subscription.pause();
|
||||||
|
} else {
|
||||||
|
_subscription.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
final chunkWriteOffset = offset + _bytesSent;
|
||||||
|
_bytesSent += chunk.length;
|
||||||
|
await file.writeBytes(chunk, offset: chunkWriteOffset);
|
||||||
|
|
||||||
|
_bytesAcked += chunk.length;
|
||||||
|
onProgress?.call(_bytesAcked);
|
||||||
|
|
||||||
|
if (_bytesOnTheWire < maxBytesOnTheWire) {
|
||||||
|
_subscription.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_streamDone &&
|
||||||
|
_bytesSent == _bytesAcked &&
|
||||||
|
!_doneCompleter.isCompleted) {
|
||||||
|
_doneCompleter.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles the completion of the data stream.
|
||||||
|
///
|
||||||
|
/// This function is triggered when the stream has finished emitting all its
|
||||||
|
/// data. It checks if all data has been successfully acknowledged and
|
||||||
|
/// marks the operation as complete by calling `_doneCompleter.complete()`
|
||||||
|
/// if no more data remains to be processed.
|
||||||
|
void _handleLocalDone() {
|
||||||
|
_streamDone = true;
|
||||||
|
if (_bytesSent == _bytesAcked) {
|
||||||
|
_doneCompleter.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implements [Future] interface for [SftpFileWriter].
|
||||||
|
///
|
||||||
|
/// This is for compatibility with earlier versions of dartssh2 and dartssh2.
|
||||||
|
mixin DoneFuture implements Future {
|
||||||
|
Future<void> get done;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<void> asStream() => done.asStream();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> catchError(
|
||||||
|
Function onError, {
|
||||||
|
bool Function(Object error)? test,
|
||||||
|
}) =>
|
||||||
|
done.catchError(onError, test: test);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<S> then<S>(FutureOr<S> Function(void) onValue, {Function? onError}) =>
|
||||||
|
done.then(onValue, onError: onError);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> whenComplete(FutureOr Function() action) =>
|
||||||
|
done.whenComplete(action);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> timeout(
|
||||||
|
Duration timeLimit, {
|
||||||
|
FutureOr<void> Function()? onTimeout,
|
||||||
|
}) =>
|
||||||
|
done.timeout(timeLimit, onTimeout: onTimeout);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/socket/ssh_socket_io.dart'
|
||||||
|
if (dart.library.js) 'package:dartssh2/src/socket/ssh_socket_js.dart';
|
||||||
|
|
||||||
|
abstract class SSHSocket {
|
||||||
|
static Future<SSHSocket> connect(
|
||||||
|
String host,
|
||||||
|
int port, {
|
||||||
|
Duration? timeout,
|
||||||
|
}) async {
|
||||||
|
return await connectNativeSocket(host, port, timeout: timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream<Uint8List> get stream;
|
||||||
|
|
||||||
|
StreamSink<List<int>> get sink;
|
||||||
|
|
||||||
|
/// A future that will complete when the consumer closes, or when an error occurs.
|
||||||
|
Future<void> get done;
|
||||||
|
|
||||||
|
/// Closes the socket, returning the same future as [done].
|
||||||
|
Future<void> close();
|
||||||
|
|
||||||
|
void destroy();
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/socket/ssh_socket.dart';
|
||||||
|
|
||||||
|
Future<SSHSocket> connectNativeSocket(
|
||||||
|
String host,
|
||||||
|
int port, {
|
||||||
|
Duration? timeout,
|
||||||
|
}) async {
|
||||||
|
final socket = await Socket.connect(host, port, timeout: timeout);
|
||||||
|
return _SSHNativeSocket._(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SSHNativeSocket implements SSHSocket {
|
||||||
|
final Socket _socket;
|
||||||
|
|
||||||
|
_SSHNativeSocket._(this._socket);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Uint8List> get stream => _socket;
|
||||||
|
|
||||||
|
@override
|
||||||
|
StreamSink<List<int>> get sink => _socket;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {
|
||||||
|
await _socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> get done => _socket.done;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void destroy() {
|
||||||
|
_socket.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
final address = '${_socket.remoteAddress.host}:${_socket.remotePort}';
|
||||||
|
return '_SSHNativeSocket($address)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import 'package:dartssh2/src/socket/ssh_socket.dart';
|
||||||
|
|
||||||
|
Future<SSHSocket> connectNativeSocket(
|
||||||
|
String host,
|
||||||
|
int port, {
|
||||||
|
Duration? timeout,
|
||||||
|
}) async {
|
||||||
|
throw UnimplementedError(
|
||||||
|
'Native socket is not supported on web. '
|
||||||
|
'To use dartssh2 in browser, you have to bring your own implementation '
|
||||||
|
'of SSHSocket.',
|
||||||
|
);
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
import 'package:dartssh2/src/algorithm/ssh_cipher_type.dart';
|
||||||
|
import 'package:dartssh2/src/algorithm/ssh_hostkey_type.dart';
|
||||||
|
import 'package:dartssh2/src/algorithm/ssh_kex_type.dart';
|
||||||
|
import 'package:dartssh2/src/algorithm/ssh_mac_type.dart';
|
||||||
|
|
||||||
|
abstract class SSHAlgorithm {
|
||||||
|
/// The name of the algorithm.
|
||||||
|
String get name;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($name)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHAlgorithmList<T extends SSHAlgorithm> on List<T> {
|
||||||
|
List<String> toNameList() {
|
||||||
|
return map((algorithm) => algorithm.name).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
T? getByName(String name) {
|
||||||
|
for (var algorithm in this) {
|
||||||
|
if (algorithm.name == name) {
|
||||||
|
return algorithm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHAlgorithms {
|
||||||
|
/// Algorithm used for the key exchange.
|
||||||
|
final List<SSHKexType> kex;
|
||||||
|
|
||||||
|
/// Algorithm used for the host key.
|
||||||
|
final List<SSHHostkeyType> hostkey;
|
||||||
|
|
||||||
|
/// Algorithm used for the encryption.
|
||||||
|
final List<SSHCipherType> cipher;
|
||||||
|
|
||||||
|
/// Algorithm used for the authentication.
|
||||||
|
final List<SSHMacType> mac;
|
||||||
|
|
||||||
|
const SSHAlgorithms({
|
||||||
|
this.kex = const [
|
||||||
|
SSHKexType.x25519,
|
||||||
|
SSHKexType.nistp521,
|
||||||
|
SSHKexType.nistp384,
|
||||||
|
SSHKexType.nistp256,
|
||||||
|
SSHKexType.dhGexSha256,
|
||||||
|
SSHKexType.dh14Sha256,
|
||||||
|
SSHKexType.dh14Sha1,
|
||||||
|
SSHKexType.dhGexSha1,
|
||||||
|
SSHKexType.dh1Sha1,
|
||||||
|
],
|
||||||
|
this.hostkey = const [
|
||||||
|
SSHHostkeyType.ed25519,
|
||||||
|
SSHHostkeyType.rsaSha512,
|
||||||
|
SSHHostkeyType.rsaSha256,
|
||||||
|
SSHHostkeyType.rsaSha1,
|
||||||
|
SSHHostkeyType.ecdsa521,
|
||||||
|
SSHHostkeyType.ecdsa384,
|
||||||
|
SSHHostkeyType.ecdsa256,
|
||||||
|
],
|
||||||
|
this.cipher = const [
|
||||||
|
SSHCipherType.aes128ctr,
|
||||||
|
SSHCipherType.aes128cbc,
|
||||||
|
SSHCipherType.aes256ctr,
|
||||||
|
SSHCipherType.aes256cbc,
|
||||||
|
],
|
||||||
|
this.mac = const [
|
||||||
|
SSHMacType.hmacSha1,
|
||||||
|
SSHMacType.hmacSha256,
|
||||||
|
SSHMacType.hmacSha512,
|
||||||
|
SSHMacType.hmacMd5,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
+526
@@ -0,0 +1,526 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_channel_id.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_transport.dart';
|
||||||
|
import 'package:dartssh2/src/utils/async_queue.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_channel.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:dartssh2/src/utils/stream.dart';
|
||||||
|
|
||||||
|
/// Handler of channel requests. Return true if the request was handled, false
|
||||||
|
/// if the request was not recognized or could not be handled.
|
||||||
|
typedef SSHChannelRequestHandler = bool Function(
|
||||||
|
SSH_Message_Channel_Request request,
|
||||||
|
);
|
||||||
|
|
||||||
|
class SSHChannelController {
|
||||||
|
final int localId;
|
||||||
|
final int localMaximumPacketSize;
|
||||||
|
final int localInitialWindowSize;
|
||||||
|
|
||||||
|
final int remoteId;
|
||||||
|
final int remoteMaximumPacketSize;
|
||||||
|
final int remoteInitialWindowSize;
|
||||||
|
|
||||||
|
final SSHPrintHandler? printDebug;
|
||||||
|
|
||||||
|
final void Function(SSHMessage) sendMessage;
|
||||||
|
|
||||||
|
SSHChannel get channel => SSHChannel(this);
|
||||||
|
|
||||||
|
SSHChannelController({
|
||||||
|
required this.localId,
|
||||||
|
required this.localMaximumPacketSize,
|
||||||
|
required this.localInitialWindowSize,
|
||||||
|
required this.remoteId,
|
||||||
|
required this.remoteInitialWindowSize,
|
||||||
|
required this.remoteMaximumPacketSize,
|
||||||
|
required this.sendMessage,
|
||||||
|
this.printDebug,
|
||||||
|
}) {
|
||||||
|
if (remoteInitialWindowSize > 0) {
|
||||||
|
_uploadLoop.activate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remaining local receive window size.
|
||||||
|
late var _localWindow = localInitialWindowSize;
|
||||||
|
|
||||||
|
/// Remaining remote receive window size.
|
||||||
|
late var _remoteWindow = remoteInitialWindowSize;
|
||||||
|
|
||||||
|
/// A [StreamController] that receives data from the remote side.
|
||||||
|
late final _remoteStream = StreamController<SSHChannelData>(
|
||||||
|
onResume: _sendWindowAdjustIfNeeded,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// A [StreamController] that accepts data from local end of the channel.
|
||||||
|
final _localStream = StreamController<SSHChannelData>();
|
||||||
|
|
||||||
|
late final _locaStreamConsumer = SSHChannelDataConsumer(_localStream.stream);
|
||||||
|
|
||||||
|
/// Handler of channel requests from the remote side.
|
||||||
|
late var _requestHandler = _defaultRequestHandler;
|
||||||
|
|
||||||
|
/// An [AsyncQueue] of pending request replies from the remote side.
|
||||||
|
final _requestReplyQueue = AsyncQueue<bool>();
|
||||||
|
|
||||||
|
/// true if we have sent an EOF message to the remote side.
|
||||||
|
var _hasSentEOF = false;
|
||||||
|
|
||||||
|
/// true if we have sent an close message to the remote side.
|
||||||
|
var _hasSentClose = false;
|
||||||
|
|
||||||
|
final _done = Completer<void>();
|
||||||
|
|
||||||
|
Future<bool> sendExec(String command) async {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.exec(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
wantReply: true,
|
||||||
|
command: command,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return await _requestReplyQueue.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> sendPtyReq({
|
||||||
|
String terminalType = 'xterm-256color',
|
||||||
|
int terminalWidth = 80,
|
||||||
|
int terminalHeight = 25,
|
||||||
|
int terminalPixelWidth = 0,
|
||||||
|
int terminalPixelHeight = 0,
|
||||||
|
Uint8List? terminalModes,
|
||||||
|
}) async {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.pty(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
termType: terminalType,
|
||||||
|
termWidth: terminalWidth,
|
||||||
|
termHeight: terminalHeight,
|
||||||
|
termPixelWidth: terminalPixelWidth,
|
||||||
|
termPixelHeight: terminalPixelHeight,
|
||||||
|
termModes: terminalModes ?? Uint8List(0),
|
||||||
|
wantReply: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return await _requestReplyQueue.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> sendShell() async {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.shell(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
wantReply: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return await _requestReplyQueue.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> sendSubsystem(String subsystem) async {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.subsystem(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
subsystemName: subsystem,
|
||||||
|
wantReply: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return await _requestReplyQueue.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendEnv(String name, String value) {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.env(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
variableName: name,
|
||||||
|
variableValue: value,
|
||||||
|
wantReply: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendSignal(String signal) {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.signal(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
signalName: signal,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendTerminalWindowChange({
|
||||||
|
required int width,
|
||||||
|
required int height,
|
||||||
|
required int pixelWidth,
|
||||||
|
required int pixelHeight,
|
||||||
|
}) {
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Request.windowChange(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
termWidth: width,
|
||||||
|
termHeight: height,
|
||||||
|
termPixelWidth: pixelWidth,
|
||||||
|
termPixelHeight: pixelHeight,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleMessage(SSHMessage message) {
|
||||||
|
if (message is SSH_Message_Channel_Data) {
|
||||||
|
_handleDataMessage(message.data);
|
||||||
|
} else if (message is SSH_Message_Channel_Extended_Data) {
|
||||||
|
_handleDataMessage(message.data, type: message.dataTypeCode);
|
||||||
|
} else if (message is SSH_Message_Channel_Window_Adjust) {
|
||||||
|
_handleWindowAdjustMessage(message.bytesToAdd);
|
||||||
|
} else if (message is SSH_Message_Channel_EOF) {
|
||||||
|
_handleEOFMessage();
|
||||||
|
} else if (message is SSH_Message_Channel_Close) {
|
||||||
|
_handleCloseMessage();
|
||||||
|
} else if (message is SSH_Message_Channel_Request) {
|
||||||
|
_handleRequestMessage(message);
|
||||||
|
} else if (message is SSH_Message_Channel_Success) {
|
||||||
|
_handleRequestSuccessMessage();
|
||||||
|
} else if (message is SSH_Message_Channel_Failure) {
|
||||||
|
_handleRequestFailureMessage();
|
||||||
|
} else {
|
||||||
|
throw UnimplementedError('Unimplemented message: $message');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes our side of the channel. Returns a [Future] that completes when
|
||||||
|
/// the remote side has closed the channel.
|
||||||
|
Future<void> close() async {
|
||||||
|
if (_done.isCompleted) return;
|
||||||
|
|
||||||
|
_locaStreamConsumer.cancel();
|
||||||
|
_sendEOFIfNeeded();
|
||||||
|
|
||||||
|
if (_remoteStream.isClosed) {
|
||||||
|
_sendCloseIfNeeded();
|
||||||
|
_done.complete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
return _done.future;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the channel immediately in both directions. This may send a close
|
||||||
|
/// message to the remote side. After this no more data can be sent or
|
||||||
|
/// received.
|
||||||
|
void destroy() {
|
||||||
|
if (_done.isCompleted) return;
|
||||||
|
_remoteStream.close();
|
||||||
|
_locaStreamConsumer.cancel();
|
||||||
|
_sendEOFIfNeeded();
|
||||||
|
_sendCloseIfNeeded();
|
||||||
|
_done.complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleWindowAdjustMessage(int bytesToAdd) {
|
||||||
|
printDebug?.call('SSHChannel._handleWindowAdjustMessage: $bytesToAdd');
|
||||||
|
|
||||||
|
if (bytesToAdd < 0) {
|
||||||
|
throw ArgumentError.value(bytesToAdd, 'bytesToAdd', 'must be positive');
|
||||||
|
}
|
||||||
|
|
||||||
|
_remoteWindow += bytesToAdd;
|
||||||
|
|
||||||
|
if (_remoteWindow > 0) {
|
||||||
|
_uploadLoop.activate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleDataMessage(Uint8List data, {int? type}) {
|
||||||
|
printDebug?.call('SSHChannel._handleDataMessage: len=${data.length}');
|
||||||
|
|
||||||
|
if (_remoteStream.isClosed) {
|
||||||
|
printDebug?.call('SSHChannel._handleDataMessage: remote already closed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_remoteStream.add(SSHChannelData(data, type: type));
|
||||||
|
|
||||||
|
_localWindow -= data.length;
|
||||||
|
if (_localWindow < 0) {
|
||||||
|
// Maybe we should close the channel here?
|
||||||
|
}
|
||||||
|
|
||||||
|
_sendWindowAdjustIfNeeded();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleRequestMessage(SSH_Message_Channel_Request request) {
|
||||||
|
printDebug?.call('SSHChannel._handleRequest: ${request.requestType}');
|
||||||
|
|
||||||
|
final success = _requestHandler(request);
|
||||||
|
if (!request.wantReply) return;
|
||||||
|
success ? _sendRequestSuccess() : _sendRequestFailure();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleRequestSuccessMessage() {
|
||||||
|
printDebug?.call('SSHChannel._handleRequestSuccessMessage');
|
||||||
|
_requestReplyQueue.add(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleRequestFailureMessage() {
|
||||||
|
printDebug?.call('SSHChannel._handleRequestFailureMessage');
|
||||||
|
_requestReplyQueue.add(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleEOFMessage() {
|
||||||
|
printDebug?.call('SSHChannel._handleEOFMessage');
|
||||||
|
_remoteStream.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleCloseMessage() {
|
||||||
|
printDebug?.call('SSHChannel._handleCLoseMessage');
|
||||||
|
_remoteStream.close();
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _defaultRequestHandler(SSH_Message_Channel_Request request) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendEOFIfNeeded() {
|
||||||
|
printDebug?.call('SSHChannel._sendEOFIfNeeded');
|
||||||
|
if (_done.isCompleted) return;
|
||||||
|
if (_hasSentEOF) return;
|
||||||
|
_hasSentEOF = true;
|
||||||
|
sendMessage(SSH_Message_Channel_EOF(recipientChannel: remoteId));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendCloseIfNeeded() {
|
||||||
|
printDebug?.call('SSHChannel._sendCloseIfNeeded');
|
||||||
|
if (_done.isCompleted) return;
|
||||||
|
if (_hasSentClose) return;
|
||||||
|
_hasSentClose = true;
|
||||||
|
sendMessage(SSH_Message_Channel_Close(recipientChannel: remoteId));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendRequestSuccess() {
|
||||||
|
printDebug?.call('SSHChannel._sendRequestSuccess');
|
||||||
|
sendMessage(SSH_Message_Channel_Success(recipientChannel: remoteId));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendRequestFailure() {
|
||||||
|
printDebug?.call('SSHChannel._sendRequestFailure');
|
||||||
|
sendMessage(SSH_Message_Channel_Failure(recipientChannel: remoteId));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendWindowAdjustIfNeeded() {
|
||||||
|
printDebug?.call('SSHChannel._sendWindowAdjustIfNeeded');
|
||||||
|
|
||||||
|
if (_done.isCompleted) return;
|
||||||
|
if (_remoteStream.isPaused) return;
|
||||||
|
if (_localWindow <= 0) return;
|
||||||
|
|
||||||
|
final bytesToAdd = localInitialWindowSize - _localWindow;
|
||||||
|
_localWindow = localInitialWindowSize;
|
||||||
|
|
||||||
|
sendMessage(
|
||||||
|
SSH_Message_Channel_Window_Adjust(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
bytesToAdd: bytesToAdd,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
late final _uploadLoop = OnceSimultaneously(() async {
|
||||||
|
while (true) {
|
||||||
|
if (_remoteWindow <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final dataToRead = min(_remoteWindow, remoteMaximumPacketSize);
|
||||||
|
final data = await _locaStreamConsumer.read(dataToRead);
|
||||||
|
|
||||||
|
if (data == null) {
|
||||||
|
_sendEOFIfNeeded();
|
||||||
|
|
||||||
|
if (_remoteStream.isClosed) {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_hasSentEOF) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
printDebug?.call('SSHChannel._uploadLoop: len=${data.bytes.length}');
|
||||||
|
|
||||||
|
final message = data.isExtendedData
|
||||||
|
? SSH_Message_Channel_Extended_Data(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
dataTypeCode: data.type!,
|
||||||
|
data: data.bytes,
|
||||||
|
)
|
||||||
|
: SSH_Message_Channel_Data(
|
||||||
|
recipientChannel: remoteId,
|
||||||
|
data: data.bytes,
|
||||||
|
);
|
||||||
|
|
||||||
|
sendMessage(message);
|
||||||
|
|
||||||
|
_remoteWindow -= data.bytes.length;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChannel {
|
||||||
|
/// The channel id on the local side.
|
||||||
|
SSHChannelId get channelId => _controller.localId;
|
||||||
|
|
||||||
|
/// The channel id on the remote side.
|
||||||
|
SSHChannelId get remoteChannelId => _controller.localId;
|
||||||
|
|
||||||
|
/// The maximum packet size that the remote side can receive.
|
||||||
|
int get maximumPacketSize => _controller.remoteMaximumPacketSize;
|
||||||
|
|
||||||
|
/// A [Stream] of data received from the remote side.
|
||||||
|
Stream<SSHChannelData> get stream => _controller._remoteStream.stream;
|
||||||
|
|
||||||
|
/// A [StreamSink] that sends data to the remote side. Chucks must be
|
||||||
|
/// equal to or less than [maximumPacketSize].
|
||||||
|
StreamSink<SSHChannelData> get sink => _controller._localStream.sink;
|
||||||
|
|
||||||
|
Future<void> get done => _controller._done.future;
|
||||||
|
|
||||||
|
SSHChannel(this._controller);
|
||||||
|
|
||||||
|
final SSHChannelController _controller;
|
||||||
|
|
||||||
|
/// Send data to the remote side.
|
||||||
|
void addData(Uint8List data, {int? type}) {
|
||||||
|
sink.add(SSHChannelData(data, type: type));
|
||||||
|
}
|
||||||
|
|
||||||
|
void setRequestHandler(SSHChannelRequestHandler handler) {
|
||||||
|
_controller._requestHandler = handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> sendExec(String command) async {
|
||||||
|
return await _controller.sendExec(command);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> sendShell() async {
|
||||||
|
return await _controller.sendShell();
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendTerminalWindowChange({
|
||||||
|
required int width,
|
||||||
|
required int height,
|
||||||
|
int pixelWidth = 0,
|
||||||
|
int pixelHeight = 0,
|
||||||
|
}) {
|
||||||
|
_controller.sendTerminalWindowChange(
|
||||||
|
width: width,
|
||||||
|
height: height,
|
||||||
|
pixelWidth: pixelWidth,
|
||||||
|
pixelHeight: pixelHeight,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendSignal(String signal) {
|
||||||
|
_controller.sendSignal(signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes our side of the channel. Returns a [Future] that completes when
|
||||||
|
/// both sides of the channel are closed.
|
||||||
|
Future<void> close() => _controller.close();
|
||||||
|
|
||||||
|
/// Destroys the channel in both directions. After calling this method,
|
||||||
|
/// no more data can be sent or received.
|
||||||
|
void destroy() => _controller.destroy();
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'SSHChannel($channelId:$remoteChannelId)';
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChannelData {
|
||||||
|
/// Type of the data. Not null if the data is extended data. See: [SSHChannelExtendedDataType]
|
||||||
|
final int? type;
|
||||||
|
|
||||||
|
final Uint8List bytes;
|
||||||
|
|
||||||
|
bool get isExtendedData => type != null;
|
||||||
|
|
||||||
|
SSHChannelData(this.bytes, {this.type});
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChannelExtendedDataType {
|
||||||
|
static const stderr = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChannelDataSplitter
|
||||||
|
extends StreamTransformerBase<SSHChannelData, SSHChannelData> {
|
||||||
|
SSHChannelDataSplitter(this.maxSize);
|
||||||
|
|
||||||
|
final int maxSize;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<SSHChannelData> bind(Stream<SSHChannelData> stream) async* {
|
||||||
|
await for (var chunk in stream) {
|
||||||
|
if (chunk.bytes.length < maxSize) {
|
||||||
|
yield chunk;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
final blocks = chunk.bytes.length ~/ maxSize;
|
||||||
|
|
||||||
|
for (var i = 0; i < blocks; i++) {
|
||||||
|
yield SSHChannelData(
|
||||||
|
Uint8List.sublistView(chunk.bytes, i * maxSize, (i + 1) * maxSize),
|
||||||
|
type: chunk.type,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (blocks * maxSize < chunk.bytes.length) {
|
||||||
|
yield SSHChannelData(
|
||||||
|
Uint8List.sublistView(chunk.bytes, blocks * maxSize),
|
||||||
|
type: chunk.type,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChannelDataConsumer extends StreamConsumerBase<SSHChannelData> {
|
||||||
|
SSHChannelDataConsumer(super.stream);
|
||||||
|
|
||||||
|
@override
|
||||||
|
int getLength(SSHChannelData chunk) {
|
||||||
|
return chunk.bytes.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHChannelData getSublistView(SSHChannelData chunk, int start, int end) {
|
||||||
|
return SSHChannelData(
|
||||||
|
Uint8List.sublistView(chunk.bytes, start, end),
|
||||||
|
type: chunk.type,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A function that can be invoked at most once simultaneously.
|
||||||
|
class OnceSimultaneously {
|
||||||
|
OnceSimultaneously(this._fn);
|
||||||
|
|
||||||
|
final Future Function() _fn;
|
||||||
|
|
||||||
|
var _isRunning = false;
|
||||||
|
|
||||||
|
/// Call the function. If the function is already running, this is a no-op.
|
||||||
|
void activate() async {
|
||||||
|
if (_isRunning) return;
|
||||||
|
_isRunning = true;
|
||||||
|
try {
|
||||||
|
await _fn();
|
||||||
|
} finally {
|
||||||
|
_isRunning = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
typedef SSHChannelId = int;
|
||||||
|
|
||||||
|
class SSHChannelIdAllocator {
|
||||||
|
SSHChannelIdAllocator();
|
||||||
|
|
||||||
|
static const _maxId = 0xFFFF;
|
||||||
|
|
||||||
|
var _nextId = 0;
|
||||||
|
|
||||||
|
final _allocated = <SSHChannelId>{};
|
||||||
|
|
||||||
|
/// Allocates a new channel id. Throw [StateError] if no more channel ids are
|
||||||
|
/// available.
|
||||||
|
SSHChannelId allocate() {
|
||||||
|
if (_allocated.length >= _maxId) {
|
||||||
|
throw Exception('No more channel ids available');
|
||||||
|
}
|
||||||
|
while (_allocated.contains(_nextId)) {
|
||||||
|
_nextId++;
|
||||||
|
if (_nextId > _maxId) {
|
||||||
|
_nextId = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_allocated.add(_nextId);
|
||||||
|
return _nextId++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases [id]. After this call, [id] can be allocated again.
|
||||||
|
void release(SSHChannelId id) {
|
||||||
|
_allocated.remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1025
File diff suppressed because it is too large.
Load diff
+132
@@ -0,0 +1,132 @@
|
|||||||
|
/// Interface for all the exceptions thrown by the library.
|
||||||
|
abstract class SSHError {}
|
||||||
|
|
||||||
|
/// Errors with a message.
|
||||||
|
mixin SSHMessageError {
|
||||||
|
String get message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($message)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that are not expected to occur. Most of the time, these are caused
|
||||||
|
/// by bugs in the library.
|
||||||
|
class SSHInternalError implements SSHError {
|
||||||
|
final Object error;
|
||||||
|
|
||||||
|
SSHInternalError(this.error);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($error)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to connect to handshake.
|
||||||
|
class SSHHandshakeError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHHandshakeError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to authenticate.
|
||||||
|
abstract class SSHAuthError with SSHMessageError implements SSHError {}
|
||||||
|
|
||||||
|
/// Errors that happen when the library tried all the authentication methods
|
||||||
|
/// and failed to authenticate.
|
||||||
|
class SSHAuthFailError with SSHMessageError implements SSHAuthError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHAuthFailError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the authentication failed due to other reasons.
|
||||||
|
/// For example network errors.
|
||||||
|
class SSHAuthAbortError with SSHMessageError implements SSHAuthError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHAuthAbortError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library receives an malformed packet.
|
||||||
|
class SSHPacketError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHPacketError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library receives an unexpected packet.
|
||||||
|
class SSHStateError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHStateError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to decode a key.
|
||||||
|
class SSHKeyDecodeError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
final Object? error;
|
||||||
|
|
||||||
|
SSHKeyDecodeError(this.message, [this.error]);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($message, $error)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to decrypt the host key.
|
||||||
|
class SSHKeyDecryptError extends SSHKeyDecodeError {
|
||||||
|
SSHKeyDecryptError(super.message, [super.error]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to open a channel.
|
||||||
|
class SSHChannelOpenError implements SSHError {
|
||||||
|
final int code;
|
||||||
|
|
||||||
|
final String description;
|
||||||
|
|
||||||
|
SSHChannelOpenError(this.code, this.description);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($code: $description)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to send a channel request.
|
||||||
|
class SSHChannelRequestError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHChannelRequestError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors that happen when the library fails to verify the host key.
|
||||||
|
class SSHHostkeyError with SSHMessageError implements SSHError {
|
||||||
|
@override
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
SSHHostkeyError(this.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors related to the underlying socket.
|
||||||
|
class SSHSocketError implements SSHError {
|
||||||
|
final Object error;
|
||||||
|
|
||||||
|
SSHSocketError(this.error);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHSocketError($error)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/socket/ssh_socket.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_channel.dart';
|
||||||
|
|
||||||
|
class SSHForwardChannel implements SSHSocket {
|
||||||
|
final SSHChannel _channel;
|
||||||
|
|
||||||
|
SSHForwardChannel(this._channel) {
|
||||||
|
_sinkController.stream
|
||||||
|
.map((data) => data is Uint8List ? data : Uint8List.fromList(data))
|
||||||
|
.map((data) => SSHChannelData(data))
|
||||||
|
.pipe(_channel.sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
final _sinkController = StreamController<List<int>>();
|
||||||
|
|
||||||
|
/// Data received from the remote host.
|
||||||
|
@override
|
||||||
|
Stream<Uint8List> get stream => _channel.stream.map((data) => data.bytes);
|
||||||
|
|
||||||
|
/// Write to this sink to send data to the remote host.
|
||||||
|
@override
|
||||||
|
StreamSink<List<int>> get sink => _sinkController.sink;
|
||||||
|
|
||||||
|
/// Close our end of the channel. Returns a future that waits for the
|
||||||
|
/// other side to close.
|
||||||
|
@override
|
||||||
|
Future<void> close() => _channel.close();
|
||||||
|
|
||||||
|
/// A future that completes when both ends of the channel are closed.
|
||||||
|
@override
|
||||||
|
Future<void> get done => _channel.done;
|
||||||
|
|
||||||
|
/// Destroys the socket in both directions.
|
||||||
|
@override
|
||||||
|
void destroy() {
|
||||||
|
_channel.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
|
||||||
|
abstract class SSHHostKey {
|
||||||
|
/// Encode the host key to SSH encoded data.
|
||||||
|
Uint8List encode();
|
||||||
|
|
||||||
|
static String getType(Uint8List encodedHostKey) {
|
||||||
|
if (encodedHostKey.length < 4) {
|
||||||
|
throw ArgumentError('Invalid encoded host key');
|
||||||
|
}
|
||||||
|
final reader = SSHMessageReader(encodedHostKey);
|
||||||
|
return reader.readUtf8();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class SSHSignature {
|
||||||
|
/// Encode the host key to SSH encoded data.
|
||||||
|
Uint8List encode();
|
||||||
|
|
||||||
|
static String getType(Uint8List encodedHostKey) {
|
||||||
|
if (encodedHostKey.length < 4) {
|
||||||
|
throw ArgumentError('Invalid encoded host key');
|
||||||
|
}
|
||||||
|
final reader = SSHMessageReader(encodedHostKey);
|
||||||
|
return reader.readUtf8();
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
/// A wrapper around [Timer] that calls [ping] every [interval], and can be
|
||||||
|
/// started or stopped idempotently.
|
||||||
|
class SSHKeepAlive {
|
||||||
|
Timer? _timer;
|
||||||
|
|
||||||
|
final Duration interval;
|
||||||
|
|
||||||
|
final Future Function() ping;
|
||||||
|
|
||||||
|
SSHKeepAlive({
|
||||||
|
required this.ping,
|
||||||
|
this.interval = const Duration(seconds: 10),
|
||||||
|
});
|
||||||
|
|
||||||
|
void start() {
|
||||||
|
_timer ??= Timer.periodic(interval, (timer) async {
|
||||||
|
await ping();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void stop() {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
/// Interface for a class that implements key exchange logic.
|
||||||
|
abstract class SSHKex {}
|
||||||
|
|
||||||
|
/// Interface for a class that implements ECDH key exchange.
|
||||||
|
abstract class SSHKexECDH implements SSHKex {
|
||||||
|
/// Public key computed from the private key.
|
||||||
|
Uint8List get publicKey;
|
||||||
|
|
||||||
|
BigInt computeSecret(Uint8List remotePublicKey);
|
||||||
|
}
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/kex/kex_dh.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
abstract class SSHKexUtils {
|
||||||
|
/// The first algorithm on the client's name-list and is also supported by the
|
||||||
|
/// server must be chosen. (rfc4253, section 7.1)
|
||||||
|
static T? selectAlgorithm<T extends SSHAlgorithm>({
|
||||||
|
required List<T> localAlgorithms,
|
||||||
|
required List<String> remoteAlgorithms,
|
||||||
|
required bool isServer,
|
||||||
|
}) {
|
||||||
|
if (isServer) {
|
||||||
|
for (final clientAlgorithm in remoteAlgorithms) {
|
||||||
|
final serverAlgorithm = localAlgorithms.getByName(clientAlgorithm);
|
||||||
|
if (serverAlgorithm != null) {
|
||||||
|
return serverAlgorithm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (final clientAlgorithm in localAlgorithms) {
|
||||||
|
if (remoteAlgorithms.contains(clientAlgorithm.name)) {
|
||||||
|
return clientAlgorithm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Uint8List computeExchangeHash({
|
||||||
|
required Digest digest,
|
||||||
|
SSHKexDH? groupExchange,
|
||||||
|
required String clientVersion,
|
||||||
|
required String serverVersion,
|
||||||
|
required Uint8List clientKexInit,
|
||||||
|
required Uint8List serverKexInit,
|
||||||
|
required Uint8List hostKey,
|
||||||
|
required Uint8List clientPublicKey,
|
||||||
|
required Uint8List serverPublicKey,
|
||||||
|
required BigInt sharedSecret,
|
||||||
|
}) {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeUtf8(clientVersion);
|
||||||
|
writer.writeUtf8(serverVersion);
|
||||||
|
writer.writeString(clientKexInit);
|
||||||
|
writer.writeString(serverKexInit);
|
||||||
|
writer.writeString(hostKey);
|
||||||
|
|
||||||
|
if (groupExchange != null) {
|
||||||
|
writer.writeUint32(SSHKexDH.gexMin);
|
||||||
|
writer.writeUint32(SSHKexDH.gexPref);
|
||||||
|
writer.writeUint32(SSHKexDH.gexMax);
|
||||||
|
writer.writeMpint(groupExchange.p);
|
||||||
|
writer.writeMpint(groupExchange.g);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.writeString(clientPublicKey);
|
||||||
|
writer.writeString(serverPublicKey);
|
||||||
|
writer.writeMpint(sharedSecret);
|
||||||
|
|
||||||
|
final message = writer.takeBytes();
|
||||||
|
digest.update(message, 0, message.length);
|
||||||
|
final result = Uint8List(digest.digestSize);
|
||||||
|
digest.doFinal(result, 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive various keys from the exchange hash.
|
||||||
|
static Uint8List deriveKey({
|
||||||
|
required Digest digest,
|
||||||
|
required BigInt sharedSecret,
|
||||||
|
required Uint8List exchangeHash,
|
||||||
|
required SSHDeriveKeyType keyType,
|
||||||
|
required Uint8List sessionId,
|
||||||
|
required int keySize,
|
||||||
|
}) {
|
||||||
|
final result = BytesBuilder(copy: false);
|
||||||
|
|
||||||
|
while (result.length < keySize) {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeMpint(sharedSecret);
|
||||||
|
writer.writeBytes(exchangeHash);
|
||||||
|
if (result.isEmpty) {
|
||||||
|
writer.writeUint8(keyType.magicChar);
|
||||||
|
writer.writeBytes(sessionId);
|
||||||
|
} else {
|
||||||
|
writer.writeBytes(result.toBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
final dataToHash = writer.takeBytes();
|
||||||
|
// final digester = SHA256Digest();
|
||||||
|
digest.update(dataToHash, 0, dataToHash.length);
|
||||||
|
final hash = Uint8List(digest.digestSize);
|
||||||
|
digest.doFinal(hash, 0);
|
||||||
|
result.add(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Uint8List.sublistView(result.takeBytes(), 0, keySize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SSHDeriveKeyType {
|
||||||
|
clientIV,
|
||||||
|
serverIV,
|
||||||
|
clientKey,
|
||||||
|
serverKey,
|
||||||
|
clientMacKey,
|
||||||
|
serverMacKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHDeriveKeyTypeX on SSHDeriveKeyType {
|
||||||
|
/// The magic character used in ke derivation.
|
||||||
|
int get magicChar {
|
||||||
|
switch (this) {
|
||||||
|
case SSHDeriveKeyType.clientIV:
|
||||||
|
return 'A'.codeUnits.first;
|
||||||
|
case SSHDeriveKeyType.serverIV:
|
||||||
|
return 'B'.codeUnits.first;
|
||||||
|
case SSHDeriveKeyType.clientKey:
|
||||||
|
return 'C'.codeUnits.first;
|
||||||
|
case SSHDeriveKeyType.serverKey:
|
||||||
|
return 'D'.codeUnits.first;
|
||||||
|
case SSHDeriveKeyType.clientMacKey:
|
||||||
|
return 'E'.codeUnits.first;
|
||||||
|
case SSHDeriveKeyType.serverMacKey:
|
||||||
|
return 'F'.codeUnits.first;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+716
@@ -0,0 +1,716 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:asn1lib/asn1lib.dart';
|
||||||
|
import 'package:convert/convert.dart';
|
||||||
|
import 'package:dartssh2/dartssh2.dart';
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_ecdsa.dart';
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_ed25519.dart';
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_rsa.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_hostkey.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bcrypt.dart';
|
||||||
|
import 'package:dartssh2/src/utils/cipher_ext.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
import 'package:pinenacl/ed25519.dart' as ed25519;
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
abstract class SSHKeyPair {
|
||||||
|
static List<SSHKeyPair> fromPem(String pemText, [String? passphrase]) {
|
||||||
|
final pem = SSHPem.decode(pemText);
|
||||||
|
switch (pem.type) {
|
||||||
|
case 'OPENSSH PRIVATE KEY':
|
||||||
|
final pairs = OpenSSHKeyPairs.decode(pem.content);
|
||||||
|
return pairs.getPrivateKeys(passphrase);
|
||||||
|
case 'RSA PRIVATE KEY':
|
||||||
|
final pair = RsaKeyPair.decode(pem);
|
||||||
|
return [pair.getPrivateKeys(passphrase)];
|
||||||
|
default:
|
||||||
|
throw UnsupportedError('Unsupported key type: ${pem.type}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isEncryptedPem(String pemText) {
|
||||||
|
final pem = SSHPem.decode(pemText);
|
||||||
|
switch (pem.type) {
|
||||||
|
case 'OPENSSH PRIVATE KEY':
|
||||||
|
final pairs = OpenSSHKeyPairs.decode(pem.content);
|
||||||
|
return pairs.isEncrypted;
|
||||||
|
case 'RSA PRIVATE KEY':
|
||||||
|
final pair = RsaKeyPair.decode(pem);
|
||||||
|
return pair.isEncrypted;
|
||||||
|
default:
|
||||||
|
throw UnsupportedError('Unsupported key type: ${pem.type}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [name] is the name of the algorithm used when saving the key. This only
|
||||||
|
/// affects how the key is serialized.
|
||||||
|
String get name;
|
||||||
|
|
||||||
|
/// [type] indicates not only the encoding of the key, but also the the
|
||||||
|
/// algorithm used when signing. Until now only RSA keys have [type]s that are
|
||||||
|
/// different from [name].
|
||||||
|
String get type;
|
||||||
|
|
||||||
|
SSHHostKey toPublicKey();
|
||||||
|
|
||||||
|
SSHSignature sign(Uint8List data);
|
||||||
|
|
||||||
|
String toPem();
|
||||||
|
}
|
||||||
|
|
||||||
|
class OpenSSHKeyPairs {
|
||||||
|
static const magic = 'openssh-key-v1';
|
||||||
|
|
||||||
|
/// Name of the algorithm used to encrypt the private key. 'none' means no
|
||||||
|
/// encryption.
|
||||||
|
final String cipherName;
|
||||||
|
|
||||||
|
/// Key derivation function used to derive the encryption key. 'none' means
|
||||||
|
/// no key derivation thus no encryption.
|
||||||
|
final String kdfName;
|
||||||
|
|
||||||
|
/// Options for the key derivation function.
|
||||||
|
final OpenSSHKdfOptions? kdfOptions;
|
||||||
|
|
||||||
|
/// List of public keys.
|
||||||
|
final List<Uint8List> publicKeys;
|
||||||
|
|
||||||
|
/// List of private keys.
|
||||||
|
final Uint8List privateKeyBlob;
|
||||||
|
|
||||||
|
/// Whether the private key is encrypted.
|
||||||
|
bool get isEncrypted => cipherName != 'none';
|
||||||
|
|
||||||
|
OpenSSHKeyPairs({
|
||||||
|
required this.cipherName,
|
||||||
|
required this.kdfName,
|
||||||
|
required this.kdfOptions,
|
||||||
|
required this.publicKeys,
|
||||||
|
required this.privateKeyBlob,
|
||||||
|
});
|
||||||
|
|
||||||
|
OpenSSHKeyPairs.unencrypted({
|
||||||
|
required this.publicKeys,
|
||||||
|
required this.privateKeyBlob,
|
||||||
|
}) : cipherName = 'none',
|
||||||
|
kdfName = 'none',
|
||||||
|
kdfOptions = null;
|
||||||
|
|
||||||
|
factory OpenSSHKeyPairs.decode(Uint8List keyBlob) {
|
||||||
|
final reader = SSHMessageReader(keyBlob);
|
||||||
|
final actualMagic = reader.readBytes(magic.length);
|
||||||
|
if (!actualMagic.equals(magic.codeUnits)) {
|
||||||
|
throw FormatException('Invalid magic: ${latin1.decode(actualMagic)}');
|
||||||
|
}
|
||||||
|
reader.readUint8(); // terminator of magic
|
||||||
|
final cipher = reader.readUtf8();
|
||||||
|
final kdfName = reader.readUtf8();
|
||||||
|
|
||||||
|
late final OpenSSHBcryptKdfOptions? kdfOptions;
|
||||||
|
final kdfOptionsBlock = reader.readString();
|
||||||
|
|
||||||
|
if (cipher == 'none') {
|
||||||
|
kdfOptions = null;
|
||||||
|
} else if (kdfName == 'bcrypt') {
|
||||||
|
kdfOptions = OpenSSHBcryptKdfOptions.decode(kdfOptionsBlock);
|
||||||
|
} else {
|
||||||
|
throw UnsupportedError('Unsupported key derivation function: $kdfName');
|
||||||
|
}
|
||||||
|
|
||||||
|
final keyCount = reader.readUint32();
|
||||||
|
final publicKeys = <Uint8List>[];
|
||||||
|
for (var i = 0; i < keyCount; i++) {
|
||||||
|
publicKeys.add(reader.readString());
|
||||||
|
}
|
||||||
|
|
||||||
|
final privateKeysBlob = reader.readString();
|
||||||
|
|
||||||
|
return OpenSSHKeyPairs(
|
||||||
|
cipherName: cipher,
|
||||||
|
kdfName: kdfName,
|
||||||
|
kdfOptions: kdfOptions,
|
||||||
|
publicKeys: publicKeys,
|
||||||
|
privateKeyBlob: privateKeysBlob,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<SSHKeyPair> getPrivateKeys([String? passphrase]) {
|
||||||
|
late Uint8List unencryptedKeys;
|
||||||
|
|
||||||
|
if (isEncrypted) {
|
||||||
|
if (passphrase == null) {
|
||||||
|
throw SSHKeyDecryptError('Private key is encrypted');
|
||||||
|
}
|
||||||
|
final passphraseBytes = Utf8Encoder().convert(passphrase);
|
||||||
|
unencryptedKeys = _decryptPrivateKeyBlob(privateKeyBlob, passphraseBytes);
|
||||||
|
} else {
|
||||||
|
if (passphrase != null) {
|
||||||
|
throw ArgumentError('Passphrase is not required for unencrypted keys');
|
||||||
|
}
|
||||||
|
unencryptedKeys = privateKeyBlob;
|
||||||
|
}
|
||||||
|
|
||||||
|
final reader = SSHMessageReader(unencryptedKeys);
|
||||||
|
final checkInt1 = reader.readUint32();
|
||||||
|
final checkInt2 = reader.readUint32();
|
||||||
|
if (checkInt1 != checkInt2) {
|
||||||
|
if (isEncrypted) {
|
||||||
|
throw SSHKeyDecryptError('Invalid passphrase');
|
||||||
|
} else {
|
||||||
|
throw SSHKeyDecryptError('Invalid private key');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final keypairs = <SSHKeyPair>[];
|
||||||
|
for (var i = 0; i < publicKeys.length; i++) {
|
||||||
|
final type = reader.readUtf8();
|
||||||
|
switch (type) {
|
||||||
|
case 'ssh-rsa':
|
||||||
|
keypairs.add(OpenSSHRsaKeyPair.readFrom(reader));
|
||||||
|
break;
|
||||||
|
case 'ssh-ed25519':
|
||||||
|
keypairs.add(OpenSSHEd25519KeyPair.readFrom(reader));
|
||||||
|
break;
|
||||||
|
case 'ecdsa-sha2-nistp256':
|
||||||
|
case 'ecdsa-sha2-nistp384':
|
||||||
|
case 'ecdsa-sha2-nistp521':
|
||||||
|
keypairs.add(OpenSSHEcdsaKeyPair.readFrom(reader));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw UnsupportedError('Unsupported key type: $type');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return keypairs;
|
||||||
|
}
|
||||||
|
|
||||||
|
String toPem() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeBytes(Uint8List.fromList(magic.codeUnits));
|
||||||
|
writer.writeUint8(0); // terminator of magic
|
||||||
|
|
||||||
|
writer.writeUtf8(cipherName);
|
||||||
|
writer.writeUtf8(kdfName);
|
||||||
|
writer.writeString(kdfOptions?.encode() ?? Uint8List(0));
|
||||||
|
|
||||||
|
writer.writeUint32(publicKeys.length);
|
||||||
|
for (var i = 0; i < publicKeys.length; i++) {
|
||||||
|
writer.writeString(publicKeys[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.writeString(privateKeyBlob);
|
||||||
|
return SSHPem('OPENSSH PRIVATE KEY', {}, writer.takeBytes()).encode(70);
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List _decryptPrivateKeyBlob(Uint8List blob, Uint8List passphrase) {
|
||||||
|
final cipher = SSHCipherType.fromName(cipherName);
|
||||||
|
|
||||||
|
if (cipher == null) {
|
||||||
|
throw UnsupportedError('Unsupported cipher: $cipherName');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.kdfOptions is! OpenSSHBcryptKdfOptions) {
|
||||||
|
throw UnsupportedError('Unsupported key derivation function: $kdfName');
|
||||||
|
}
|
||||||
|
|
||||||
|
final kdfOptions = this.kdfOptions as OpenSSHBcryptKdfOptions;
|
||||||
|
|
||||||
|
final kdfHash = Uint8List(cipher.keySize + cipher.ivSize);
|
||||||
|
|
||||||
|
bcrypt_pbkdf(
|
||||||
|
passphrase,
|
||||||
|
passphrase.lengthInBytes,
|
||||||
|
kdfOptions.salt,
|
||||||
|
kdfOptions.salt.lengthInBytes,
|
||||||
|
kdfHash,
|
||||||
|
kdfHash.lengthInBytes,
|
||||||
|
kdfOptions.rounds,
|
||||||
|
);
|
||||||
|
|
||||||
|
final key = Uint8List.view(kdfHash.buffer, 0, cipher.keySize);
|
||||||
|
final iv = Uint8List.view(kdfHash.buffer, cipher.keySize, cipher.ivSize);
|
||||||
|
final decryptCipher = cipher.createCipher(key, iv, forEncryption: false);
|
||||||
|
return decryptCipher.processAll(blob);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType{cipher: $cipherName, kdf: $kdfName, kdfOptions: $kdfOptions, keys.length: ${publicKeys.length}}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class OpenSSHKdfOptions {
|
||||||
|
Uint8List encode();
|
||||||
|
}
|
||||||
|
|
||||||
|
class OpenSSHBcryptKdfOptions implements OpenSSHKdfOptions {
|
||||||
|
final Uint8List salt;
|
||||||
|
final int rounds;
|
||||||
|
|
||||||
|
OpenSSHBcryptKdfOptions(this.salt, this.rounds);
|
||||||
|
|
||||||
|
factory OpenSSHBcryptKdfOptions.decode(Uint8List data) {
|
||||||
|
final reader = SSHMessageReader(data);
|
||||||
|
final salt = reader.readString();
|
||||||
|
final rounds = reader.readUint32();
|
||||||
|
return OpenSSHBcryptKdfOptions(salt, rounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List encode() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeString(salt);
|
||||||
|
writer.writeUint32(rounds);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType{salt: ${latin1.decode(salt)}, rounds: $rounds}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class OpenSSHKeyPair implements SSHKeyPair {
|
||||||
|
void writeTo(SSHMessageWriter writer);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toPem() {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
final checkInt = Random().nextInt(0xFFFFFFFF);
|
||||||
|
|
||||||
|
writer.writeUint32(checkInt);
|
||||||
|
writer.writeUint32(checkInt);
|
||||||
|
writer.writeUtf8(name);
|
||||||
|
writeTo(writer);
|
||||||
|
|
||||||
|
// pad with bytes 1, 2, 3, ...
|
||||||
|
for (var i = 0; writer.length % 8 != 0; i++) {
|
||||||
|
writer.writeUint8(i + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return OpenSSHKeyPairs.unencrypted(
|
||||||
|
publicKeys: [toPublicKey().encode()],
|
||||||
|
privateKeyBlob: writer.takeBytes(),
|
||||||
|
).toPem();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class OpenSSHRsaKeyPair with OpenSSHKeyPair {
|
||||||
|
@override
|
||||||
|
final name = 'ssh-rsa';
|
||||||
|
|
||||||
|
@override
|
||||||
|
final type = SSHRsaSignatureType.sha256;
|
||||||
|
|
||||||
|
final BigInt n;
|
||||||
|
final BigInt e;
|
||||||
|
|
||||||
|
final BigInt d;
|
||||||
|
final BigInt iqmp;
|
||||||
|
final BigInt p;
|
||||||
|
final BigInt q;
|
||||||
|
|
||||||
|
final String comment;
|
||||||
|
|
||||||
|
OpenSSHRsaKeyPair(
|
||||||
|
this.n,
|
||||||
|
this.e,
|
||||||
|
this.d,
|
||||||
|
this.iqmp,
|
||||||
|
this.p,
|
||||||
|
this.q,
|
||||||
|
this.comment,
|
||||||
|
);
|
||||||
|
|
||||||
|
factory OpenSSHRsaKeyPair.readFrom(SSHMessageReader reader) {
|
||||||
|
final n = reader.readMpint();
|
||||||
|
final e = reader.readMpint();
|
||||||
|
final d = reader.readMpint();
|
||||||
|
final iqmp = reader.readMpint();
|
||||||
|
final p = reader.readMpint();
|
||||||
|
final q = reader.readMpint();
|
||||||
|
final comment = reader.readUtf8();
|
||||||
|
return OpenSSHRsaKeyPair(n, e, d, iqmp, p, q, comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHHostKey toPublicKey() {
|
||||||
|
return SSHRsaPublicKey(e, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHRsaSignature sign(Uint8List data) {
|
||||||
|
final signer = RSASigner(SHA256Digest(), '0609608648016503040201');
|
||||||
|
|
||||||
|
signer.init(
|
||||||
|
true,
|
||||||
|
PrivateKeyParameter<RSAPrivateKey>(
|
||||||
|
RSAPrivateKey(n, d, p, q),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return SSHRsaSignature(type, signer.generateSignature(data).bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeMpint(n);
|
||||||
|
writer.writeMpint(e);
|
||||||
|
writer.writeMpint(d);
|
||||||
|
writer.writeMpint(iqmp);
|
||||||
|
writer.writeMpint(p);
|
||||||
|
writer.writeMpint(q);
|
||||||
|
writer.writeUtf8(comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(comment: "$comment")';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class OpenSSHEd25519KeyPair with OpenSSHKeyPair {
|
||||||
|
@override
|
||||||
|
final name = 'ssh-ed25519';
|
||||||
|
|
||||||
|
@override
|
||||||
|
final type = 'ssh-ed25519';
|
||||||
|
|
||||||
|
final Uint8List publicKey;
|
||||||
|
|
||||||
|
final Uint8List privateKey;
|
||||||
|
|
||||||
|
final String comment;
|
||||||
|
|
||||||
|
OpenSSHEd25519KeyPair(this.publicKey, this.privateKey, this.comment);
|
||||||
|
|
||||||
|
factory OpenSSHEd25519KeyPair.readFrom(SSHMessageReader reader) {
|
||||||
|
final publicKey = reader.readString();
|
||||||
|
final privateKey = reader.readString();
|
||||||
|
final comment = reader.readUtf8();
|
||||||
|
return OpenSSHEd25519KeyPair(publicKey, privateKey, comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHHostKey toPublicKey() {
|
||||||
|
return SSHEd25519PublicKey(publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHEd25519Signature sign(Uint8List data) {
|
||||||
|
final signer = ed25519.SigningKey.fromValidBytes(privateKey);
|
||||||
|
return SSHEd25519Signature(signer.sign(data).asTypedList.sublist(0, 64));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeString(publicKey);
|
||||||
|
writer.writeString(privateKey);
|
||||||
|
writer.writeUtf8(comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(comment: "$comment")';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class OpenSSHEcdsaKeyPair with OpenSSHKeyPair {
|
||||||
|
@override
|
||||||
|
String get name => 'ecdsa-sha2-$curveId';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get type => 'ecdsa-sha2-$curveId';
|
||||||
|
|
||||||
|
final String curveId;
|
||||||
|
|
||||||
|
final Uint8List q;
|
||||||
|
|
||||||
|
final BigInt d;
|
||||||
|
|
||||||
|
final String comment;
|
||||||
|
|
||||||
|
OpenSSHEcdsaKeyPair(this.curveId, this.q, this.d, this.comment);
|
||||||
|
|
||||||
|
factory OpenSSHEcdsaKeyPair.readFrom(SSHMessageReader reader) {
|
||||||
|
final curve = reader.readUtf8();
|
||||||
|
final q = reader.readString();
|
||||||
|
final d = reader.readMpint();
|
||||||
|
final comment = reader.readUtf8();
|
||||||
|
return OpenSSHEcdsaKeyPair(curve, q, d, comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHHostKey toPublicKey() {
|
||||||
|
return SSHEcdsaPublicKey(type: name, curveId: curveId, q: q);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHEcdsaSignature sign(Uint8List data) {
|
||||||
|
late Digest hash;
|
||||||
|
late ECDomainParameters curve;
|
||||||
|
|
||||||
|
switch (curveId) {
|
||||||
|
case 'nistp256':
|
||||||
|
hash = SHA256Digest();
|
||||||
|
curve = ECCurve_secp256r1();
|
||||||
|
break;
|
||||||
|
case 'nistp384':
|
||||||
|
hash = SHA384Digest();
|
||||||
|
curve = ECCurve_secp384r1();
|
||||||
|
break;
|
||||||
|
case 'nistp521':
|
||||||
|
hash = SHA512Digest();
|
||||||
|
curve = ECCurve_secp521r1();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw UnsupportedError('Unsupported curve: $curveId');
|
||||||
|
}
|
||||||
|
|
||||||
|
final signer = ECDSASigner(hash);
|
||||||
|
|
||||||
|
signer.init(
|
||||||
|
true,
|
||||||
|
ParametersWithRandom(
|
||||||
|
PrivateKeyParameter(ECPrivateKey(d, curve)),
|
||||||
|
FortunaRandom()..seed(KeyParameter(randomBytes(32))),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final signature = signer.generateSignature(data) as ECSignature;
|
||||||
|
return SSHEcdsaSignature('ecdsa-sha2-$curveId', signature.r, signature.s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void writeTo(SSHMessageWriter writer) {
|
||||||
|
writer.writeUtf8(curveId);
|
||||||
|
writer.writeString(q);
|
||||||
|
writer.writeMpint(d);
|
||||||
|
writer.writeUtf8(comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(comment: "$comment")';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RsaKeyPair {
|
||||||
|
final RsaKeyPairDEKInfo? dekInfo;
|
||||||
|
|
||||||
|
final Uint8List keyBlob;
|
||||||
|
|
||||||
|
const RsaKeyPair(this.dekInfo, this.keyBlob);
|
||||||
|
|
||||||
|
factory RsaKeyPair.decode(SSHPem pem) {
|
||||||
|
final dekInfoHeader = pem.headers['DEK-Info'];
|
||||||
|
|
||||||
|
final dekInfo =
|
||||||
|
dekInfoHeader != null ? RsaKeyPairDEKInfo.parse(dekInfoHeader) : null;
|
||||||
|
|
||||||
|
final keyBlob = pem.content;
|
||||||
|
|
||||||
|
return RsaKeyPair(dekInfo, keyBlob);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isEncrypted => dekInfo != null;
|
||||||
|
|
||||||
|
RsaPrivateKey getPrivateKeys([String? passphrase]) {
|
||||||
|
var keyBlob = this.keyBlob;
|
||||||
|
|
||||||
|
if (isEncrypted) {
|
||||||
|
if (passphrase == null) {
|
||||||
|
throw ArgumentError('passphrase is required for encrypted key');
|
||||||
|
}
|
||||||
|
final passphraseBytes = Utf8Encoder().convert(passphrase);
|
||||||
|
keyBlob = _decryptPrivateKeyBlob(passphraseBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return RsaPrivateKey.decode(keyBlob);
|
||||||
|
} catch (e) {
|
||||||
|
throw SSHKeyDecodeError('Failed to decode private key', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List _decryptPrivateKeyBlob(Uint8List passphrase) {
|
||||||
|
final cipher = _getCipher(dekInfo!.algorithm);
|
||||||
|
|
||||||
|
if (cipher == null) {
|
||||||
|
throw UnsupportedError('Unsupported cipher: ${dekInfo!.algorithm}');
|
||||||
|
}
|
||||||
|
|
||||||
|
final kdfHash = _deriveKey(
|
||||||
|
Uint8List.sublistView(dekInfo!.iv, 0, 8),
|
||||||
|
passphrase,
|
||||||
|
cipher.keySize,
|
||||||
|
);
|
||||||
|
|
||||||
|
final key = Uint8List.sublistView(kdfHash, 0, cipher.keySize);
|
||||||
|
|
||||||
|
final decryptCipher =
|
||||||
|
cipher.createCipher(key, dekInfo!.iv, forEncryption: false);
|
||||||
|
|
||||||
|
return decryptCipher.processAll(keyBlob);
|
||||||
|
}
|
||||||
|
|
||||||
|
static SSHCipherType? _getCipher(String name) {
|
||||||
|
switch (name.toUpperCase()) {
|
||||||
|
case 'AES-128-CBC':
|
||||||
|
return SSHCipherType.aes128cbc;
|
||||||
|
case 'AES-192-CBC':
|
||||||
|
return SSHCipherType.aes192cbc;
|
||||||
|
case 'AES-256-CBC':
|
||||||
|
return SSHCipherType.aes256cbc;
|
||||||
|
case 'AES-128-CTR':
|
||||||
|
return SSHCipherType.aes128ctr;
|
||||||
|
case 'AES-192-CTR':
|
||||||
|
return SSHCipherType.aes192ctr;
|
||||||
|
case 'AES-256-CTR':
|
||||||
|
return SSHCipherType.aes256ctr;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Uint8List _deriveKey(Uint8List salt, Uint8List data, int length) {
|
||||||
|
final result = BytesBuilder();
|
||||||
|
var lastHash = Uint8List(0);
|
||||||
|
|
||||||
|
while (result.length < length) {
|
||||||
|
final digest = MD5Digest();
|
||||||
|
final hash = Uint8List(digest.digestSize);
|
||||||
|
digest.reset();
|
||||||
|
digest.update(lastHash, 0, lastHash.length);
|
||||||
|
digest.update(data, 0, data.length);
|
||||||
|
digest.update(salt, 0, salt.length);
|
||||||
|
digest.doFinal(hash, 0);
|
||||||
|
result.add(hash);
|
||||||
|
lastHash = hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.takeBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corresponds to the `DEK-Info` header in PEM.
|
||||||
|
class RsaKeyPairDEKInfo {
|
||||||
|
final String algorithm;
|
||||||
|
final Uint8List iv;
|
||||||
|
|
||||||
|
RsaKeyPairDEKInfo(this.algorithm, this.iv);
|
||||||
|
|
||||||
|
factory RsaKeyPairDEKInfo.parse(String header) {
|
||||||
|
final parts = header.split(',');
|
||||||
|
if (parts.length != 2) {
|
||||||
|
throw FormatException('Invalid DEK-Info header: $header');
|
||||||
|
}
|
||||||
|
return RsaKeyPairDEKInfo(
|
||||||
|
parts[0],
|
||||||
|
Uint8List.fromList(hex.decode(parts[1])),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(algorithm: $algorithm, iv: ${hex.encode(iv)})';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RsaPrivateKey implements SSHKeyPair {
|
||||||
|
@override
|
||||||
|
final name = 'ssh-rsa';
|
||||||
|
|
||||||
|
@override
|
||||||
|
final type = SSHRsaSignatureType.sha256;
|
||||||
|
|
||||||
|
final BigInt version;
|
||||||
|
final BigInt n;
|
||||||
|
final BigInt e;
|
||||||
|
final BigInt d;
|
||||||
|
final BigInt p;
|
||||||
|
final BigInt q;
|
||||||
|
final BigInt exponent1;
|
||||||
|
final BigInt exponent2;
|
||||||
|
final BigInt coefficient;
|
||||||
|
|
||||||
|
RsaPrivateKey(
|
||||||
|
this.version,
|
||||||
|
this.n,
|
||||||
|
this.e,
|
||||||
|
this.d,
|
||||||
|
this.p,
|
||||||
|
this.q,
|
||||||
|
this.exponent1,
|
||||||
|
this.exponent2,
|
||||||
|
this.coefficient,
|
||||||
|
);
|
||||||
|
|
||||||
|
factory RsaPrivateKey.decode(Uint8List keyBlob) {
|
||||||
|
final parser = ASN1Parser(keyBlob);
|
||||||
|
|
||||||
|
final sequence = parser.nextObject() as ASN1Sequence;
|
||||||
|
final version = (sequence.elements[0] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final n = (sequence.elements[1] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final e = (sequence.elements[2] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final d = (sequence.elements[3] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final p = (sequence.elements[4] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final q = (sequence.elements[5] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final exponent1 = (sequence.elements[6] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final exponent2 = (sequence.elements[7] as ASN1Integer).valueAsBigInteger;
|
||||||
|
final coefficient = (sequence.elements[8] as ASN1Integer).valueAsBigInteger;
|
||||||
|
|
||||||
|
return RsaPrivateKey(
|
||||||
|
version,
|
||||||
|
n,
|
||||||
|
e,
|
||||||
|
d,
|
||||||
|
p,
|
||||||
|
q,
|
||||||
|
exponent1,
|
||||||
|
exponent2,
|
||||||
|
coefficient,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHHostKey toPublicKey() {
|
||||||
|
return SSHRsaPublicKey(e, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
SSHRsaSignature sign(Uint8List data) {
|
||||||
|
final signer = RSASigner(SHA256Digest(), '0609608648016503040201');
|
||||||
|
|
||||||
|
signer.init(
|
||||||
|
true,
|
||||||
|
PrivateKeyParameter<RSAPrivateKey>(
|
||||||
|
RSAPrivateKey(n, d, p, q),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return SSHRsaSignature(type, signer.generateSignature(data).bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toPem() {
|
||||||
|
final sequence = ASN1Sequence();
|
||||||
|
sequence.add(ASN1Integer(version));
|
||||||
|
sequence.add(ASN1Integer(n));
|
||||||
|
sequence.add(ASN1Integer(e));
|
||||||
|
sequence.add(ASN1Integer(d));
|
||||||
|
sequence.add(ASN1Integer(p));
|
||||||
|
sequence.add(ASN1Integer(q));
|
||||||
|
sequence.add(ASN1Integer(exponent1));
|
||||||
|
sequence.add(ASN1Integer(exponent2));
|
||||||
|
sequence.add(ASN1Integer(coefficient));
|
||||||
|
return SSHPem('RSA PRIVATE KEY', {}, sequence.encodedBytes).encode(64);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType(version: $version)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/utils/int.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bigint.dart';
|
||||||
|
import 'package:dartssh2/src/utils/utf8.dart';
|
||||||
|
|
||||||
|
abstract class SSHMessage {
|
||||||
|
/// Encode the message to SSH encoded data.
|
||||||
|
Uint8List encode();
|
||||||
|
|
||||||
|
static int readMessageId(Uint8List bytes) {
|
||||||
|
return bytes[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHMessageReader {
|
||||||
|
/// Message data.
|
||||||
|
final Uint8List data;
|
||||||
|
|
||||||
|
SSHMessageReader(this.data) : _byteData = ByteData.sublistView(data);
|
||||||
|
|
||||||
|
/// ByteData view of [data], used for reading numbers.
|
||||||
|
final ByteData _byteData;
|
||||||
|
|
||||||
|
/// The current position in the message.
|
||||||
|
var _offset = 0;
|
||||||
|
|
||||||
|
bool get isDone => _offset >= data.length;
|
||||||
|
|
||||||
|
void skip(int bytes) {
|
||||||
|
_offset += bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool readBool() {
|
||||||
|
return readUint8() != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int readUint8() {
|
||||||
|
return _byteData.getUint8(_offset++);
|
||||||
|
}
|
||||||
|
|
||||||
|
int readUint16() {
|
||||||
|
final value = _byteData.getUint16(_offset);
|
||||||
|
_offset += 2;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
int readUint32() {
|
||||||
|
final value = _byteData.getUint32(_offset);
|
||||||
|
_offset += 4;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
int readUint64() {
|
||||||
|
final value = _byteData.getUint64(_offset);
|
||||||
|
_offset += 8;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List readBytes(int length) {
|
||||||
|
final value = Uint8List.view(_byteData.buffer, _offset, length);
|
||||||
|
_offset += length;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List readString() {
|
||||||
|
final length = readUint32();
|
||||||
|
final value = Uint8List.sublistView(data, _offset, _offset + length);
|
||||||
|
_offset += length;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
String readUtf8() {
|
||||||
|
return utf8.decode(readString());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> readNameList() {
|
||||||
|
final string = utf8.decode(readString());
|
||||||
|
final list = string.split(',');
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Uint8List> readStringList() {
|
||||||
|
final list = <Uint8List>[];
|
||||||
|
while (!isDone) {
|
||||||
|
list.add(readString());
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInt readMpint() {
|
||||||
|
final magnitude = readString();
|
||||||
|
final value = decodeBigIntWithSign(1, magnitude);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List readToEnd() {
|
||||||
|
final value = Uint8List.sublistView(data, _offset);
|
||||||
|
_offset = data.length;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHMessageWriter {
|
||||||
|
SSHMessageWriter({bool copy = false}) : _builder = BytesBuilder(copy: copy);
|
||||||
|
|
||||||
|
final BytesBuilder _builder;
|
||||||
|
|
||||||
|
int get length => _builder.length;
|
||||||
|
|
||||||
|
void writeBool(bool value) {
|
||||||
|
_builder.addByte(value ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeUint8(int value) {
|
||||||
|
_builder.addByte(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// void writeUint16(int value) {
|
||||||
|
// _builder.addByte(value >> 8);
|
||||||
|
// _builder.addByte(value);
|
||||||
|
// }
|
||||||
|
|
||||||
|
void writeUint32(int value) {
|
||||||
|
_builder.add(value.toUint32());
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeUint64(int value) {
|
||||||
|
_builder.add(value.toUint64());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write fixed length string.
|
||||||
|
void writeBytes(Uint8List value) {
|
||||||
|
_builder.add(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write variable length string.
|
||||||
|
void writeString(Uint8List value) {
|
||||||
|
writeUint32(value.length);
|
||||||
|
writeBytes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeUtf8(String value) {
|
||||||
|
writeString(utf8Encode(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write comma separated list of names as a string.
|
||||||
|
void writeNameList(List<String> value) {
|
||||||
|
writeString(Utf8Encoder().convert(value.join(',')));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write multiple precision integer as a string.
|
||||||
|
void writeMpint(BigInt value) {
|
||||||
|
writeString(encodeBigInt(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List takeBytes() {
|
||||||
|
return _builder.takeBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
/// Contains rfc4253 packet format related constants and helper functions.
|
||||||
|
abstract class SSHPacket {
|
||||||
|
/// The maximum size of a packet including the header and MAC.
|
||||||
|
static const maxLength = 35000;
|
||||||
|
|
||||||
|
/// The maximum size of uncompressed packet payload.
|
||||||
|
static const maxPayloadLength = 32768;
|
||||||
|
|
||||||
|
/// rfc4253 requires the total length of the packet is a multiple of 8 or
|
||||||
|
/// the cipher block size, whichever is larger.
|
||||||
|
static const minAlign = 8;
|
||||||
|
|
||||||
|
/// The length of the packet header, is the sum of the lengths of the
|
||||||
|
/// length field and the padding length field.
|
||||||
|
static const headerLength = 5;
|
||||||
|
|
||||||
|
/// Returns the length field of the packet. This is the number of bytes
|
||||||
|
/// following the length field except for the MAC. [packet] can be partitial.
|
||||||
|
static int readPacketLength(Uint8List packet) {
|
||||||
|
return ByteData.sublistView(packet).getUint32(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the length of padding at the end of the packet before the MAC.
|
||||||
|
/// [packet] can be partitial.
|
||||||
|
static int readPaddingLength(Uint8List packet) {
|
||||||
|
return ByteData.sublistView(packet).getUint8(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Computes the correct padding length for the packet from [payloadLength]
|
||||||
|
/// and [align].
|
||||||
|
static int paddingLength(int payloadLength, {required int align}) {
|
||||||
|
final paddingLength = align - ((payloadLength + headerLength) % align);
|
||||||
|
// ssh padding must be at least 4 bytes
|
||||||
|
return paddingLength < 4 ? paddingLength + align : paddingLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a rfc4253 packet built from [payload] and [align] including the
|
||||||
|
/// length field, padding length field, and padding. Withouth the MAC.
|
||||||
|
static Uint8List pack(Uint8List payload, {required int align}) {
|
||||||
|
final padding = paddingLength(payload.length, align: align);
|
||||||
|
final header = ByteData(5);
|
||||||
|
header.setUint32(0, 1 + payload.length + padding);
|
||||||
|
header.setUint8(4, padding);
|
||||||
|
final result = BytesBuilder(copy: false);
|
||||||
|
result.add(Uint8List.view(header.buffer));
|
||||||
|
result.add(payload);
|
||||||
|
result.add(Uint8List(padding));
|
||||||
|
return result.takeBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SSH packet sequence number wraps around to zero after every 2^32
|
||||||
|
/// packets.
|
||||||
|
class SSHPacketSN {
|
||||||
|
SSHPacketSN(this._value);
|
||||||
|
|
||||||
|
SSHPacketSN.fromZero() : _value = 0;
|
||||||
|
|
||||||
|
var _value = 0;
|
||||||
|
|
||||||
|
int get value => _value;
|
||||||
|
|
||||||
|
void increase() {
|
||||||
|
if (_value == 0xffffffff) {
|
||||||
|
_value = 0;
|
||||||
|
} else {
|
||||||
|
_value++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
class SSHPem {
|
||||||
|
final String type;
|
||||||
|
|
||||||
|
final Map<String, String> headers;
|
||||||
|
|
||||||
|
final Uint8List content;
|
||||||
|
|
||||||
|
SSHPem(this.type, this.headers, this.content);
|
||||||
|
|
||||||
|
static const _pemHeaderBegin = '-----BEGIN ';
|
||||||
|
static const _pemFooterBegin = '-----END ';
|
||||||
|
static const _pemEnd = '-----';
|
||||||
|
|
||||||
|
factory SSHPem.decode(String pem) {
|
||||||
|
final lines = pem.trim().split("\n");
|
||||||
|
final header = lines.first;
|
||||||
|
final footer = lines.last;
|
||||||
|
|
||||||
|
if (!header.startsWith(_pemHeaderBegin)) {
|
||||||
|
throw FormatException('PEM header must start with $_pemHeaderBegin');
|
||||||
|
}
|
||||||
|
if (!footer.startsWith(_pemFooterBegin)) {
|
||||||
|
throw FormatException('PEM footer must start with $_pemFooterBegin');
|
||||||
|
}
|
||||||
|
if (!header.endsWith(_pemEnd)) {
|
||||||
|
throw FormatException('PEM header must end with $_pemEnd');
|
||||||
|
}
|
||||||
|
if (!footer.endsWith(_pemEnd)) {
|
||||||
|
throw FormatException('PEM footer must end with $_pemEnd');
|
||||||
|
}
|
||||||
|
|
||||||
|
final type = header.substring(
|
||||||
|
_pemHeaderBegin.length,
|
||||||
|
header.length - _pemEnd.length,
|
||||||
|
);
|
||||||
|
final footerType = footer.substring(
|
||||||
|
_pemFooterBegin.length,
|
||||||
|
footer.length - _pemEnd.length,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (type != footerType) {
|
||||||
|
throw FormatException('Type mismatch: $type != $footerType');
|
||||||
|
}
|
||||||
|
|
||||||
|
final pemHeader = <String, String>{};
|
||||||
|
|
||||||
|
final pemBodyLines = <String>[];
|
||||||
|
|
||||||
|
for (final line in lines.sublist(1, lines.length - 1)) {
|
||||||
|
if (line.trim().isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.contains(':')) {
|
||||||
|
if (pemBodyLines.isNotEmpty) {
|
||||||
|
throw FormatException('Unexpected header line: $line');
|
||||||
|
} else {
|
||||||
|
final parts = line.split(':');
|
||||||
|
pemHeader[parts[0].trim()] = parts[1].trim();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pemBodyLines.add(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
final pemBody = pemBodyLines.join('');
|
||||||
|
|
||||||
|
final content = base64.decode(pemBody);
|
||||||
|
|
||||||
|
return SSHPem(type, pemHeader, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
String encode([int lineLength = 64]) {
|
||||||
|
final encoded = base64.encode(content);
|
||||||
|
final builder = StringBuffer();
|
||||||
|
builder.writeln('-----BEGIN $type-----');
|
||||||
|
for (var i = 0; i < encoded.length; i += lineLength) {
|
||||||
|
final chunk = encoded.substring(i, min(i + lineLength, encoded.length));
|
||||||
|
builder.writeln(chunk);
|
||||||
|
}
|
||||||
|
builder.writeln('-----END $type-----');
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return '$runtimeType($type, length: ${content.length})';
|
||||||
|
}
|
||||||
|
}
|
||||||
+175
@@ -0,0 +1,175 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/ssh_channel.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_signal.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_channel.dart';
|
||||||
|
|
||||||
|
/// A [SSHSession] represents a remote execution of a program.
|
||||||
|
class SSHSession {
|
||||||
|
/// Stdin of the remote process. Close this to send EOF to the remote process.
|
||||||
|
StreamSink<Uint8List> get stdin => _stdinController.sink;
|
||||||
|
|
||||||
|
/// Stdout of the remote process.
|
||||||
|
Stream<Uint8List> get stdout => _stdoutController.stream;
|
||||||
|
|
||||||
|
/// Stderr of the remote process. May be empty if the remote process is
|
||||||
|
/// started in pseudo terminal or remote ssh implementation does not support
|
||||||
|
/// stderr.
|
||||||
|
Stream<Uint8List> get stderr => _stderrController.stream;
|
||||||
|
|
||||||
|
/// Exit code of the remote process. May be null if the process has not yet
|
||||||
|
/// exited, the remote process has been terminated due to a signal, or the
|
||||||
|
/// remote ssh implementation does not report exit codes.
|
||||||
|
int? get exitCode => _exitCode;
|
||||||
|
|
||||||
|
/// Information about the exit signal of a remote process. May be null if the
|
||||||
|
/// process is still running, the remote process exited normally, or the
|
||||||
|
/// remote ssh implementation does not report exit signals.
|
||||||
|
SSHSessionExitSignal? get exitSignal => _exitSignal;
|
||||||
|
|
||||||
|
/// This [Future] completes when the channel is closed. More data may still
|
||||||
|
/// be available on the [stdout] and [stderr] streams at this time.
|
||||||
|
Future<void> get done => _channel.done;
|
||||||
|
|
||||||
|
SSHSession(this._channel) {
|
||||||
|
_channel.setRequestHandler(_handleRequest);
|
||||||
|
|
||||||
|
_channelDataSubscription = _channel.stream.listen(
|
||||||
|
_handleChannelData,
|
||||||
|
onDone: _handleChannelDataDone,
|
||||||
|
);
|
||||||
|
|
||||||
|
_stdinController.stream
|
||||||
|
.map((data) => SSHChannelData(data))
|
||||||
|
.pipe(_channel.sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
final SSHChannel _channel;
|
||||||
|
|
||||||
|
int? _exitCode;
|
||||||
|
|
||||||
|
SSHSessionExitSignal? _exitSignal;
|
||||||
|
|
||||||
|
late final StreamSubscription _channelDataSubscription;
|
||||||
|
|
||||||
|
late final _stdinController = StreamController<Uint8List>();
|
||||||
|
|
||||||
|
late final _stdoutController = StreamController<Uint8List>(
|
||||||
|
onPause: _pauseChannelData,
|
||||||
|
onResume: _resumeChannelData,
|
||||||
|
);
|
||||||
|
|
||||||
|
late final _stderrController = StreamController<Uint8List>(
|
||||||
|
onPause: _pauseChannelData,
|
||||||
|
onResume: _resumeChannelData,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Writes data to the stdin of the remote process. This is a convenience
|
||||||
|
/// method that calls [stdin.add].
|
||||||
|
void write(Uint8List data) {
|
||||||
|
stdin.add(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inform remote process of the current window size.
|
||||||
|
void resizeTerminal(
|
||||||
|
int width,
|
||||||
|
int height, [
|
||||||
|
int pixelWidth = 0,
|
||||||
|
int pixelHeight = 0,
|
||||||
|
]) {
|
||||||
|
if (width < 0) {
|
||||||
|
throw ArgumentError.value(width, 'width', 'must be positive');
|
||||||
|
}
|
||||||
|
if (height < 0) {
|
||||||
|
throw ArgumentError.value(height, 'height', 'must be positive');
|
||||||
|
}
|
||||||
|
if (pixelWidth < 0) {
|
||||||
|
throw ArgumentError.value(pixelWidth, 'pixelWidth', 'must be positive');
|
||||||
|
}
|
||||||
|
if (pixelHeight < 0) {
|
||||||
|
throw ArgumentError.value(pixelHeight, 'pixelHeight', 'must be positive');
|
||||||
|
}
|
||||||
|
_channel.sendTerminalWindowChange(
|
||||||
|
width: width,
|
||||||
|
height: height,
|
||||||
|
pixelWidth: pixelWidth,
|
||||||
|
pixelHeight: pixelHeight,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close the session. After this call, the session is no longer usable.
|
||||||
|
void close() {
|
||||||
|
_channel.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver [signal] to the remote process. Some implementations may not
|
||||||
|
/// support this.
|
||||||
|
void kill(SSHSignal signal) {
|
||||||
|
_channel.sendSignal(signal.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _handleRequest(SSH_Message_Channel_Request request) {
|
||||||
|
switch (request.requestType) {
|
||||||
|
case SSHChannelRequestType.exitStatus:
|
||||||
|
_exitCode = request.exitStatus!;
|
||||||
|
return true;
|
||||||
|
case SSHChannelRequestType.exitSignal:
|
||||||
|
_exitSignal = SSHSessionExitSignal(
|
||||||
|
signalName: request.exitSignalName!,
|
||||||
|
coreDumped: request.coreDumped!,
|
||||||
|
errorMessage: request.errorMessage!,
|
||||||
|
languageTag: request.languageTag!,
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _pauseChannelData() {
|
||||||
|
_channelDataSubscription.pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _resumeChannelData() {
|
||||||
|
_channelDataSubscription.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleChannelData(SSHChannelData data) {
|
||||||
|
switch (data.type) {
|
||||||
|
case null:
|
||||||
|
return _stdoutController.add(data.bytes);
|
||||||
|
case SSHChannelExtendedDataType.stderr:
|
||||||
|
return _stderrController.add(data.bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleChannelDataDone() {
|
||||||
|
_stdoutController.close();
|
||||||
|
_stderrController.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Information about the exit signal of a remote process.
|
||||||
|
class SSHSessionExitSignal {
|
||||||
|
/// Signal name without the leading "SIG".
|
||||||
|
final String signalName;
|
||||||
|
|
||||||
|
final bool coreDumped;
|
||||||
|
|
||||||
|
/// An additional textual explanation of the error message
|
||||||
|
final String errorMessage;
|
||||||
|
|
||||||
|
final String languageTag;
|
||||||
|
|
||||||
|
SSHSessionExitSignal({
|
||||||
|
required this.signalName,
|
||||||
|
required this.coreDumped,
|
||||||
|
required this.errorMessage,
|
||||||
|
required this.languageTag,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHSessionExitSignal(signalName: $signalName, coreDumped: $coreDumped, errorMessage: $errorMessage, languageTag: $languageTag)';
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
// ignore_for_file: constant_identifier_names
|
||||||
|
|
||||||
|
enum SSHSignal {
|
||||||
|
ABRT,
|
||||||
|
ALRM,
|
||||||
|
FPE,
|
||||||
|
HUP,
|
||||||
|
ILL,
|
||||||
|
INT,
|
||||||
|
KILL,
|
||||||
|
PIPE,
|
||||||
|
QUIT,
|
||||||
|
SEGV,
|
||||||
|
TERM,
|
||||||
|
USR1,
|
||||||
|
USR2,
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHSignalX on SSHSignal {
|
||||||
|
String get name {
|
||||||
|
switch (this) {
|
||||||
|
case SSHSignal.ABRT:
|
||||||
|
return 'ABRT';
|
||||||
|
case SSHSignal.ALRM:
|
||||||
|
return 'ALRM';
|
||||||
|
case SSHSignal.FPE:
|
||||||
|
return 'FPE';
|
||||||
|
case SSHSignal.HUP:
|
||||||
|
return 'HUP';
|
||||||
|
case SSHSignal.ILL:
|
||||||
|
return 'ILL';
|
||||||
|
case SSHSignal.INT:
|
||||||
|
return 'INT';
|
||||||
|
case SSHSignal.KILL:
|
||||||
|
return 'KILL';
|
||||||
|
case SSHSignal.PIPE:
|
||||||
|
return 'PIPE';
|
||||||
|
case SSHSignal.QUIT:
|
||||||
|
return 'QUIT';
|
||||||
|
case SSHSignal.SEGV:
|
||||||
|
return 'SEGV';
|
||||||
|
case SSHSignal.TERM:
|
||||||
|
return 'TERM';
|
||||||
|
case SSHSignal.USR1:
|
||||||
|
return 'USR1';
|
||||||
|
case SSHSignal.USR2:
|
||||||
|
return 'USR2';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static SSHSignal fromName(String name) {
|
||||||
|
switch (name) {
|
||||||
|
case 'ABRT':
|
||||||
|
return SSHSignal.ABRT;
|
||||||
|
case 'ALRM':
|
||||||
|
return SSHSignal.ALRM;
|
||||||
|
case 'FPE':
|
||||||
|
return SSHSignal.FPE;
|
||||||
|
case 'HUP':
|
||||||
|
return SSHSignal.HUP;
|
||||||
|
case 'ILL':
|
||||||
|
return SSHSignal.ILL;
|
||||||
|
case 'INT':
|
||||||
|
return SSHSignal.INT;
|
||||||
|
case 'KILL':
|
||||||
|
return SSHSignal.KILL;
|
||||||
|
case 'PIPE':
|
||||||
|
return SSHSignal.PIPE;
|
||||||
|
case 'QUIT':
|
||||||
|
return SSHSignal.QUIT;
|
||||||
|
case 'SEGV':
|
||||||
|
return SSHSignal.SEGV;
|
||||||
|
case 'TERM':
|
||||||
|
return SSHSignal.TERM;
|
||||||
|
case 'USR1':
|
||||||
|
return SSHSignal.USR1;
|
||||||
|
case 'USR2':
|
||||||
|
return SSHSignal.USR2;
|
||||||
|
}
|
||||||
|
throw ArgumentError('Unknown signal name: $name');
|
||||||
|
}
|
||||||
|
}
|
||||||
+862
@@ -0,0 +1,862 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math' show max;
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_ecdsa.dart';
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_rsa.dart';
|
||||||
|
import 'package:dartssh2/src/kex/kex_dh.dart';
|
||||||
|
import 'package:dartssh2/src/kex/kex_nist.dart';
|
||||||
|
import 'package:dartssh2/src/kex/kex_x25519.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_userauth.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_algorithm.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_kex.dart';
|
||||||
|
import 'package:dartssh2/src/utils/bigint.dart';
|
||||||
|
import 'package:dartssh2/src/utils/cipher_ext.dart';
|
||||||
|
import 'package:dartssh2/src/utils/chunk_buffer.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_kex_utils.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_packet.dart';
|
||||||
|
import 'package:dartssh2/src/utils/int.dart';
|
||||||
|
import 'package:dartssh2/src/hostkey/hostkey_ed25519.dart';
|
||||||
|
import 'package:dartssh2/src/utils/list.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_kex.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_kex_dh.dart';
|
||||||
|
import 'package:dartssh2/src/message/msg_kex_ecdh.dart';
|
||||||
|
import 'package:dartssh2/src/ssh_message.dart';
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
import '../dartssh2.dart';
|
||||||
|
|
||||||
|
typedef SSHPrintHandler = void Function(String?);
|
||||||
|
|
||||||
|
/// Function called when host key is received.
|
||||||
|
/// [type] is the type of the host key, For example 'ssh-rsa',
|
||||||
|
/// [fingerprint] md5 fingerprint of the host key.
|
||||||
|
typedef SSHHostkeyVerifyHandler = FutureOr<bool> Function(
|
||||||
|
String type,
|
||||||
|
Uint8List fingerprint,
|
||||||
|
);
|
||||||
|
|
||||||
|
typedef SSHTransportReadyHandler = void Function();
|
||||||
|
|
||||||
|
typedef SSHPacketHandler = void Function(Uint8List payload);
|
||||||
|
|
||||||
|
class SSHTransport {
|
||||||
|
/// Version of the SSH software. By default "DartSSH_2.0"
|
||||||
|
final String version;
|
||||||
|
|
||||||
|
/// The socket to read and write data to.
|
||||||
|
final SSHSocket socket;
|
||||||
|
|
||||||
|
/// Whether the transport acts as a server.
|
||||||
|
final bool isServer;
|
||||||
|
|
||||||
|
/// Whether the transport acts as a client. This is equal to `!isServer`.
|
||||||
|
bool get isClient => !isServer;
|
||||||
|
|
||||||
|
/// Function invoked with debug logging.
|
||||||
|
final SSHPrintHandler? printDebug;
|
||||||
|
|
||||||
|
/// Function invoked with trace logging.
|
||||||
|
final SSHPrintHandler? printTrace;
|
||||||
|
|
||||||
|
final SSHAlgorithms algorithms;
|
||||||
|
|
||||||
|
/// Function called when the hostkey has been received. Returns true if the
|
||||||
|
/// hostkey is valid, false to reject key and disconnect.
|
||||||
|
final SSHHostkeyVerifyHandler? onVerifyHostKey;
|
||||||
|
|
||||||
|
/// Function called when the transport is ready to send data.
|
||||||
|
final SSHTransportReadyHandler? onReady;
|
||||||
|
|
||||||
|
/// Function called when a packet is received.
|
||||||
|
final SSHPacketHandler? onPacket;
|
||||||
|
|
||||||
|
/// A [Future] that completes when the transport is closed, or when an error
|
||||||
|
/// occurs. After this [Future] completes, [isClosed] will be true and no
|
||||||
|
/// more data can be sent or received.
|
||||||
|
Future<void> get done => _doneCompleter.future;
|
||||||
|
|
||||||
|
/// `true` if the connection is closed normally or due to an error.
|
||||||
|
bool get isClosed => _doneCompleter.isCompleted;
|
||||||
|
|
||||||
|
/// Identification string sent by the other side. For example, "SSH-2.0-OpenSSH_7.4p1".
|
||||||
|
/// May be `null` if the handshake has not yet completed.
|
||||||
|
String? get remoteVersion => _remoteVersion;
|
||||||
|
|
||||||
|
SSHTransport(
|
||||||
|
this.socket, {
|
||||||
|
this.isServer = false,
|
||||||
|
this.version = 'DartSSH_2.0',
|
||||||
|
this.printDebug,
|
||||||
|
this.printTrace,
|
||||||
|
this.algorithms = const SSHAlgorithms(),
|
||||||
|
this.onVerifyHostKey,
|
||||||
|
this.onReady,
|
||||||
|
this.onPacket,
|
||||||
|
}) {
|
||||||
|
_initSocket();
|
||||||
|
_startHandshake();
|
||||||
|
}
|
||||||
|
|
||||||
|
final _doneCompleter = Completer<void>();
|
||||||
|
|
||||||
|
/// Contains unprocessed data from the socket.
|
||||||
|
final _buffer = ChunkBuffer();
|
||||||
|
|
||||||
|
/// Contains decrypted packet data. May be partial.
|
||||||
|
final _decryptBuffer = ChunkBuffer();
|
||||||
|
|
||||||
|
/// Subscription to the socket's [Stream]. It should be closed when the
|
||||||
|
/// transport is closed.
|
||||||
|
StreamSubscription? _socketSubscription;
|
||||||
|
|
||||||
|
/// Identification string sent by us without trailing \r\n. For example,
|
||||||
|
/// "SSH-2.0-DartSSH_2.0".
|
||||||
|
String get _localVersion => 'SSH-2.0-$version';
|
||||||
|
|
||||||
|
/// Identification string sent by the other side. For example, "SSH-2.0-OpenSSH_7.4p1".
|
||||||
|
/// May be `null` if the handshake has not yet completed.
|
||||||
|
/// This is kept to compute [_exchangeHash]
|
||||||
|
String? _remoteVersion;
|
||||||
|
|
||||||
|
/// Payload of the [SSH_Message_KexInit] sent by us. Kept to compute the
|
||||||
|
/// exchange hash.
|
||||||
|
late Uint8List _localKexInit;
|
||||||
|
|
||||||
|
/// Payload of the [SSH_Message_KexInit] sent by the other side. Kept to
|
||||||
|
/// compute the exchange hash.
|
||||||
|
late Uint8List _remoteKexInit;
|
||||||
|
|
||||||
|
SSHKexType? _kexType;
|
||||||
|
|
||||||
|
SSHHostkeyType? _hostkeyType;
|
||||||
|
|
||||||
|
SSHCipherType? _clientCipherType;
|
||||||
|
|
||||||
|
SSHCipherType? _serverCipherType;
|
||||||
|
|
||||||
|
SSHMacType? _clientMacType;
|
||||||
|
|
||||||
|
SSHMacType? _serverMacType;
|
||||||
|
|
||||||
|
SSHKex? _kex;
|
||||||
|
|
||||||
|
/// [_exchangeHash] of the first key exchange is used as session identifier.
|
||||||
|
/// Used to derive the cipher IV, cipher key and MAC key.
|
||||||
|
Uint8List? _sessionId;
|
||||||
|
|
||||||
|
/// A hash value of various parameters (defined in rfc4253). Kept to derive the
|
||||||
|
/// cipher IV, cipher key and MAC key.
|
||||||
|
Uint8List? _exchangeHash;
|
||||||
|
|
||||||
|
/// Whether the hostkey of the server has been verified. This is always false
|
||||||
|
/// when the transport is acting as a server.
|
||||||
|
var _hostkeyVerified = false;
|
||||||
|
|
||||||
|
/// Shared secret derived from the key exchange process. Kept to derive the
|
||||||
|
/// cipher IV, cipher key and MAC key.
|
||||||
|
BigInt? _sharedSecret;
|
||||||
|
|
||||||
|
/// A [BlockCipher] to encrypt data sent to the other side.
|
||||||
|
BlockCipher? _encryptCipher;
|
||||||
|
|
||||||
|
/// A [BlockCipher] to decrypt data sent from the other side.
|
||||||
|
BlockCipher? _decryptCipher;
|
||||||
|
|
||||||
|
/// A [Mac] used to authenticate data sent to the other side.
|
||||||
|
Mac? _localMac;
|
||||||
|
|
||||||
|
/// A [Mac] used to authenticate data sent from the other side.
|
||||||
|
Mac? _remoteMac;
|
||||||
|
|
||||||
|
final _localPacketSN = SSHPacketSN.fromZero();
|
||||||
|
|
||||||
|
final _remotePacketSN = SSHPacketSN.fromZero();
|
||||||
|
|
||||||
|
void sendPacket(Uint8List data) {
|
||||||
|
if (isClosed) {
|
||||||
|
throw SSHStateError('Transport is closed');
|
||||||
|
}
|
||||||
|
final packetAlign = _encryptCipher == null
|
||||||
|
? SSHPacket.minAlign
|
||||||
|
: max(SSHPacket.minAlign, _encryptCipher!.blockSize);
|
||||||
|
|
||||||
|
final packet = SSHPacket.pack(data, align: packetAlign);
|
||||||
|
|
||||||
|
if (_encryptCipher == null) {
|
||||||
|
socket.sink.add(packet);
|
||||||
|
} else {
|
||||||
|
final mac = _localMac!;
|
||||||
|
mac.updateAll(_localPacketSN.value.toUint32());
|
||||||
|
mac.updateAll(packet);
|
||||||
|
|
||||||
|
final buffer = BytesBuilder(copy: false);
|
||||||
|
buffer.add(_encryptCipher!.processAll(packet));
|
||||||
|
buffer.add(mac.finish());
|
||||||
|
|
||||||
|
socket.sink.add(buffer.takeBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
_localPacketSN.increase();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
printDebug?.call('SSHTransport.close');
|
||||||
|
if (isClosed) return;
|
||||||
|
_socketSubscription?.cancel();
|
||||||
|
_socketSubscription = null;
|
||||||
|
_doneCompleter.complete();
|
||||||
|
socket.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
void closeWithError(SSHError error, [StackTrace? stackTrace]) {
|
||||||
|
printDebug?.call('SSHTransport.closeWithError $error');
|
||||||
|
if (isClosed) return;
|
||||||
|
_socketSubscription?.cancel();
|
||||||
|
_socketSubscription = null;
|
||||||
|
_doneCompleter.completeError(error, stackTrace ?? StackTrace.current);
|
||||||
|
socket.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _initSocket() {
|
||||||
|
_socketSubscription = socket.stream.listen(
|
||||||
|
_onSocketData,
|
||||||
|
onError: _onSocketError,
|
||||||
|
onDone: _onSocketDone,
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.done.catchError(_onSocketError);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSocketData(Uint8List data) {
|
||||||
|
_buffer.add(data);
|
||||||
|
try {
|
||||||
|
_processData();
|
||||||
|
} on SSHError catch (e, stackTrace) {
|
||||||
|
closeWithError(e, stackTrace);
|
||||||
|
} catch (e) {
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSocketError(Object error, StackTrace stackTrace) {
|
||||||
|
printDebug?.call('SSHTransport._onSocketError($error)');
|
||||||
|
closeWithError(SSHSocketError(error), stackTrace);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSocketDone() {
|
||||||
|
printDebug?.call('SSHTransport._onSocketDone');
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _processData() {
|
||||||
|
if (_remoteVersion == null) {
|
||||||
|
_processVersionExchange();
|
||||||
|
} else {
|
||||||
|
_processPackets();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _processVersionExchange() {
|
||||||
|
printDebug?.call('SSHTransport._processVersionExchange');
|
||||||
|
|
||||||
|
if (_buffer.length > 10240) {
|
||||||
|
throw SSHHandshakeError('Version exchange too long');
|
||||||
|
}
|
||||||
|
|
||||||
|
final bufferString = latin1.decode(_buffer.data);
|
||||||
|
|
||||||
|
// SSH version exchange is terminated by \r\n.
|
||||||
|
var index = bufferString.indexOf('\r\n');
|
||||||
|
if (index == -1) {
|
||||||
|
// In the (rare) case SSH-2 version string is terminated by \n only (observed on Synology DS120j 2021)
|
||||||
|
index = bufferString.indexOf('\n');
|
||||||
|
if (index == -1) {
|
||||||
|
throw SSHHandshakeError('Version exchange not terminated');
|
||||||
|
}
|
||||||
|
_buffer.consume(index + 1);
|
||||||
|
} else {
|
||||||
|
_buffer.consume(index + 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
final versionString = bufferString.substring(0, index);
|
||||||
|
if (!versionString.startsWith('SSH-2.0-')) {
|
||||||
|
socket.sink.add(latin1.encode('Protocol mismatch\r\n'));
|
||||||
|
throw SSHHandshakeError('Invalid version: $versionString');
|
||||||
|
}
|
||||||
|
|
||||||
|
printTrace?.call('<- $socket: $versionString');
|
||||||
|
printDebug?.call('SSHTransport._remoteVersion = "$versionString"');
|
||||||
|
_remoteVersion = versionString;
|
||||||
|
|
||||||
|
if (isServer) {
|
||||||
|
_sendKexInit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// There maybe more data in the buffer, so process it.
|
||||||
|
_processPackets();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process one or more SSH packets queued in [_buffer].
|
||||||
|
void _processPackets() {
|
||||||
|
printDebug?.call('SSHTransport._processPackets');
|
||||||
|
|
||||||
|
while (_buffer.isNotEmpty && !isClosed) {
|
||||||
|
final payload = _consumePacket();
|
||||||
|
if (payload == null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if (payload.length > SSHPacket.maxPayloadLength) {
|
||||||
|
// throw SSHPacketError('Packet too long: ${payload.length}');
|
||||||
|
// }
|
||||||
|
|
||||||
|
_handleMessage(payload);
|
||||||
|
|
||||||
|
_remotePacketSN.increase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a single SSH packet from the buffer. Returns payload of the packet
|
||||||
|
/// WITHOUT `packet length`, `padding length`, `padding` and `MAC`. Returns
|
||||||
|
/// `null` if there is not enough data in the buffer to read the packet.
|
||||||
|
Uint8List? _consumePacket() {
|
||||||
|
return _decryptCipher == null
|
||||||
|
? _consumeClearTextPacket()
|
||||||
|
: _consumeEncryptedPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List? _consumeClearTextPacket() {
|
||||||
|
printDebug?.call('SSHTransport._consumeClearTextPacket');
|
||||||
|
|
||||||
|
if (_buffer.length < 4) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final packetLength = SSHPacket.readPacketLength(_buffer.data);
|
||||||
|
_verifyPacketLength(packetLength);
|
||||||
|
|
||||||
|
if (_buffer.length < packetLength + 4) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final packet = _buffer.consume(packetLength + 4);
|
||||||
|
final paddingLength = SSHPacket.readPaddingLength(packet);
|
||||||
|
final payloadLength = packetLength - paddingLength - 1;
|
||||||
|
_verifyPacketPadding(payloadLength, paddingLength);
|
||||||
|
|
||||||
|
return Uint8List.sublistView(packet, 5, packet.length - paddingLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List? _consumeEncryptedPacket() {
|
||||||
|
printDebug?.call('SSHTransport._consumeEncryptedPacket');
|
||||||
|
|
||||||
|
final blockSize = _decryptCipher!.blockSize;
|
||||||
|
if (_buffer.length < blockSize) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_decryptBuffer.isEmpty) {
|
||||||
|
final firstBlock = _buffer.consume(blockSize);
|
||||||
|
_decryptBuffer.add(_decryptCipher!.process(firstBlock));
|
||||||
|
}
|
||||||
|
|
||||||
|
final packetLength = SSHPacket.readPacketLength(_decryptBuffer.data);
|
||||||
|
_verifyPacketLength(packetLength);
|
||||||
|
|
||||||
|
final macLength = _remoteMac!.macSize;
|
||||||
|
if (_buffer.length + _decryptBuffer.length < 4 + packetLength + macLength) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (_decryptBuffer.length < 4 + packetLength) {
|
||||||
|
final block = _buffer.consume(blockSize);
|
||||||
|
_decryptBuffer.add(_decryptCipher!.process(block));
|
||||||
|
}
|
||||||
|
|
||||||
|
final packet = _decryptBuffer.consume(packetLength + 4);
|
||||||
|
final paddingLength = SSHPacket.readPaddingLength(packet);
|
||||||
|
final payloadLength = packetLength - paddingLength - 1;
|
||||||
|
_verifyPacketPadding(payloadLength, paddingLength);
|
||||||
|
|
||||||
|
final mac = _buffer.consume(macLength);
|
||||||
|
_verifyPacketMac(packet, mac);
|
||||||
|
|
||||||
|
return Uint8List.sublistView(packet, 5, packet.length - paddingLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _verifyPacketLength(int packetLength) {
|
||||||
|
if (packetLength > SSHPacket.maxLength) {
|
||||||
|
throw SSHPacketError('Packet too long: $packetLength');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies that the padding of the packet is correct. Throws [SSHPacketError]
|
||||||
|
/// if the padding is incorrect.
|
||||||
|
void _verifyPacketPadding(int payloadLength, int paddingLength) {
|
||||||
|
final expectedPacketAlign = _decryptCipher == null
|
||||||
|
? SSHPacket.minAlign
|
||||||
|
: max(SSHPacket.minAlign, _decryptCipher!.blockSize);
|
||||||
|
|
||||||
|
final minPaddingLength = SSHPacket.paddingLength(
|
||||||
|
payloadLength,
|
||||||
|
align: expectedPacketAlign,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (paddingLength < minPaddingLength) {
|
||||||
|
throw SSHPacketError(
|
||||||
|
'Invalid padding length: $paddingLength, expected: $minPaddingLength',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies that the MAC of the packet is correct. Throws [SSHPacketError]
|
||||||
|
/// if the MAC is incorrect.
|
||||||
|
void _verifyPacketMac(Uint8List payload, Uint8List actualMac) {
|
||||||
|
final macSize = _remoteMac!.macSize;
|
||||||
|
if (actualMac.length != macSize) {
|
||||||
|
throw ArgumentError.value(actualMac, 'mac', 'Invalid MAC size');
|
||||||
|
}
|
||||||
|
|
||||||
|
_remoteMac!.updateAll(_remotePacketSN.value.toUint32());
|
||||||
|
_remoteMac!.updateAll(payload);
|
||||||
|
final expectedMac = _remoteMac!.finish();
|
||||||
|
|
||||||
|
if (!expectedMac.equals(actualMac)) {
|
||||||
|
throw SSHPacketError(
|
||||||
|
'MAC mismatch, expected: $expectedMac, actual: $actualMac',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _startHandshake() {
|
||||||
|
socket.sink.add(latin1.encode('$_localVersion\r\n'));
|
||||||
|
|
||||||
|
if (isClient) {
|
||||||
|
_sendKexInit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applyLocalKeys() {
|
||||||
|
final cipherType = isClient ? _clientCipherType : _serverCipherType;
|
||||||
|
if (cipherType == null) throw StateError('No cipher type selected');
|
||||||
|
|
||||||
|
_encryptCipher = cipherType.createCipher(
|
||||||
|
_deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.clientKey : SSHDeriveKeyType.serverKey,
|
||||||
|
cipherType.keySize,
|
||||||
|
),
|
||||||
|
_deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.clientIV : SSHDeriveKeyType.serverIV,
|
||||||
|
cipherType.ivSize,
|
||||||
|
),
|
||||||
|
forEncryption: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
final macType = isClient ? _clientMacType : _serverMacType;
|
||||||
|
if (macType == null) throw StateError('No MAC type selected');
|
||||||
|
|
||||||
|
final macKey = _deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.clientMacKey : SSHDeriveKeyType.serverMacKey,
|
||||||
|
macType.keySize,
|
||||||
|
);
|
||||||
|
|
||||||
|
_localMac = macType.createMac(macKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applyRemoteKeys() {
|
||||||
|
final cipherType = isClient ? _serverCipherType : _clientCipherType;
|
||||||
|
if (cipherType == null) throw StateError('No cipher type selected');
|
||||||
|
|
||||||
|
_decryptCipher = cipherType.createCipher(
|
||||||
|
_deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.serverKey : SSHDeriveKeyType.clientKey,
|
||||||
|
cipherType.keySize,
|
||||||
|
),
|
||||||
|
_deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.serverIV : SSHDeriveKeyType.clientIV,
|
||||||
|
cipherType.ivSize,
|
||||||
|
),
|
||||||
|
forEncryption: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
final macType = isClient ? _serverMacType : _clientMacType;
|
||||||
|
if (macType == null) throw StateError('No MAC type selected');
|
||||||
|
|
||||||
|
final macKey = _deriveKey(
|
||||||
|
isClient ? SSHDeriveKeyType.serverMacKey : SSHDeriveKeyType.clientMacKey,
|
||||||
|
macType.keySize,
|
||||||
|
);
|
||||||
|
_remoteMac = macType.createMac(macKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List _deriveKey(SSHDeriveKeyType keyType, int keySize) {
|
||||||
|
return SSHKexUtils.deriveKey(
|
||||||
|
digest: _kexType!.createDigest(),
|
||||||
|
sharedSecret: _sharedSecret!,
|
||||||
|
exchangeHash: _exchangeHash!,
|
||||||
|
keyType: keyType,
|
||||||
|
sessionId: _sessionId!,
|
||||||
|
keySize: keySize,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Composes the data blob to be signed by the client with its public key.
|
||||||
|
Uint8List composeChallenge({
|
||||||
|
required String username,
|
||||||
|
required String service,
|
||||||
|
required String publicKeyAlgorithm,
|
||||||
|
required Uint8List publicKey,
|
||||||
|
}) {
|
||||||
|
final writer = SSHMessageWriter();
|
||||||
|
writer.writeString(_sessionId!);
|
||||||
|
writer.writeUint8(SSH_Message_Userauth_Request.messageId);
|
||||||
|
writer.writeUtf8(username);
|
||||||
|
writer.writeUtf8(service);
|
||||||
|
writer.writeUtf8('publickey');
|
||||||
|
writer.writeBool(true);
|
||||||
|
writer.writeUtf8(publicKeyAlgorithm);
|
||||||
|
writer.writeString(publicKey);
|
||||||
|
return writer.takeBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _verifyHostkey({
|
||||||
|
required Uint8List keyBytes,
|
||||||
|
required Uint8List signatureBytes,
|
||||||
|
required Uint8List exchangeHash,
|
||||||
|
}) {
|
||||||
|
switch (_hostkeyType) {
|
||||||
|
case SSHHostkeyType.ed25519:
|
||||||
|
final publicKey = SSHEd25519PublicKey.decode(keyBytes);
|
||||||
|
final signature = SSHEd25519Signature.decode(signatureBytes);
|
||||||
|
return publicKey.verify(exchangeHash, signature);
|
||||||
|
case SSHHostkeyType.rsaSha1:
|
||||||
|
case SSHHostkeyType.rsaSha256:
|
||||||
|
case SSHHostkeyType.rsaSha512:
|
||||||
|
final publicKey = SSHRsaPublicKey.decode(keyBytes);
|
||||||
|
final signature = SSHRsaSignature.decode(signatureBytes);
|
||||||
|
return publicKey.verify(exchangeHash, signature);
|
||||||
|
case SSHHostkeyType.ecdsa256:
|
||||||
|
case SSHHostkeyType.ecdsa384:
|
||||||
|
case SSHHostkeyType.ecdsa521:
|
||||||
|
final publicKey = SSHEcdsaPublicKey.decode(keyBytes);
|
||||||
|
final signature = SSHEcdsaSignature.decode(signatureBytes);
|
||||||
|
return publicKey.verify(exchangeHash, signature);
|
||||||
|
case null:
|
||||||
|
throw StateError('No hostkey type negotiated');
|
||||||
|
default:
|
||||||
|
throw UnimplementedError('Unsupported hostkey type: $_hostkeyType');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendKexInit() {
|
||||||
|
printDebug?.call('SSHTransport._sendKexInit');
|
||||||
|
|
||||||
|
final message = SSH_Message_KexInit(
|
||||||
|
kexAlgorithms: algorithms.kex.toNameList(),
|
||||||
|
// kexAlgorithms: ['curve25519-sha256'],
|
||||||
|
serverHostKeyAlgorithms: algorithms.hostkey.toNameList(),
|
||||||
|
encryptionClientToServer: algorithms.cipher.toNameList(),
|
||||||
|
encryptionServerToClient: algorithms.cipher.toNameList(),
|
||||||
|
macClientToServer: algorithms.mac.toNameList(),
|
||||||
|
macServerToClient: algorithms.mac.toNameList(),
|
||||||
|
compressionClientToServer: ['none'],
|
||||||
|
compressionServerToClient: ['none'],
|
||||||
|
firstKexPacketFollows: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
final payload = message.encode();
|
||||||
|
_localKexInit = payload;
|
||||||
|
|
||||||
|
sendPacket(payload);
|
||||||
|
printTrace?.call('-> $socket: $message');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send diffie-hellman key exchange message. The exact message format depends
|
||||||
|
/// on the negotiated key exchange algorithm.
|
||||||
|
void _sendKexDHInit() {
|
||||||
|
printDebug?.call('SSHTransport._sendKexDHInit');
|
||||||
|
|
||||||
|
final kex = _kex;
|
||||||
|
late final SSHMessage message;
|
||||||
|
|
||||||
|
if (kex is SSHKexDH) {
|
||||||
|
message = SSH_Message_KexDH_Init(e: kex.e);
|
||||||
|
} else if (kex is SSHKexECDH) {
|
||||||
|
message = SSH_Message_KexECDH_Init(kex.publicKey);
|
||||||
|
} else {
|
||||||
|
throw StateError('No key exchange algorithm negotiated');
|
||||||
|
}
|
||||||
|
|
||||||
|
sendPacket(message.encode());
|
||||||
|
printTrace?.call('-> $socket: $message');
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendKexDHGexRequest() {
|
||||||
|
printDebug?.call('SSHTransport._sendKexDHGexRequest');
|
||||||
|
|
||||||
|
final message = SSH_Message_KexDH_GexRequest(
|
||||||
|
minN: SSHKexDH.gexMin,
|
||||||
|
preferredN: SSHKexDH.gexPref,
|
||||||
|
maxN: SSHKexDH.gexMax,
|
||||||
|
);
|
||||||
|
|
||||||
|
sendPacket(message.encode());
|
||||||
|
printTrace?.call('-> $socket: $message');
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendKexDHGexInit() {
|
||||||
|
printDebug?.call('SSHTransport._sendKexDHGexInit');
|
||||||
|
|
||||||
|
final kex = _kex;
|
||||||
|
if (kex is! SSHKexDH) {
|
||||||
|
throw StateError('kex is not SSHKexDH');
|
||||||
|
}
|
||||||
|
|
||||||
|
final message = SSH_Message_KexDH_GexInit(e: kex.e);
|
||||||
|
sendPacket(message.encode());
|
||||||
|
printTrace?.call('-> $socket: $message');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends [SSH_Message_NewKeys] message. After this message, all data sent
|
||||||
|
/// to the server should be encrypted with the keys negotiated in key exchange.
|
||||||
|
void _sendNewKeys() {
|
||||||
|
printDebug?.call('SSHTransport._sendNewKeys');
|
||||||
|
final message = SSH_Message_NewKeys();
|
||||||
|
printTrace?.call('-> $socket: $message');
|
||||||
|
sendPacket(message.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleMessage(Uint8List message) {
|
||||||
|
final messageId = SSHMessage.readMessageId(message);
|
||||||
|
switch (messageId) {
|
||||||
|
case SSH_Message_KexInit.messageId:
|
||||||
|
return _handleMessageKexInit(message);
|
||||||
|
case SSH_Message_KexDH_Reply.messageId:
|
||||||
|
case SSH_Message_KexDH_GexReply.messageId:
|
||||||
|
return _handleMessageKexReply(message);
|
||||||
|
case SSH_Message_NewKeys.messageId:
|
||||||
|
return _handleMessageNewKeys(message);
|
||||||
|
default:
|
||||||
|
onPacket?.call(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleMessageKexInit(Uint8List payload) {
|
||||||
|
printDebug?.call('SSHTransport._handleMessageKexInit');
|
||||||
|
|
||||||
|
final message = SSH_Message_KexInit.decode(payload);
|
||||||
|
printTrace?.call('<- $socket: $message');
|
||||||
|
_remoteKexInit = payload;
|
||||||
|
|
||||||
|
_kexType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.kex,
|
||||||
|
remoteAlgorithms: message.kexAlgorithms,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
_hostkeyType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.hostkey,
|
||||||
|
remoteAlgorithms: message.serverHostKeyAlgorithms,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
_clientCipherType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.cipher,
|
||||||
|
remoteAlgorithms: message.encryptionClientToServer,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
_serverCipherType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.cipher,
|
||||||
|
remoteAlgorithms: message.encryptionServerToClient,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
_clientMacType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.mac,
|
||||||
|
remoteAlgorithms: message.macClientToServer,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
_serverMacType = SSHKexUtils.selectAlgorithm(
|
||||||
|
localAlgorithms: algorithms.mac,
|
||||||
|
remoteAlgorithms: message.macServerToClient,
|
||||||
|
isServer: isServer,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (_kexType == null) {
|
||||||
|
throw StateError('No matching key exchange algorithm');
|
||||||
|
}
|
||||||
|
if (_hostkeyType == null) {
|
||||||
|
throw StateError('No matching host key algorithm');
|
||||||
|
}
|
||||||
|
if (_clientCipherType == null) {
|
||||||
|
throw StateError('No matching client cipher algorithm');
|
||||||
|
}
|
||||||
|
if (_serverCipherType == null) {
|
||||||
|
throw StateError('No matching server cipher algorithm');
|
||||||
|
}
|
||||||
|
if (_clientMacType == null) {
|
||||||
|
throw StateError('No matching client MAC algorithm');
|
||||||
|
}
|
||||||
|
if (_serverMacType == null) {
|
||||||
|
throw StateError('No matching server MAC algorithm');
|
||||||
|
}
|
||||||
|
|
||||||
|
printDebug?.call('SSHTransport._kexType: $_kexType');
|
||||||
|
printDebug?.call('SSHTransport._hostkeyType: $_hostkeyType');
|
||||||
|
printDebug?.call('SSHTransport._clientCipherType: $_clientCipherType');
|
||||||
|
printDebug?.call('SSHTransport._serverCipherType: $_serverCipherType');
|
||||||
|
printDebug?.call('SSHTransport._clientMacType: $_clientMacType');
|
||||||
|
printDebug?.call('SSHTransport._serverMacType: $_serverMacType');
|
||||||
|
|
||||||
|
switch (_kexType) {
|
||||||
|
case SSHKexType.x25519:
|
||||||
|
_kex = SSHKexX25519();
|
||||||
|
break;
|
||||||
|
case SSHKexType.nistp256:
|
||||||
|
_kex = SSHKexNist.p256();
|
||||||
|
break;
|
||||||
|
case SSHKexType.nistp384:
|
||||||
|
_kex = SSHKexNist.p384();
|
||||||
|
break;
|
||||||
|
case SSHKexType.nistp521:
|
||||||
|
_kex = SSHKexNist.p521();
|
||||||
|
break;
|
||||||
|
case SSHKexType.dh14Sha1:
|
||||||
|
case SSHKexType.dh14Sha256:
|
||||||
|
_kex = SSHKexDH.group14();
|
||||||
|
break;
|
||||||
|
case SSHKexType.dh1Sha1:
|
||||||
|
_kex = SSHKexDH.group1();
|
||||||
|
break;
|
||||||
|
case SSHKexType.dhGexSha1:
|
||||||
|
case SSHKexType.dhGexSha256:
|
||||||
|
if (isClient) _sendKexDHGexRequest();
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
throw UnimplementedError('$_kexType');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isClient) {
|
||||||
|
_sendKexDHInit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When client receives [SSH_Message_KexECDH_Reply], it should verify the
|
||||||
|
/// server's signature with the server's public key. Then send NEW_KEYS
|
||||||
|
/// message back to the server.
|
||||||
|
void _handleMessageKexReply(Uint8List payload) {
|
||||||
|
printDebug?.call('SSHTransport._handleMessageKexReply');
|
||||||
|
if (isServer) throw SSHStateError('Unexpected KEX_REPLY');
|
||||||
|
|
||||||
|
final kex = _kex;
|
||||||
|
final kexType = _kexType;
|
||||||
|
|
||||||
|
if (kexType == null) {
|
||||||
|
throw SSHStateError('kexType has not been negotiated');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kex == null) {
|
||||||
|
if (kexType.isGroupExchange == true) {
|
||||||
|
return _handleMessageKexGexReply(payload);
|
||||||
|
} else {
|
||||||
|
throw SSHStateError('No key exchange algorithm');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
late Uint8List hostkey;
|
||||||
|
late Uint8List hostSignature;
|
||||||
|
late Uint8List serverKexKey;
|
||||||
|
late Uint8List clientKexKey;
|
||||||
|
late BigInt sharedSecret;
|
||||||
|
|
||||||
|
if (kex is SSHKexDH) {
|
||||||
|
final message = kexType.isGroupExchange
|
||||||
|
? SSH_Message_KexDH_GexReply.decode(payload)
|
||||||
|
: SSH_Message_KexDH_Reply.decode(payload);
|
||||||
|
printTrace?.call('<- $socket: $message');
|
||||||
|
hostkey = message.hostPublicKey;
|
||||||
|
hostSignature = message.signature;
|
||||||
|
serverKexKey = encodeBigInt(message.f);
|
||||||
|
clientKexKey = encodeBigInt(kex.e);
|
||||||
|
sharedSecret = kex.computeSecret(message.f);
|
||||||
|
} else if (kex is SSHKexECDH) {
|
||||||
|
final message = SSH_Message_KexECDH_Reply.decode(payload);
|
||||||
|
printTrace?.call('<- $socket: $message');
|
||||||
|
hostkey = message.hostPublicKey;
|
||||||
|
hostSignature = message.signature;
|
||||||
|
serverKexKey = message.ecdhPublicKey;
|
||||||
|
clientKexKey = kex.publicKey;
|
||||||
|
sharedSecret = kex.computeSecret(message.ecdhPublicKey);
|
||||||
|
} else {
|
||||||
|
throw UnimplementedError('$kex');
|
||||||
|
}
|
||||||
|
|
||||||
|
final exchangeHash = SSHKexUtils.computeExchangeHash(
|
||||||
|
digest: _kexType!.createDigest(),
|
||||||
|
groupExchange: kexType.isGroupExchange ? kex as SSHKexDH : null,
|
||||||
|
clientVersion: _localVersion,
|
||||||
|
serverVersion: _remoteVersion!,
|
||||||
|
clientKexInit: _localKexInit,
|
||||||
|
serverKexInit: _remoteKexInit,
|
||||||
|
hostKey: hostkey,
|
||||||
|
clientPublicKey: clientKexKey,
|
||||||
|
serverPublicKey: serverKexKey,
|
||||||
|
sharedSecret: sharedSecret,
|
||||||
|
);
|
||||||
|
|
||||||
|
final verified = _verifyHostkey(
|
||||||
|
keyBytes: hostkey,
|
||||||
|
signatureBytes: hostSignature,
|
||||||
|
exchangeHash: exchangeHash,
|
||||||
|
);
|
||||||
|
if (!verified) throw SSHHostkeyError('Signature verification failed');
|
||||||
|
|
||||||
|
_exchangeHash = exchangeHash;
|
||||||
|
_sessionId ??= exchangeHash;
|
||||||
|
_sharedSecret = sharedSecret;
|
||||||
|
|
||||||
|
final fingerprint = MD5Digest().process(hostkey);
|
||||||
|
|
||||||
|
if (_hostkeyVerified) {
|
||||||
|
_sendNewKeys();
|
||||||
|
_applyLocalKeys();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final userVerified = onVerifyHostKey != null
|
||||||
|
? onVerifyHostKey!(_hostkeyType!.name, fingerprint)
|
||||||
|
: true;
|
||||||
|
|
||||||
|
Future.value(userVerified).then(
|
||||||
|
(verified) {
|
||||||
|
if (!verified) {
|
||||||
|
closeWithError(SSHHostkeyError('Hostkey verification failed'));
|
||||||
|
} else {
|
||||||
|
_hostkeyVerified = true;
|
||||||
|
_sendNewKeys();
|
||||||
|
_applyLocalKeys();
|
||||||
|
onReady?.call();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error) {
|
||||||
|
closeWithError(error);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleMessageKexGexReply(Uint8List payload) {
|
||||||
|
printDebug?.call('SSHTransport._handleMessageKexGexReply');
|
||||||
|
if (isServer) throw SSHStateError('Unexpected KEX_GEX_REPLY');
|
||||||
|
|
||||||
|
final message = SSH_Message_KexDH_GexGroup.decode(payload);
|
||||||
|
printTrace?.call('<- $socket: $message');
|
||||||
|
|
||||||
|
_kex = SSHKexDH(p: message.p, g: message.g, secretBits: 256);
|
||||||
|
_sendKexDHGexInit();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleMessageNewKeys(Uint8List message) {
|
||||||
|
printDebug?.call('SSHTransport._handleMessageNewKeys');
|
||||||
|
printTrace?.call('<- $socket: SSH_Message_NewKeys');
|
||||||
|
_applyRemoteKeys();
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
enum SSHAuthMethod {
|
||||||
|
none,
|
||||||
|
password,
|
||||||
|
publicKey,
|
||||||
|
keyboardInteractive,
|
||||||
|
// hostbased,
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHAuthMethodX on SSHAuthMethod {
|
||||||
|
String get name {
|
||||||
|
switch (this) {
|
||||||
|
case SSHAuthMethod.none:
|
||||||
|
return 'none';
|
||||||
|
case SSHAuthMethod.password:
|
||||||
|
return 'password';
|
||||||
|
case SSHAuthMethod.publicKey:
|
||||||
|
return 'publickey';
|
||||||
|
case SSHAuthMethod.keyboardInteractive:
|
||||||
|
return 'keyboard-interactive';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHUserInfoRequest {
|
||||||
|
SSHUserInfoRequest(this.name, this.instruction, this.prompts);
|
||||||
|
|
||||||
|
/// Name of the request. For example, ""Password Expired".
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// Instructions for the user. For example, "Please enter your password."
|
||||||
|
final String instruction;
|
||||||
|
|
||||||
|
/// List of prompts.
|
||||||
|
final List<SSHUserInfoPrompt> prompts;
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHUserInfoPrompt {
|
||||||
|
SSHUserInfoPrompt(this.promptText, this.echo);
|
||||||
|
|
||||||
|
/// The prompt string. For example, "Password: ".
|
||||||
|
final String promptText;
|
||||||
|
|
||||||
|
/// Indicates whether or not the user input should be echoed as characters are typed.
|
||||||
|
final bool echo;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => '$runtimeType(prompt: $promptText, echo: $echo)';
|
||||||
|
}
|
||||||
|
|
||||||
|
class SSHChangePasswordResponse {
|
||||||
|
SSHChangePasswordResponse(this.oldPassword, this.newPassword);
|
||||||
|
|
||||||
|
/// Old password of the user.
|
||||||
|
final String oldPassword;
|
||||||
|
|
||||||
|
/// New password of the user.
|
||||||
|
final String newPassword;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'dart:collection';
|
||||||
|
|
||||||
|
/// A queue that consumers can wait asynchronously for items to be added.
|
||||||
|
class AsyncQueue<T> {
|
||||||
|
final _data = Queue<T>();
|
||||||
|
|
||||||
|
final _completers = Queue<Completer<T>>();
|
||||||
|
|
||||||
|
/// The length of the queue.
|
||||||
|
int get length => _completers.length;
|
||||||
|
|
||||||
|
/// Return true if the queue has consumers waiting for items.
|
||||||
|
bool get hasWaiters => _completers.isNotEmpty;
|
||||||
|
|
||||||
|
/// Returns a [Future] that completes when an item is added to the queue.
|
||||||
|
FutureOr<T> get next {
|
||||||
|
if (_data.isNotEmpty) {
|
||||||
|
return _data.removeFirst();
|
||||||
|
} else {
|
||||||
|
final completer = Completer<T>();
|
||||||
|
_completers.add(completer);
|
||||||
|
return completer.future;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds an item to the queue.
|
||||||
|
void add(T value) {
|
||||||
|
if (_completers.isNotEmpty) {
|
||||||
|
_completers.removeFirst().complete(value);
|
||||||
|
} else {
|
||||||
|
_data.add(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1369
File diff suppressed because it is too large.
Load diff
+84
@@ -0,0 +1,84 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
|
final _byteMask = BigInt.from(0xff);
|
||||||
|
final _negativeFlag = BigInt.from(0x80);
|
||||||
|
|
||||||
|
/// Decode a big integer with arbitrary sign.
|
||||||
|
/// When:
|
||||||
|
/// sign == 0: Zero regardless of magnitude
|
||||||
|
/// sign < 0: Negative
|
||||||
|
/// sign > 0: Positive
|
||||||
|
@internal
|
||||||
|
BigInt decodeBigIntWithSign(int sign, List<int> magnitude) {
|
||||||
|
if (sign == 0) {
|
||||||
|
return BigInt.zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInt result;
|
||||||
|
|
||||||
|
if (magnitude.length == 1) {
|
||||||
|
result = BigInt.from(magnitude[0]);
|
||||||
|
} else {
|
||||||
|
result = BigInt.from(0);
|
||||||
|
for (var i = 0; i < magnitude.length; i++) {
|
||||||
|
var item = magnitude[magnitude.length - i - 1];
|
||||||
|
result |= (BigInt.from(item) << (8 * i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result != BigInt.zero) {
|
||||||
|
result = sign < 0
|
||||||
|
? result.toSigned(result.bitLength)
|
||||||
|
: result.toUnsigned(result.bitLength);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode a BigInt into bytes using big-endian encoding.
|
||||||
|
/// It encodes the integer to a minimal twos-compliment integer as defined by
|
||||||
|
/// ASN.1
|
||||||
|
@internal
|
||||||
|
Uint8List encodeBigInt(BigInt? number) {
|
||||||
|
if (number == BigInt.zero) {
|
||||||
|
return Uint8List.fromList([0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
int needsPaddingByte;
|
||||||
|
int rawSize;
|
||||||
|
|
||||||
|
if (number! > BigInt.zero) {
|
||||||
|
rawSize = (number.bitLength + 7) >> 3;
|
||||||
|
needsPaddingByte =
|
||||||
|
((number >> (rawSize - 1) * 8) & _negativeFlag) == _negativeFlag
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
} else {
|
||||||
|
needsPaddingByte = 0;
|
||||||
|
rawSize = (number.bitLength + 8) >> 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
final size = rawSize + needsPaddingByte;
|
||||||
|
var result = Uint8List(size);
|
||||||
|
for (var i = 0; i < rawSize; i++) {
|
||||||
|
result[size - i - 1] = (number! & _byteMask).toInt();
|
||||||
|
number = number >> 8;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode as Big Endian unsigned byte array.
|
||||||
|
@internal
|
||||||
|
Uint8List encodeBigIntAsUnsigned(BigInt number) {
|
||||||
|
if (number == BigInt.zero) {
|
||||||
|
return Uint8List.fromList([0]);
|
||||||
|
}
|
||||||
|
var size = number.bitLength + (number.isNegative ? 8 : 7) >> 3;
|
||||||
|
var result = Uint8List(size);
|
||||||
|
for (var i = 0; i < size; i++) {
|
||||||
|
result[size - i - 1] = (number & _byteMask).toInt();
|
||||||
|
number = number >> 8;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
/// A buffer that can queue chunks of data and consume parts or all of them as
|
||||||
|
/// needed. Primarily used for reading data from a socket.
|
||||||
|
class ChunkBuffer {
|
||||||
|
var _buffer = Uint8List(0);
|
||||||
|
|
||||||
|
void add(Uint8List data) {
|
||||||
|
if (_buffer.isEmpty) {
|
||||||
|
_buffer = data;
|
||||||
|
} else {
|
||||||
|
var newBuffer = Uint8List(data.length + _buffer.length);
|
||||||
|
newBuffer.setRange(0, _buffer.length, _buffer);
|
||||||
|
newBuffer.setRange(_buffer.length, newBuffer.length, data);
|
||||||
|
_buffer = newBuffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List consume([int? length]) {
|
||||||
|
if (length == null) {
|
||||||
|
final result = _buffer;
|
||||||
|
_buffer = Uint8List(0);
|
||||||
|
return result;
|
||||||
|
} else {
|
||||||
|
final result = Uint8List.sublistView(data, 0, length);
|
||||||
|
_buffer = Uint8List.sublistView(data, length, data.length);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear() {
|
||||||
|
_buffer = Uint8List(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List get data {
|
||||||
|
return _buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List view(int start, int length) {
|
||||||
|
return _buffer.sublist(start, start + length);
|
||||||
|
}
|
||||||
|
|
||||||
|
int get length {
|
||||||
|
return _buffer.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isEmpty {
|
||||||
|
return _buffer.isEmpty;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isNotEmpty {
|
||||||
|
return _buffer.isNotEmpty;
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteData get byteData {
|
||||||
|
return ByteData.sublistView(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'SSHChunkBuffer(length: $length)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:pointycastle/pointycastle.dart';
|
||||||
|
|
||||||
|
extension BlockCipherX on BlockCipher {
|
||||||
|
Uint8List processAll(Uint8List data) {
|
||||||
|
final result = Uint8List(data.length);
|
||||||
|
|
||||||
|
if (data.length % blockSize != 0) {
|
||||||
|
throw FormatException('input ${data.length} not multiple of $blockSize');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var offset = 0; offset < data.length; offset += blockSize) {
|
||||||
|
processBlock(data, offset, result, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension MacX on Mac {
|
||||||
|
void updateAll(Uint8List data) {
|
||||||
|
update(data, 0, data.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List finish() {
|
||||||
|
final result = Uint8List(macSize);
|
||||||
|
final resuitLength = doFinal(result, 0);
|
||||||
|
if (resuitLength != macSize) throw FormatException('mac size mismatch');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
extension IntX on int {
|
||||||
|
/// Returns a [Uint8List] with the bytes of the integer encoded in [endian].
|
||||||
|
Uint8List toUint32([Endian endian = Endian.big]) {
|
||||||
|
final result = ByteData(4);
|
||||||
|
result.setUint32(0, this, endian);
|
||||||
|
return result.buffer.asUint8List();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a [Uint8List] with the bytes of the integer encoded in [endian].
|
||||||
|
Uint8List toUint64([Endian endian = Endian.big]) {
|
||||||
|
final result = ByteData(8);
|
||||||
|
result.setUint64(0, this, endian);
|
||||||
|
return result.buffer.asUint8List();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the octal representation of this integer.
|
||||||
|
String toOctal() {
|
||||||
|
return toRadixString(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a colon-separated hex representation of this integer.
|
||||||
|
String toColonHex() {
|
||||||
|
return toRadixString(16)
|
||||||
|
.padLeft(8, '0')
|
||||||
|
.replaceAllMapped(RegExp(r'(..)'), (match) => ':${match[1]}');
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
Uint8List randomBytes(int length) {
|
||||||
|
final random = Random();
|
||||||
|
final bytes = Uint8List(length);
|
||||||
|
for (var i = 0; i < length; i++) {
|
||||||
|
bytes[i] = random.nextInt(255);
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
extension ListX<T> on List<T> {
|
||||||
|
bool equals(List<T> other) {
|
||||||
|
if (other.length != length) return false;
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
if (this[i] != other[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
+150
@@ -0,0 +1,150 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
|
class MaxChunkSize extends StreamTransformerBase<Uint8List, Uint8List> {
|
||||||
|
MaxChunkSize(this.size);
|
||||||
|
|
||||||
|
final int size;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Uint8List> bind(Stream<Uint8List> stream) async* {
|
||||||
|
await for (var chunk in stream) {
|
||||||
|
if (chunk.length < size) {
|
||||||
|
yield chunk;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
final blocks = chunk.length ~/ size;
|
||||||
|
|
||||||
|
for (var i = 0; i < blocks; i++) {
|
||||||
|
yield Uint8List.sublistView(chunk, i * size, (i + 1) * size);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (blocks * size < chunk.length) {
|
||||||
|
yield Uint8List.sublistView(chunk, blocks * size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MinChunkSize extends StreamTransformerBase<Uint8List, Uint8List> {
|
||||||
|
MinChunkSize(this.size);
|
||||||
|
|
||||||
|
final int size;
|
||||||
|
|
||||||
|
var _yielded = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Uint8List> bind(Stream<Uint8List> stream) async* {
|
||||||
|
var buffer = BytesBuilder(copy: false);
|
||||||
|
|
||||||
|
await for (var chunk in stream) {
|
||||||
|
buffer.add(chunk);
|
||||||
|
|
||||||
|
if (buffer.length < size) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield buffer.takeBytes();
|
||||||
|
_yielded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (buffer.isNotEmpty || !_yielded) {
|
||||||
|
yield buffer.takeBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A helper class that can be used to read data from a data stream on demand.
|
||||||
|
abstract class StreamConsumerBase<T> {
|
||||||
|
/// Creates a new [StreamConsumer] that reads from [stream].
|
||||||
|
///
|
||||||
|
/// The underlying [stream] is paused during calls to [read].
|
||||||
|
StreamConsumerBase(Stream<T> stream) : _stream = StreamIterator(stream);
|
||||||
|
|
||||||
|
/// The underlying stream being read from.
|
||||||
|
final StreamIterator<T> _stream;
|
||||||
|
|
||||||
|
/// The current chunk being read from. `null` when the next chunk needs to be
|
||||||
|
/// read from the stream.
|
||||||
|
T? _currentChunk;
|
||||||
|
|
||||||
|
/// The amount of bytes that have been read from [_currentChunk].
|
||||||
|
var _currentOffset = 0;
|
||||||
|
|
||||||
|
/// Returns the length of type [T].
|
||||||
|
@protected
|
||||||
|
int getLength(T chunk);
|
||||||
|
|
||||||
|
/// Returns a sublist view of type [T] from [start] to [end].
|
||||||
|
@protected
|
||||||
|
T getSublistView(T chunk, int start, int end);
|
||||||
|
|
||||||
|
/// Reads up to [size] bytes from the stream.
|
||||||
|
///
|
||||||
|
/// The returned data may be less than [size] if the end of the stream is
|
||||||
|
/// reached or if chunk boundaries are encountered.
|
||||||
|
///
|
||||||
|
/// Returns `null` if the end of the stream is reached.
|
||||||
|
Future<T?> read(int size) async {
|
||||||
|
if (_currentChunk == null) {
|
||||||
|
if (!await _stream.moveNext()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_currentChunk = _stream.current;
|
||||||
|
_currentOffset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fast path for the case where [_currentChunk] can be directly returned
|
||||||
|
/// without creating a sublist view.
|
||||||
|
if (_currentOffset == 0 && size >= getLength(_currentChunk as T)) {
|
||||||
|
final result = _currentChunk;
|
||||||
|
_currentChunk = null;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
final effectSize = min(
|
||||||
|
size,
|
||||||
|
getLength(_currentChunk as T) - _currentOffset,
|
||||||
|
);
|
||||||
|
|
||||||
|
final result = getSublistView(
|
||||||
|
_currentChunk as T,
|
||||||
|
_currentOffset,
|
||||||
|
_currentOffset + effectSize,
|
||||||
|
);
|
||||||
|
|
||||||
|
_currentOffset += effectSize;
|
||||||
|
|
||||||
|
if (_currentOffset >= getLength(_currentChunk as T)) {
|
||||||
|
_currentChunk = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dispose the consumer and cancel the underlying stream.
|
||||||
|
Future<void> cancel() async {
|
||||||
|
await _stream.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A helper class that can be used to read data from a byte stream on demand.
|
||||||
|
class StreamConsumer extends StreamConsumerBase<Uint8List> {
|
||||||
|
StreamConsumer(super.stream);
|
||||||
|
|
||||||
|
@override
|
||||||
|
int getLength(Uint8List chunk) {
|
||||||
|
return chunk.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Uint8List getSublistView(Uint8List chunk, int start, int end) {
|
||||||
|
return Uint8List.sublistView(chunk, start, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
extension StirngX on String {
|
||||||
|
int get octal => int.parse(this, radix: 8);
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
Uint8List utf8Encode(String input) {
|
||||||
|
return Utf8Encoder().convert(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
String utf8Decode(Uint8List input) {
|
||||||
|
return Utf8Decoder().convert(input);
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
Vendored
+23
@@ -0,0 +1,23 @@
|
|||||||
|
name: dartssh2
|
||||||
|
version: 2.11.0
|
||||||
|
description: SSH and SFTP client written in pure Dart, aiming to be feature-rich as well as easy to use.
|
||||||
|
homepage: https://github.com/TerminalStudio/dartssh2
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: ">=2.17.0 <4.0.0"
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
asn1lib: ^1.5.3
|
||||||
|
convert: ^3.1.1
|
||||||
|
meta: ^1.15.0
|
||||||
|
pointycastle: ^3.9.1
|
||||||
|
pinenacl: ^0.6.0
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
build_runner: ^2.4.12
|
||||||
|
dart_code_metrics_presets: ^2.15.0
|
||||||
|
lints: ">=4.0.0 <6.0.0"
|
||||||
|
test: ^1.25.8
|
||||||
|
|
||||||
|
false_secrets:
|
||||||
|
- test
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
|
||||||
|
1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQQSA8zUPX0QP2Gd20hm2u4XA1ZwTAVe
|
||||||
|
zH/o9x8/RUji9BzzEL5k+apPwKHV6iXe7coRlun8ZeYqB0VjqodqgM5yAAAAuNM7tzfTO7
|
||||||
|
c3AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBIDzNQ9fRA/YZ3b
|
||||||
|
SGba7hcDVnBMBV7Mf+j3Hz9FSOL0HPMQvmT5qk/AodXqJd7tyhGW6fxl5ioHRWOqh2qAzn
|
||||||
|
IAAAAgdgkPZYI74SpmM9mhEAlquDKlPh7lejy7eEXMshzBTYgAAAAZamZvdXR0c0BVU0FK
|
||||||
|
Rk9VVFRTTS5sb2NhbAECAwQFBgc=
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBIDzNQ9fRA/YZ3bSGba7hcDVnBMBV7Mf+j3Hz9FSOL0HPMQvmT5qk/AodXqJd7tyhGW6fxl5ioHRWOqh2qAznI= jfoutts@USAJFOUTTSM.local
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
|
||||||
|
1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQR6CRv2GHU23gai7jw8YQ5IwOj09tOS
|
||||||
|
MoG6b6hRQnC9BseB427xHD2y4xYUZeOoeD+k5vAgWzG5XSis/U1mEWf0AAAAuOLU2yri1N
|
||||||
|
sqAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHoJG/YYdTbeBqLu
|
||||||
|
PDxhDkjA6PT205IygbpvqFFCcL0Gx4HjbvEcPbLjFhRl46h4P6Tm8CBbMbldKKz9TWYRZ/
|
||||||
|
QAAAAhAMOqFkndoggSsAYprv9Ur+sHi4LVhJ0VjTp4CHi9+nriAAAAGWpmb3V0dHNAVVNB
|
||||||
|
SkZPVVRUU00ubG9jYWwBAgMEBQY=
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHoJG/YYdTbeBqLuPDxhDkjA6PT205IygbpvqFFCcL0Gx4HjbvEcPbLjFhRl46h4P6Tm8CBbMbldKKz9TWYRZ/Q= jfoutts@USAJFOUTTSM.local
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAiAAAABNlY2RzYS
|
||||||
|
1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRSnxUwiMy7mxlPapzJSLYiONwDGnz+
|
||||||
|
auFw1m5FQ8+5INYrhUZF3WPFRkoObFFHrRMWyfUCGdxAgnbftSGWRWPFli1Lf60ylQTI9i
|
||||||
|
0dfUaUIhP2flMR2gDWvDrh5Czn7/AAAADo9vJYo/byWKMAAAATZWNkc2Etc2hhMi1uaXN0
|
||||||
|
cDM4NAAAAAhuaXN0cDM4NAAAAGEEUp8VMIjMu5sZT2qcyUi2IjjcAxp8/mrhcNZuRUPPuS
|
||||||
|
DWK4VGRd1jxUZKDmxRR60TFsn1AhncQIJ237UhlkVjxZYtS3+tMpUEyPYtHX1GlCIT9n5T
|
||||||
|
EdoA1rw64eQs5+/wAAAAMQDz4scmpkYxgdTcvgTgaWMSnDrXIWNWFEGfIZOJTxITvoAT6f
|
||||||
|
UJig+lGSNXRGdFw6EAAAAZamZvdXR0c0BVU0FKRk9VVFRTTS5sb2NhbAECAwQFBg==
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBFKfFTCIzLubGU9qnMlItiI43AMafP5q4XDWbkVDz7kg1iuFRkXdY8VGSg5sUUetExbJ9QIZ3ECCdt+1IZZFY8WWLUt/rTKVBMj2LR19RpQiE/Z+UxHaANa8OuHkLOfv8A== jfoutts@USAJFOUTTSM.local
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAiAAAABNlY2RzYS
|
||||||
|
1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQT0F6vCdx5FhEP4/Ydl1AOwYwJgpGeu
|
||||||
|
iDLxbqe11tAtauIFHMNEGPWOr8N0b+1iARQhIHO++iY8IBjQCGva3FT3jf14I+VS1bW1hN
|
||||||
|
Xo7Fpq+4zuZjWzIQOf/gQ+0ArY7yYAAADowut4MMLreDAAAAATZWNkc2Etc2hhMi1uaXN0
|
||||||
|
cDM4NAAAAAhuaXN0cDM4NAAAAGEE9BerwnceRYRD+P2HZdQDsGMCYKRnrogy8W6ntdbQLW
|
||||||
|
riBRzDRBj1jq/DdG/tYgEUISBzvvomPCAY0Ahr2txU9439eCPlUtW1tYTV6OxaavuM7mY1
|
||||||
|
syEDn/4EPtAK2O8mAAAAMQDcQgSdqB9LNIKBwvQKUIpp+VvXiWspnuxjcutKmhO0sbHR5j
|
||||||
|
wq+yO8ZkBR8ZPyE8AAAAAZamZvdXR0c0BVU0FKRk9VVFRTTS5sb2NhbAECAwQFBg==
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBPQXq8J3HkWEQ/j9h2XUA7BjAmCkZ66IMvFup7XW0C1q4gUcw0QY9Y6vw3Rv7WIBFCEgc776JjwgGNAIa9rcVPeN/Xgj5VLVtbWE1ejsWmr7jO5mNbMhA5/+BD7QCtjvJg== jfoutts@USAJFOUTTSM.local
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAArAAAABNlY2RzYS
|
||||||
|
1zaGEyLW5pc3RwNTIxAAAACG5pc3RwNTIxAAAAhQQAs81G8m/qvEcIv9vtU+5MLmnH7OSe
|
||||||
|
jnXT+SQP1rVN07Cz/Q04gk2GaCf9xDCRoS+61sd5ebxRUBONJZsZPoVxxoMA81EcO3g0H2
|
||||||
|
YmYCgQ4EAZgEuFhEXybt/MygZnXleDrsv+bFSBo09b5ANUXsZ4/fLVLk9CI4N3mTivkmyP
|
||||||
|
K6f0F8cAAAEYD8pDVg/KQ1YAAAATZWNkc2Etc2hhMi1uaXN0cDUyMQAAAAhuaXN0cDUyMQ
|
||||||
|
AAAIUEALPNRvJv6rxHCL/b7VPuTC5px+zkno510/kkD9a1TdOws/0NOIJNhmgn/cQwkaEv
|
||||||
|
utbHeXm8UVATjSWbGT6FccaDAPNRHDt4NB9mJmAoEOBAGYBLhYRF8m7fzMoGZ15Xg67L/m
|
||||||
|
xUgaNPW+QDVF7GeP3y1S5PQiODd5k4r5Jsjyun9BfHAAAAQgE/WWa/K2kJn8zctAwyBBPI
|
||||||
|
cycvhKpRovCKnXLAxOv0tKGQki98S/FEswfF2pVbcMIysss7ujM/HIiZQExXZvzPOAAAAB
|
||||||
|
lqZm91dHRzQFVTQUpGT1VUVFNNLmxvY2FsAQ==
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user