diff --git a/analysis_options.yaml b/analysis_options.yaml index 0abcf92..62c7caf 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -8,6 +8,7 @@ analyzer: exclude: - build/** + - third_party/** - android/** - ios/** - web/** diff --git a/pubspec.yaml b/pubspec.yaml index 93b1517..f7d54e8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -6,7 +6,8 @@ environment: sdk: ">=3.0.0 <4.0.0" dependencies: - dartssh2: 2.8.2 # 锁定版本:2.11.0 与新版 Dart SDK 类型提升不兼容,编译失败 + dartssh2: + path: third_party/dartssh2 xterm: ^4.0.0 dio: ^5.4.0 archive: ^3.6.0 diff --git a/third_party/dartssh2/CHANGELOG.md b/third_party/dartssh2/CHANGELOG.md new file mode 100644 index 0000000..8ca764f --- /dev/null +++ b/third_party/dartssh2/CHANGELOG.md @@ -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>` 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` 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 \ No newline at end of file diff --git a/third_party/dartssh2/LICENSE b/third_party/dartssh2/LICENSE new file mode 100644 index 0000000..3754132 --- /dev/null +++ b/third_party/dartssh2/LICENSE @@ -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. diff --git a/third_party/dartssh2/README.md b/third_party/dartssh2/README.md new file mode 100644 index 0000000..6ee4037 --- /dev/null +++ b/third_party/dartssh2/README.md @@ -0,0 +1,442 @@ + +

DartSSH 2

+ + +

+ + + + + + + + + + + + + + + + +

+ +

+SSH and SFTP client written in pure Dart, aiming to be feature-rich as well as easy to use. +

+ +> **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 + + + + + + + + + + + + + + + + + + + +
+ ServerBox + + Ssh! No Ports + + DartShell +
+ ServerBox interface displaying connection management options + ServerBox user interface for server control and monitoring + + + Ssh! No Ports demo showcasing SSH connectivity without open ports + + + dartShell displaying terminal and session information for SSH operations +
+ + +> 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: + +# 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: '', + onPasswordRequest: () => '', +); +``` + +> `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().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>().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>().pipe(socket); + socket.pipe(connection.sink); +} +``` + +### Authenticate with public keys + +```dart +final client = SSHClient( + socket, + 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('', ''); +print(keys); +``` + +Decrypt PEM file with [`compute`](https://api.flutter.dev/flutter/foundation/compute-constant.html) in Flutter + +```dart +List decryptKeyPairs(List args) { + return SSHKeyPair.fromPem(args[0], args[1]); +} + +final keypairs = await compute(decryptKeyPairs, ['', '']); +``` + +### 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('', 22), + username: '...', + onPasswordRequest: () => '...', +); + +final client = SSHClient( + await jumpServer.forwardLocal('', 22), + username: '...', + onPasswordRequest: () => '...', +); + +print(utf8.decode(await client.run('hostname'))); // -> hostname of +``` +} + + +## 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 diff --git a/third_party/dartssh2/analysis_options.yaml b/third_party/dartssh2/analysis_options.yaml new file mode 100644 index 0000000..1e17640 --- /dev/null +++ b/third_party/dartssh2/analysis_options.yaml @@ -0,0 +1,9 @@ +include: package:lints/recommended.yaml + +linter: + rules: + prefer_function_declarations_over_variables: false + +analyzer: + plugins: + - dart_code_metrics_presets \ No newline at end of file diff --git a/third_party/dartssh2/example/example.dart b/third_party/dartssh2/example/example.dart new file mode 100644 index 0000000..935cd1d --- /dev/null +++ b/third_party/dartssh2/example/example.dart @@ -0,0 +1,24 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/execute.dart b/third_party/dartssh2/example/execute.dart new file mode 100644 index 0000000..b4df8f7 --- /dev/null +++ b/third_party/dartssh2/example/execute.dart @@ -0,0 +1,25 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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().pipe(session.stdin); + + await session.done; + print('done'); + + client.close(); + await client.done; +} diff --git a/third_party/dartssh2/example/forward_local.dart b/third_party/dartssh2/example/forward_local.dart new file mode 100644 index 0000000..75257d0 --- /dev/null +++ b/third_party/dartssh2/example/forward_local.dart @@ -0,0 +1,32 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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>().pipe(socket); + socket.cast>().pipe(forward.sink); + } + + client.close(); + await client.done; +} diff --git a/third_party/dartssh2/example/forward_remote.dart b/third_party/dartssh2/example/forward_remote.dart new file mode 100644 index 0000000..25a13c4 --- /dev/null +++ b/third_party/dartssh2/example/forward_remote.dart @@ -0,0 +1,37 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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>().pipe(socket); + socket.cast>().pipe(connection.sink); + } + + client.close(); + await client.done; +} diff --git a/third_party/dartssh2/example/pubkey.dart b/third_party/dartssh2/example/pubkey.dart new file mode 100644 index 0000000..950e0ee --- /dev/null +++ b/third_party/dartssh2/example/pubkey.dart @@ -0,0 +1,23 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_filetype.dart b/third_party/dartssh2/example/sftp_filetype.dart new file mode 100644 index 0000000..5399b49 --- /dev/null +++ b/third_party/dartssh2/example/sftp_filetype.dart @@ -0,0 +1,27 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_list.dart b/third_party/dartssh2/example/sftp_list.dart new file mode 100644 index 0000000..8e74df7 --- /dev/null +++ b/third_party/dartssh2/example/sftp_list.dart @@ -0,0 +1,27 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_read.dart b/third_party/dartssh2/example/sftp_read.dart new file mode 100644 index 0000000..98b09d3 --- /dev/null +++ b/third_party/dartssh2/example/sftp_read.dart @@ -0,0 +1,26 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_stat.dart b/third_party/dartssh2/example/sftp_stat.dart new file mode 100644 index 0000000..d7cb3f8 --- /dev/null +++ b/third_party/dartssh2/example/sftp_stat.dart @@ -0,0 +1,25 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_upload.dart b/third_party/dartssh2/example/sftp_upload.dart new file mode 100644 index 0000000..68f3c18 --- /dev/null +++ b/third_party/dartssh2/example/sftp_upload.dart @@ -0,0 +1,27 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/sftp_write.dart b/third_party/dartssh2/example/sftp_write.dart new file mode 100644 index 0000000..98ea7a3 --- /dev/null +++ b/third_party/dartssh2/example/sftp_write.dart @@ -0,0 +1,31 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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; +} diff --git a/third_party/dartssh2/example/shell.dart b/third_party/dartssh2/example/shell.dart new file mode 100644 index 0000000..c715585 --- /dev/null +++ b/third_party/dartssh2/example/shell.dart @@ -0,0 +1,28 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; + +void main(List 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().listen(shell.write); + + await shell.done; + + client.close(); + await client.done; +} diff --git a/third_party/dartssh2/example/ssh_http.dart b/third_party/dartssh2/example/ssh_http.dart new file mode 100644 index 0000000..b2c4394 --- /dev/null +++ b/third_party/dartssh2/example/ssh_http.dart @@ -0,0 +1,16 @@ +import 'package:dartssh2/dartssh2.dart'; + +void main(List args) async { + final client = SSHClient( + await SSHSocket.connect('', 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(); +} diff --git a/third_party/dartssh2/example/ssh_jump.dart b/third_party/dartssh2/example/ssh_jump.dart new file mode 100644 index 0000000..c19178b --- /dev/null +++ b/third_party/dartssh2/example/ssh_jump.dart @@ -0,0 +1,23 @@ +import 'dart:convert'; + +import 'package:dartssh2/dartssh2.dart'; + +void main() async { + final jumpServer = SSHClient( + await SSHSocket.connect('', 22), + username: '...', + onPasswordRequest: () => '...', + ); + + final client = SSHClient( + await jumpServer.forwardLocal('', 22), + username: '...', + onPasswordRequest: () => '...', + ); + + print(utf8.decode(await client.run('hostname'))); + print(utf8.decode(await client.run('ifconfig'))); + + client.close(); + jumpServer.close(); +} diff --git a/third_party/dartssh2/lib/dartssh2.dart b/third_party/dartssh2/lib/dartssh2.dart new file mode 100644 index 0000000..956142a --- /dev/null +++ b/third_party/dartssh2/lib/dartssh2.dart @@ -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'; diff --git a/third_party/dartssh2/lib/src/algorithm/ssh_cipher_type.dart b/third_party/dartssh2/lib/src/algorithm/ssh_cipher_type.dart new file mode 100644 index 0000000..2553ca6 --- /dev/null +++ b/third_party/dartssh2/lib/src/algorithm/ssh_cipher_type.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()); +} diff --git a/third_party/dartssh2/lib/src/algorithm/ssh_hostkey_type.dart b/third_party/dartssh2/lib/src/algorithm/ssh_hostkey_type.dart new file mode 100644 index 0000000..307ef7d --- /dev/null +++ b/third_party/dartssh2/lib/src/algorithm/ssh_hostkey_type.dart @@ -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; +} diff --git a/third_party/dartssh2/lib/src/algorithm/ssh_kex_type.dart b/third_party/dartssh2/lib/src/algorithm/ssh_kex_type.dart new file mode 100644 index 0000000..9110230 --- /dev/null +++ b/third_party/dartssh2/lib/src/algorithm/ssh_kex_type.dart @@ -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(); diff --git a/third_party/dartssh2/lib/src/algorithm/ssh_mac_type.dart b/third_party/dartssh2/lib/src/algorithm/ssh_mac_type.dart new file mode 100644 index 0000000..0d1f59b --- /dev/null +++ b/third_party/dartssh2/lib/src/algorithm/ssh_mac_type.dart @@ -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); +} diff --git a/third_party/dartssh2/lib/src/hostkey/hostkey_ecdsa.dart b/third_party/dartssh2/lib/src/hostkey/hostkey_ecdsa.dart new file mode 100644 index 0000000..4770bd4 --- /dev/null +++ b/third_party/dartssh2/lib/src/hostkey/hostkey_ecdsa.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/hostkey/hostkey_ed25519.dart b/third_party/dartssh2/lib/src/hostkey/hostkey_ed25519.dart new file mode 100644 index 0000000..4b61a86 --- /dev/null +++ b/third_party/dartssh2/lib/src/hostkey/hostkey_ed25519.dart @@ -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)})'; + } +} diff --git a/third_party/dartssh2/lib/src/hostkey/hostkey_rsa.dart b/third_party/dartssh2/lib/src/hostkey/hostkey_rsa.dart new file mode 100644 index 0000000..f34022d --- /dev/null +++ b/third_party/dartssh2/lib/src/hostkey/hostkey_rsa.dart @@ -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(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)})'; + } +} diff --git a/third_party/dartssh2/lib/src/http/http_client.dart b/third_party/dartssh2/lib/src/http/http_client.dart new file mode 100644 index 0000000..be3f972 --- /dev/null +++ b/third_party/dartssh2/lib/src/http/http_client.dart @@ -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 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> _headers = >{}; + + final SSHHttpClientRequest _request; + + @override + SSHContentType? contentType; + + _SSHHttpClientRequestHeaders(this._request); + + @override + List? 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((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] = []; + } + _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 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> 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 from(SSHSocket socket) async { + int? statusCode; + String? reasonPhrase; + final body = StringBuffer(); + final headers = >{}; + + 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> _headers; + + _SSHHttpClientResponseHeaders(this._headers); + + @override + List? 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 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'); + } +} diff --git a/third_party/dartssh2/lib/src/http/http_content_type.dart b/third_party/dartssh2/lib/src/http/http_content_type.dart new file mode 100644 index 0000000..74e6d34 --- /dev/null +++ b/third_party/dartssh2/lib/src/http/http_content_type.dart @@ -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 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 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? _parameters; + Map? _unmodifiableParameters; + + // ignore: unused_element + _HeaderValue([this._value = "", Map parameters = const {}]) { + if (parameters.isNotEmpty) { + _parameters = HashMap.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 _ensureParameters() => + _parameters ??= {}; + + Map 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(); + } +} diff --git a/third_party/dartssh2/lib/src/http/http_exception.dart b/third_party/dartssh2/lib/src/http/http_exception.dart new file mode 100644 index 0000000..ecda165 --- /dev/null +++ b/third_party/dartssh2/lib/src/http/http_exception.dart @@ -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(); + } +} diff --git a/third_party/dartssh2/lib/src/http/http_headers.dart b/third_party/dartssh2/lib/src/http/http_headers.dart new file mode 100644 index 0000000..55851a5 --- /dev/null +++ b/third_party/dartssh2/lib/src/http/http_headers.dart @@ -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? 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 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(); +} diff --git a/third_party/dartssh2/lib/src/http/line_decoder.dart b/third_party/dartssh2/lib/src/http/line_decoder.dart new file mode 100644 index 0000000..91443b1 --- /dev/null +++ b/third_party/dartssh2/lib/src/http/line_decoder.dart @@ -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 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 line) => + _callback(utf8.decoder.convert(line), line.length, this); + + int get bufferedBytes => _unprocessedBytes.length; + + void close() => _process(_unprocessedBytes.takeBytes()); +} diff --git a/third_party/dartssh2/lib/src/kex/kex_dh.dart b/third_party/dartssh2/lib/src/kex/kex_dh.dart new file mode 100644 index 0000000..bf83cd4 --- /dev/null +++ b/third_party/dartssh2/lib/src/kex/kex_dh.dart @@ -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, + ]), +); diff --git a/third_party/dartssh2/lib/src/kex/kex_nist.dart b/third_party/dartssh2/lib/src/kex/kex_nist.dart new file mode 100644 index 0000000..23df1a8 --- /dev/null +++ b/third_party/dartssh2/lib/src/kex/kex_nist.dart @@ -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; + } +} diff --git a/third_party/dartssh2/lib/src/kex/kex_x25519.dart b/third_party/dartssh2/lib/src/kex/kex_x25519.dart new file mode 100644 index 0000000..77a8ff6 --- /dev/null +++ b/third_party/dartssh2/lib/src/kex/kex_x25519.dart @@ -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; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_channel.dart b/third_party/dartssh2/lib/src/message/msg_channel.dart new file mode 100644 index 0000000..cab4111 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_channel.dart @@ -0,0 +1,1049 @@ +// ignore_for_file: camel_case_types + +import 'dart:typed_data'; + +import 'package:dartssh2/src/ssh_message.dart'; + +/// Message to request opening a channel to remote host. +class SSH_Message_Channel_Open implements SSHMessage { + static const messageId = 90; + + /// `session`, `x11`, `direct-tcpip` or `forwarded-tcpip` + final String channelType; + + /// The channel number. + final int senderChannel; + + final int initialWindowSize; + + final int maximumPacketSize; + + /// "forwarded-tcpip" "direct-tcpip" "x11" channel specific data. + final String? host; + final int? port; + final String? originatorIP; + final int? originatorPort; + + SSH_Message_Channel_Open({ + required this.channelType, + required this.senderChannel, + required this.initialWindowSize, + required this.maximumPacketSize, + this.host, + this.port, + this.originatorIP, + this.originatorPort, + }); + + factory SSH_Message_Channel_Open.session({ + required int senderChannel, + required int initialWindowSize, + required int maximumPacketSize, + }) { + return SSH_Message_Channel_Open( + channelType: 'session', + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + ); + } + + factory SSH_Message_Channel_Open.x11({ + required int senderChannel, + required int initialWindowSize, + required int maximumPacketSize, + required String originatorIP, + required int originatorPort, + }) { + return SSH_Message_Channel_Open( + channelType: 'x11', + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + } + + factory SSH_Message_Channel_Open.forwardedTcpip({ + required int senderChannel, + required int initialWindowSize, + required int maximumPacketSize, + required String host, + required int port, + required String originatorIP, + required int originatorPort, + }) { + return SSH_Message_Channel_Open( + channelType: 'forwarded-tcpip', + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + host: host, + port: port, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + } + + factory SSH_Message_Channel_Open.directTcpip({ + required int senderChannel, + required int initialWindowSize, + required int maximumPacketSize, + required String host, + required int port, + required String originatorIP, + required int originatorPort, + }) { + return SSH_Message_Channel_Open( + channelType: 'direct-tcpip', + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + host: host, + port: port, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + } + + factory SSH_Message_Channel_Open.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final channelType = reader.readUtf8(); + final senderChannel = reader.readUint32(); + final initialWindowSize = reader.readUint32(); + final maximumPacketSize = reader.readUint32(); + switch (channelType) { + case 'session': + return SSH_Message_Channel_Open.session( + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + ); + case 'x11': + final originatorIP = reader.readUtf8(); + final originatorPort = reader.readUint32(); + return SSH_Message_Channel_Open.x11( + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + case 'forwarded-tcpip': + final host = reader.readUtf8(); + final port = reader.readUint32(); + final originatorIP = reader.readUtf8(); + final originatorPort = reader.readUint32(); + return SSH_Message_Channel_Open.forwardedTcpip( + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + host: host, + port: port, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + case 'direct-tcpip': + final host = reader.readUtf8(); + final port = reader.readUint32(); + final originatorIP = reader.readUtf8(); + final originatorPort = reader.readUint32(); + return SSH_Message_Channel_Open.directTcpip( + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + host: host, + port: port, + originatorIP: originatorIP, + originatorPort: originatorPort, + ); + + default: + return SSH_Message_Channel_Open( + channelType: channelType, + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + ); + } + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUtf8(channelType); + writer.writeUint32(senderChannel); + writer.writeUint32(initialWindowSize); + writer.writeUint32(maximumPacketSize); + switch (channelType) { + case 'session': + break; + case 'x11': + writer.writeUtf8(originatorIP!); + writer.writeUint32(originatorPort!); + break; + case 'forwarded-tcpip': + writer.writeUtf8(host!); + writer.writeUint32(port!); + writer.writeUtf8(originatorIP!); + writer.writeUint32(originatorPort!); + break; + case 'direct-tcpip': + writer.writeUtf8(host!); + writer.writeUint32(port!); + writer.writeUtf8(originatorIP!); + writer.writeUint32(originatorPort!); + break; + } + return writer.takeBytes(); + } + + @override + String toString() { + switch (channelType) { + case 'session': + return 'SSH_Message_Channel_Open(channelType: $channelType, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize)'; + case 'x11': + return 'SSH_Message_Channel_Open(channelType: $channelType, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize, originatorIP: $originatorIP, originatorPort: $originatorPort)'; + case 'forwarded-tcpip': + return 'SSH_Message_Channel_Open(channelType: $channelType, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize, host: $host, port: $port, originatorIP: $originatorIP, originatorPort: $originatorPort)'; + case 'direct-tcpip': + return 'SSH_Message_Channel_Open(channelType: $channelType, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize, host: $host, port: $port, originatorIP: $originatorIP, originatorPort: $originatorPort)'; + default: + return 'SSH_Message_Channel_Open(channelType: $channelType, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize)'; + } + } +} + +/// Message to inform remote host that channel is open. +class SSH_Message_Channel_Confirmation implements SSHMessage { + static const messageId = 91; + + /// The channel number given in the original open request + final int recipientChannel; + + /// The channel number allocated by the other side. + final int senderChannel; + + final int initialWindowSize; + + final int maximumPacketSize; + + final Uint8List data; + + SSH_Message_Channel_Confirmation({ + required this.recipientChannel, + required this.senderChannel, + required this.initialWindowSize, + required this.maximumPacketSize, + required this.data, + }); + + factory SSH_Message_Channel_Confirmation.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final senderChannel = reader.readUint32(); + final initialWindowSize = reader.readUint32(); + final maximumPacketSize = reader.readUint32(); + final data = reader.readToEnd(); + return SSH_Message_Channel_Confirmation( + recipientChannel: recipientChannel, + senderChannel: senderChannel, + initialWindowSize: initialWindowSize, + maximumPacketSize: maximumPacketSize, + data: data, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeUint32(senderChannel); + writer.writeUint32(initialWindowSize); + writer.writeUint32(maximumPacketSize); + writer.writeBytes(data); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Confirmation(recipientChannel: $recipientChannel, senderChannel: $senderChannel, initialWindowSize: $initialWindowSize, maximumPacketSize: $maximumPacketSize)'; + } +} + +/// Message to inform remote host that channel can't be opened. +class SSH_Message_Channel_Open_Failure implements SSHMessage { + static const messageId = 92; + + // Reason codes for failure + static const codeAdministrativelyProhibited = 1; + static const codeConnectFailed = 2; + static const codeUnknownChannelType = 3; + static const codeResourceShortage = 4; + + /// The channel number given in the original open request + final int recipientChannel; + + final int reasonCode; + + final String description; + + final String languageTag; + + SSH_Message_Channel_Open_Failure({ + required this.recipientChannel, + required this.reasonCode, + required this.description, + this.languageTag = '', + }); + + factory SSH_Message_Channel_Open_Failure.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final reasonCode = reader.readUint32(); + final description = reader.readUtf8(); + final languageTag = reader.readUtf8(); + return SSH_Message_Channel_Open_Failure( + recipientChannel: recipientChannel, + reasonCode: reasonCode, + description: description, + languageTag: languageTag, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeUint32(reasonCode); + writer.writeUtf8(description); + writer.writeUtf8(languageTag); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Open_Failure(recipientChannel: $recipientChannel, reasonCode: $reasonCode, description: $description, languageTag: $languageTag)'; + } +} + +/// Message to inform remote host how many bytes can be sent before it must wait +/// for window to be increased. +class SSH_Message_Channel_Window_Adjust implements SSHMessage { + static const messageId = 93; + + /// The channel number given in the original open request + final int recipientChannel; + + final int bytesToAdd; + + SSH_Message_Channel_Window_Adjust({ + required this.recipientChannel, + required this.bytesToAdd, + }); + + factory SSH_Message_Channel_Window_Adjust.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final bytesToAdd = reader.readUint32(); + return SSH_Message_Channel_Window_Adjust( + recipientChannel: recipientChannel, + bytesToAdd: bytesToAdd, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeUint32(bytesToAdd); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Window_Adjust(recipientChannel: $recipientChannel, bytesToAdd: $bytesToAdd)'; + } +} + +/// Message to transfer data between channels. +class SSH_Message_Channel_Data implements SSHMessage { + static const messageId = 94; + + /// The channel number + final int recipientChannel; + + /// The data to send + final Uint8List data; + + SSH_Message_Channel_Data({ + required this.recipientChannel, + required this.data, + }); + + factory SSH_Message_Channel_Data.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final data = reader.readString(); + return SSH_Message_Channel_Data( + recipientChannel: recipientChannel, + data: data, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeString(data); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Data(recipientChannel: $recipientChannel, data.length=${data.length})'; + } +} + +class SSH_Message_Channel_Extended_Data implements SSHMessage { + static const messageId = 95; + + static const dataTypeStderr = 1; + + /// The channel number + final int recipientChannel; + + /// The data to send + final int dataTypeCode; + + /// The data to send + final Uint8List data; + + SSH_Message_Channel_Extended_Data({ + required this.recipientChannel, + required this.dataTypeCode, + required this.data, + }); + + factory SSH_Message_Channel_Extended_Data.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final dataTypeCode = reader.readUint32(); + final data = reader.readString(); + return SSH_Message_Channel_Extended_Data( + recipientChannel: recipientChannel, + dataTypeCode: dataTypeCode, + data: data, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeUint32(dataTypeCode); + writer.writeString(data); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Extended_Data(recipientChannel: $recipientChannel, dataTypeCode: $dataTypeCode, data.length=${data.length})'; + } +} + +/// Message to inform remote host that no more data will be sent. +class SSH_Message_Channel_EOF implements SSHMessage { + static const messageId = 96; + + /// The channel number + final int recipientChannel; + + SSH_Message_Channel_EOF({ + required this.recipientChannel, + }); + + factory SSH_Message_Channel_EOF.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + return SSH_Message_Channel_EOF( + recipientChannel: recipientChannel, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_EOF(recipientChannel: $recipientChannel)'; + } +} + +/// Message to inform remote host the channel is now closed. +class SSH_Message_Channel_Close implements SSHMessage { + static const messageId = 97; + + /// The channel number + final int recipientChannel; + + SSH_Message_Channel_Close({ + required this.recipientChannel, + }); + + factory SSH_Message_Channel_Close.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + return SSH_Message_Channel_Close( + recipientChannel: recipientChannel, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Close(recipientChannel: $recipientChannel)'; + } +} + +abstract class SSHChannelRequestType { + static const pty = 'pty-req'; + static const x11 = 'x11-req'; + static const env = 'env'; + static const shell = 'shell'; + static const exec = 'exec'; + static const subsystem = 'subsystem'; + static const windowChange = 'window-change'; + static const xon = 'xon-xoff'; + static const signal = 'signal'; + static const exitStatus = 'exit-status'; + static const exitSignal = 'exit-signal'; +} + +/// Message to send channel-specific requests. +class SSH_Message_Channel_Request implements SSHMessage { + static const messageId = 98; + + final int recipientChannel; + final String requestType; + final bool wantReply; + + /// "pty-req" and "window-change" request specific data + final String? termType; + final int? termWidth; + final int? termHeight; + final int? termPixelWidth; + final int? termPixelHeight; + final Uint8List? termModes; + + /// "x11-req" request specific data + final bool? singleConnection; + final String? x11AuthenticationProtocol; + final String? x11AuthenticationCookie; + final String? x11ScreenNumber; + + /// "env" request specific data + final String? variableName; + final String? variableValue; + + /// "exec" request specific data + final String? command; + + /// "subsystem" request specific data + final String? subsystemName; + + /// "signal" request specific data, signal name (without the "SIG" prefix) + final String? signalName; + + /// "exit-status" request specific data + final int? exitStatus; + + /// "exit-signal" request specific data + final String? exitSignalName; + final bool? coreDumped; + final String? errorMessage; + final String? languageTag; + + SSH_Message_Channel_Request({ + required this.recipientChannel, + required this.requestType, + required this.wantReply, + this.termType, + this.termWidth, + this.termHeight, + this.termPixelWidth, + this.termPixelHeight, + this.termModes, + this.singleConnection, + this.x11AuthenticationProtocol, + this.x11AuthenticationCookie, + this.x11ScreenNumber, + this.variableName, + this.variableValue, + this.command, + this.subsystemName, + this.signalName, + this.exitStatus, + this.exitSignalName, + this.coreDumped, + this.errorMessage, + this.languageTag, + }); + + /// Request a pseudo-terminal to be allocated for the session + factory SSH_Message_Channel_Request.pty({ + required int recipientChannel, + bool wantReply = false, + required String termType, + required int termWidth, + required int termHeight, + required int termPixelWidth, + required int termPixelHeight, + required Uint8List termModes, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.pty, + wantReply: wantReply, + termType: termType, + termWidth: termWidth, + termHeight: termHeight, + termPixelWidth: termPixelWidth, + termPixelHeight: termPixelHeight, + termModes: termModes, + ); + } + + /// Request x11 forwarding for the session + factory SSH_Message_Channel_Request.x11({ + required int recipientChannel, + bool wantReply = false, + bool singleConnection = false, + required String x11AuthenticationProtocol, + required String x11AuthenticationCookie, + required String x11ScreenNumber, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.x11, + wantReply: wantReply, + singleConnection: singleConnection, + x11AuthenticationProtocol: x11AuthenticationProtocol, + x11AuthenticationCookie: x11AuthenticationCookie, + x11ScreenNumber: x11ScreenNumber, + ); + } + + /// Pass environment variable to the shell/command to be started later + factory SSH_Message_Channel_Request.env({ + required int recipientChannel, + bool wantReply = false, + required String variableName, + required String variableValue, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.env, + wantReply: wantReply, + variableName: variableName, + variableValue: variableValue, + ); + } + + /// Request that the user's default shell be started at the other end + factory SSH_Message_Channel_Request.shell({ + required int recipientChannel, + required bool wantReply, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.shell, + wantReply: wantReply, + ); + } + + /// Request the server start executing the given command + factory SSH_Message_Channel_Request.exec({ + required int recipientChannel, + required bool wantReply, + required String command, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.exec, + wantReply: wantReply, + command: command, + ); + } + + /// Request the server execute a predefined subsystem + factory SSH_Message_Channel_Request.subsystem({ + required int recipientChannel, + required bool wantReply, + required String subsystemName, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.subsystem, + wantReply: wantReply, + subsystemName: subsystemName, + ); + } + + /// Inform the server that the window size has changed + factory SSH_Message_Channel_Request.windowChange({ + required int recipientChannel, + required int termWidth, + required int termHeight, + required int termPixelWidth, + required int termPixelHeight, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.windowChange, + wantReply: false, + termWidth: termWidth, + termHeight: termHeight, + termPixelWidth: termPixelWidth, + termPixelHeight: termPixelHeight, + ); + } + + /// Deliver a signal to the process on the other end of the channel + factory SSH_Message_Channel_Request.signal({ + required int recipientChannel, + required String signalName, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.signal, + wantReply: false, + signalName: signalName, + ); + } + + /// Return exit status of the process on the other end of the channel + factory SSH_Message_Channel_Request.exitStatus({ + required int recipientChannel, + required int exitStatus, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.exitStatus, + wantReply: false, + exitStatus: exitStatus, + ); + } + + /// Indicate that the remote command terminated due to a signal + factory SSH_Message_Channel_Request.exitSignal({ + required int recipientChannel, + required String exitSignalName, + bool coreDumped = false, + String? errorMessage, + String? languageTag, + }) { + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: SSHChannelRequestType.exitSignal, + wantReply: false, + exitSignalName: exitSignalName, + coreDumped: coreDumped, + errorMessage: errorMessage, + languageTag: languageTag, + ); + } + + factory SSH_Message_Channel_Request.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + final requestType = reader.readUtf8(); + final wantReply = reader.readBool(); + switch (requestType) { + case SSHChannelRequestType.pty: + final termType = reader.readUtf8(); + final termWidth = reader.readUint32(); + final termHeight = reader.readUint32(); + final termPixelWidth = reader.readUint32(); + final termPixelHeight = reader.readUint32(); + final termModes = reader.readString(); + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: requestType, + wantReply: wantReply, + termType: termType, + termWidth: termWidth, + termHeight: termHeight, + termPixelWidth: termPixelWidth, + termPixelHeight: termPixelHeight, + termModes: termModes, + ); + case SSHChannelRequestType.x11: + final singleConnection = reader.readBool(); + final x11AuthenticationProtocol = reader.readUtf8(); + final x11AuthenticationCookie = reader.readUtf8(); + final x11ScreenNumber = reader.readUtf8(); + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: requestType, + wantReply: wantReply, + singleConnection: singleConnection, + x11AuthenticationProtocol: x11AuthenticationProtocol, + x11AuthenticationCookie: x11AuthenticationCookie, + x11ScreenNumber: x11ScreenNumber, + ); + case SSHChannelRequestType.env: + final variableName = reader.readUtf8(); + final variableValue = reader.readUtf8(); + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: requestType, + wantReply: wantReply, + variableName: variableName, + variableValue: variableValue, + ); + case SSHChannelRequestType.shell: + return SSH_Message_Channel_Request.shell( + recipientChannel: recipientChannel, + wantReply: wantReply, + ); + case SSHChannelRequestType.exec: + final command = reader.readUtf8(); + return SSH_Message_Channel_Request.exec( + recipientChannel: recipientChannel, + wantReply: wantReply, + command: command, + ); + case SSHChannelRequestType.subsystem: + final subsystemName = reader.readUtf8(); + return SSH_Message_Channel_Request.subsystem( + recipientChannel: recipientChannel, + wantReply: wantReply, + subsystemName: subsystemName, + ); + case SSHChannelRequestType.windowChange: + final termWidth = reader.readUint32(); + final termHeight = reader.readUint32(); + final termPixelWidth = reader.readUint32(); + final termPixelHeight = reader.readUint32(); + return SSH_Message_Channel_Request.windowChange( + recipientChannel: recipientChannel, + termWidth: termWidth, + termHeight: termHeight, + termPixelWidth: termPixelWidth, + termPixelHeight: termPixelHeight, + ); + case SSHChannelRequestType.signal: + final signalName = reader.readUtf8(); + return SSH_Message_Channel_Request.signal( + recipientChannel: recipientChannel, + signalName: signalName, + ); + case SSHChannelRequestType.exitStatus: + final exitStatus = reader.readUint32(); + return SSH_Message_Channel_Request.exitStatus( + recipientChannel: recipientChannel, + exitStatus: exitStatus, + ); + case SSHChannelRequestType.exitSignal: + final exitSignalName = reader.readUtf8(); + final coreDumped = reader.readBool(); + final errorMessage = reader.readUtf8(); + final languageTag = reader.readUtf8(); + return SSH_Message_Channel_Request.exitSignal( + recipientChannel: recipientChannel, + exitSignalName: exitSignalName, + coreDumped: coreDumped, + errorMessage: errorMessage, + languageTag: languageTag, + ); + default: + return SSH_Message_Channel_Request( + recipientChannel: recipientChannel, + requestType: requestType, + wantReply: wantReply, + ); + } + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + writer.writeUtf8(requestType); + writer.writeBool(wantReply); + switch (requestType) { + case 'pty-req': + writer.writeUtf8(termType!); + writer.writeUint32(termWidth!); + writer.writeUint32(termHeight!); + writer.writeUint32(termPixelWidth!); + writer.writeUint32(termPixelHeight!); + writer.writeString(termModes!); + break; + case 'x11-req': + writer.writeBool(singleConnection!); + writer.writeUtf8(x11AuthenticationProtocol!); + writer.writeUtf8(x11AuthenticationCookie!); + writer.writeUtf8(x11ScreenNumber!); + break; + case 'env': + writer.writeUtf8(variableName!); + writer.writeUtf8(variableValue!); + break; + case 'shell': + break; + case 'exec': + writer.writeUtf8(command!); + break; + case 'subsystem': + writer.writeUtf8(subsystemName!); + break; + case 'window-change': + writer.writeUint32(termWidth!); + writer.writeUint32(termHeight!); + writer.writeUint32(termPixelWidth!); + writer.writeUint32(termPixelHeight!); + break; + case 'signal': + writer.writeUtf8(signalName!); + break; + case 'exit-status': + writer.writeUint32(exitStatus!); + break; + case 'exit-signal': + writer.writeUtf8(exitSignalName!); + writer.writeBool(coreDumped!); + writer.writeUtf8(errorMessage!); + writer.writeUtf8(languageTag!); + break; + } + return writer.takeBytes(); + } + + @override + String toString() { + switch (requestType) { + case 'pty-req': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, termType: $termType, termWidth: $termWidth, termHeight: $termHeight, termPixelWidth: $termPixelWidth, termPixelHeight: $termPixelHeight, termModes: $termModes)'; + case 'x11-req': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, singleConnection: $singleConnection, x11AuthenticationProtocol: $x11AuthenticationProtocol, x11AuthenticationCookie: $x11AuthenticationCookie, x11ScreenNumber: $x11ScreenNumber)'; + case 'env': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, variableName: $variableName, variableValue: $variableValue)'; + case 'shell': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply)'; + case 'exec': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, command: $command)'; + case 'subsystem': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, subsystemName: $subsystemName)'; + case 'window-change': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, termWidth: $termWidth, termHeight: $termHeight, termPixelWidth: $termPixelWidth, termPixelHeight: $termPixelHeight)'; + case 'signal': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, signalName: $signalName)'; + case 'exit-status': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, exitStatus: $exitStatus)'; + case 'exit-signal': + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply, exitSignalName: $exitSignalName, coreDumped: $coreDumped, errorMessage: $errorMessage, languageTag: $languageTag)'; + default: + return 'SSH_Message_Channel_Request(recipientChannel: $recipientChannel, requestType: $requestType, wantReply: $wantReply)'; + } + } +} + +/// Response to a [SSH_Message_Channel_Request] if the request was successful +class SSH_Message_Channel_Success extends SSHMessage { + static const int messageId = 99; + + /// The channel number the request was sent on + final int recipientChannel; + + SSH_Message_Channel_Success({ + required this.recipientChannel, + }); + + factory SSH_Message_Channel_Success.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + return SSH_Message_Channel_Success( + recipientChannel: recipientChannel, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Success(recipientChannel: $recipientChannel)'; + } +} + +/// Response to a [SSH_Message_Channel_Request] if the request failed +class SSH_Message_Channel_Failure extends SSHMessage { + static const int messageId = 100; + + /// The channel number the request was sent on + final int recipientChannel; + + SSH_Message_Channel_Failure({ + required this.recipientChannel, + }); + + factory SSH_Message_Channel_Failure.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.skip(1); + final recipientChannel = reader.readUint32(); + return SSH_Message_Channel_Failure( + recipientChannel: recipientChannel, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(messageId); + writer.writeUint32(recipientChannel); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SSH_Message_Channel_Failure(recipientChannel: $recipientChannel)'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_debug.dart b/third_party/dartssh2/lib/src/message/msg_debug.dart new file mode 100644 index 0000000..be8ded0 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_debug.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_disconnect.dart b/third_party/dartssh2/lib/src/message/msg_disconnect.dart new file mode 100644 index 0000000..c3922b6 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_disconnect.dart @@ -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; + } + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_ignore.dart b/third_party/dartssh2/lib/src/message/msg_ignore.dart new file mode 100644 index 0000000..82a2bbf --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_ignore.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_kex.dart b/third_party/dartssh2/lib/src/message/msg_kex.dart new file mode 100644 index 0000000..57ca7a6 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_kex.dart @@ -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 kexAlgorithms; + final List serverHostKeyAlgorithms; + final List encryptionClientToServer; + final List encryptionServerToClient; + final List macClientToServer; + final List macServerToClient; + final List compressionClientToServer; + final List compressionServerToClient; + final List languagesClientToServer; + final List 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()'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_kex_dh.dart b/third_party/dartssh2/lib/src/message/msg_kex_dh.dart new file mode 100644 index 0000000..60d83b5 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_kex_dh.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_kex_ecdh.dart b/third_party/dartssh2/lib/src/message/msg_kex_ecdh.dart new file mode 100644 index 0000000..3ecd55f --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_kex_ecdh.dart @@ -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)})'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_request.dart b/third_party/dartssh2/lib/src/message/msg_request.dart new file mode 100644 index 0000000..c18029b --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_request.dart @@ -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? 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 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 _parseHostKeys(List pairs) { + // final result = []; + // 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 _encodeHostKeys(List hostKeys) { + // final result = []; + // 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()'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_service.dart b/third_party/dartssh2/lib/src/message/msg_service.dart new file mode 100644 index 0000000..62e66a1 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_service.dart @@ -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}'; + } +} diff --git a/third_party/dartssh2/lib/src/message/msg_userauth.dart b/third_party/dartssh2/lib/src/message/msg_userauth.dart new file mode 100644 index 0000000..42b23f9 --- /dev/null +++ b/third_party/dartssh2/lib/src/message/msg_userauth.dart @@ -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 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 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 = []; + 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 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 = []; + 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)'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_client.dart b/third_party/dartssh2/lib/src/sftp/sftp_client.dart new file mode 100644 index 0000000..7613b2b --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_client.dart @@ -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(); + + final _done = Completer(); + + final _requestId = SftpRequestId(); + + final _replyWaiters = >{}; + + /// The handshake information received from the server. + Future get handshake => _handshake.future; + + /// Gets the attributes of the file at [path]. + Future 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 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 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> 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> listdir(String path) async { + final result = []; + 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 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 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 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 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 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 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 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 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 _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?> _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 _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 _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 _sendClose(Uint8List handle) async { + await handshake; + final request = SftpClosePacket(_requestId.next, handle); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _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 _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 _sendLStat(String path) async { + await handshake; + final request = SftpLStatPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendFStat(Uint8List handle) async { + await handshake; + final request = SftpFStatPacket(_requestId.next, handle); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendSetStat( + String path, + SftpFileAttrs attrs, + ) async { + await handshake; + final request = SftpSetStatPacket(_requestId.next, path, attrs); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendFSetStat( + Uint8List handle, + SftpFileAttrs attrs, + ) async { + await handshake; + final request = SftpFSetStatPacket(_requestId.next, handle, attrs); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendOpenDir(String path) async { + await handshake; + final request = SftpOpenDirPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendReadDir(Uint8List handle) async { + await handshake; + final request = SftpReadDirPacket(_requestId.next, handle); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendRemove(String filename) async { + await handshake; + final request = SftpRemovePacket(_requestId.next, filename); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendMakeDir( + String path, + SftpFileAttrs attrs, + ) async { + await handshake; + final request = SftpMkdirPacket(_requestId.next, path, attrs); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendRemoveDir(String path) async { + await handshake; + final request = SftpRmdirPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendRealPath(String path) async { + await handshake; + final request = SftpRealpathPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendStat(String path) async { + await handshake; + final request = SftpStatPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendRename( + String oldPath, + String newPath, + ) async { + await handshake; + final request = SftpRenamePacket(_requestId.next, oldPath, newPath); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendReadLink(String path) async { + await handshake; + final request = SftpReadlinkPacket(_requestId.next, path); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _sendSymlink( + String linkPath, + String targetPath, + ) async { + await handshake; + final request = SftpSymlinkPacket(_requestId.next, linkPath, targetPath); + _sendPacket(request); + return await _waitReply(request.requestId); + } + + Future _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 _waitReply(int requestId) { + final completer = Completer(); + _replyWaiters[requestId] = completer; + return completer.future; + } + + Future _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 close() async { + if (_isClosed) return; + _isClosed = true; + await _client._close(_handle); + } + + Future 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 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 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(); + + var bytessRecieved = 0; + var bytessRequested = 0; + // 补丁:length 为 int?,await 之后无法类型提升,复制为非空局部变量 + final totalLength = length; + + Future 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 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 stream, { + int offset = 0, + void Function(int total)? onProgress, + }) { + return SftpFileWriter(this, stream, offset, onProgress); + } + + /// Writes [data] to the file starting at [offset]. + Future writeBytes(Uint8List data, {int offset = 0}) async { + const maxChunkSize = 16 * 1024; + var bytesSent = 0; + final futures = >[]; + 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 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 _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 _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 extensions; + + SftpHandsake(this.version, this.extensions); + + @override + String toString() => 'SftpHandsake($version, $extensions)'; +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_errors.dart b/third_party/dartssh2/lib/src/sftp/sftp_errors.dart new file mode 100644 index 0000000..74f5a38 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_errors.dart @@ -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'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_file_attrs.dart b/third_party/dartssh2/lib/src/sftp/sftp_file_attrs.dart new file mode 100644 index 0000000..44e4bc2 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_file_attrs.dart @@ -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? 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) ? {} : 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 = []; + 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(', ')})'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_file_open_mode.dart b/third_party/dartssh2/lib/src/sftp/sftp_file_open_mode.dart new file mode 100644 index 0000000..824fd4a --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_file_open_mode.dart @@ -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); +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_name.dart b/third_party/dartssh2/lib/src/sftp/sftp_name.dart new file mode 100644 index 0000000..7620c63 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_name.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_packet.dart b/third_party/dartssh2/lib/src/sftp/sftp_packet.dart new file mode 100644 index 0000000..7e81877 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_packet.dart @@ -0,0 +1,1042 @@ +import 'dart:typed_data'; + +import 'package:convert/convert.dart'; +import 'package:dartssh2/src/sftp/sftp_file_attrs.dart'; +import 'package:dartssh2/src/sftp/sftp_name.dart'; +import 'package:dartssh2/src/ssh_message.dart'; + +// SSH_FXP_INIT 1 init +// SSH_FXP_VERSION 2 init-reply +// SSH_FXP_OPEN 3 ---> SSH_FXP_STATUS | SSH_FXP_HANDLE +// SSH_FXP_CLOSE 4 ---> SSH_FXP_STATUS +// SSH_FXP_READ 5 ---> SSH_FXP_STATUS | SSH_FXP_DATA +// SSH_FXP_WRITE 6 ---> SSH_FXP_STATUS +// SSH_FXP_LSTAT 7 ---> SSH_FXP_STATUS | SSH_FXP_ATTRS +// SSH_FXP_FSTAT 8 ---> SSH_FXP_STATUS | SSH_FXP_ATTRS +// SSH_FXP_SETSTAT 9 ---> SSH_FXP_STATUS +// SSH_FXP_FSETSTAT 10 ---> SSH_FXP_STATUS +// SSH_FXP_OPENDIR 11 ---> SSH_FXP_STATUS | SSH_FXP_HANDLE +// SSH_FXP_READDIR 12 ---> SSH_FXP_STATUS | SSH_FXP_NAME +// SSH_FXP_REMOVE 13 ---> SSH_FXP_STATUS +// SSH_FXP_MKDIR 14 ---> SSH_FXP_STATUS +// SSH_FXP_RMDIR 15 ---> SSH_FXP_STATUS +// SSH_FXP_REALPATH 16 ---> SSH_FXP_STATUS | SSH_FXP_NAME +// SSH_FXP_STAT 17 ---> SSH_FXP_STATUS | SSH_FXP_ATTRS +// SSH_FXP_RENAME 18 ---> SSH_FXP_STATUS +// SSH_FXP_READLINK 19 ---> SSH_FXP_STATUS | SSH_FXP_NAME +// SSH_FXP_SYMLINK 20 ---> SSH_FXP_STATUS + +// SSH_FXP_STATUS 101 +// SSH_FXP_HANDLE 102 <--- SSH_FXP_OPEN | SSH_FXP_OPENDIR +// SSH_FXP_DATA 103 +// SSH_FXP_NAME 104 +// SSH_FXP_ATTRS 105 +// SSH_FXP_EXTENDED 200 +// SSH_FXP_EXTENDED_REPLY 201 + +abstract class SftpPacket { + Uint8List encode(); +} + +abstract class SftpRequestPacket implements SftpPacket { + int get requestId; +} + +abstract class SftpResponsePacket implements SftpPacket { + int get requestId; +} + +class SftpInitPacket implements SftpPacket { + static const int packetType = 1; + + final int version; + + final Map extensions; + + SftpInitPacket(this.version, [this.extensions = const {}]); + + factory SftpInitPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final version = reader.readUint32(); + final extensions = {}; + while (reader.isDone) { + final name = reader.readUtf8(); + final value = reader.readUtf8(); + extensions[name] = value; + } + return SftpInitPacket(version, extensions); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(version); + for (final extension in extensions.entries) { + writer.writeUtf8(extension.key); + writer.writeUtf8(extension.value); + } + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpInitPacket(version: $version, extensions: $extensions)'; + } +} + +class SftpVersionPacket implements SftpPacket { + static const int packetType = 2; + + final int version; + + final Map extensions; + + SftpVersionPacket(this.version, [this.extensions = const {}]); + + factory SftpVersionPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final version = reader.readUint32(); + final extensions = {}; + while (!reader.isDone) { + final name = reader.readUtf8(); + final value = reader.readUtf8(); + extensions[name] = value; + } + return SftpVersionPacket(version, extensions); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(version); + for (final extension in extensions.entries) { + writer.writeUtf8(extension.key); + writer.writeUtf8(extension.value); + } + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpVersionPacket(version: $version, extensions: $extensions)'; + } +} + +class SftpOpenPacket implements SftpRequestPacket { + static const int packetType = 3; + + @override + final int requestId; + + final String path; + + final int flags; + + final SftpFileAttrs attrs; + + SftpOpenPacket(this.requestId, this.path, this.flags, this.attrs); + + factory SftpOpenPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + final flags = reader.readUint32(); + final attrs = SftpFileAttrs.readFrom(reader); + return SftpOpenPacket(requestId, path, flags, attrs); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + writer.writeUint32(flags); + attrs.writeTo(writer); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpOpenPacket(requestId: $requestId, path: $path, flags: $flags, attrs: $attrs)'; + } +} + +class SftpClosePacket implements SftpRequestPacket { + static const int packetType = 4; + + @override + final int requestId; + + final Uint8List handle; + + SftpClosePacket(this.requestId, this.handle); + + factory SftpClosePacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + return SftpClosePacket(requestId, handle); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpClosePacket(requestId: $requestId, handle: ${hex.encode(handle)})'; + } +} + +class SftpReadPacket implements SftpRequestPacket { + static const int packetType = 5; + + @override + final int requestId; + + final Uint8List handle; + + final int offset; + + final int length; + + SftpReadPacket({ + required this.requestId, + required this.handle, + required this.offset, + required this.length, + }); + + factory SftpReadPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + final offset = reader.readUint64(); + final length = reader.readUint32(); + return SftpReadPacket( + requestId: requestId, + handle: handle, + offset: offset, + length: length, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + writer.writeUint64(offset); + writer.writeUint32(length); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpReadPacket(requestId: $requestId, handle: ${hex.encode(handle)}, offset: $offset, length: $length)'; + } +} + +class SftpWritePacket implements SftpRequestPacket { + static const int packetType = 6; + + @override + final int requestId; + + final Uint8List handle; + + final int offset; + + final Uint8List data; + + SftpWritePacket({ + required this.requestId, + required this.handle, + required this.offset, + required this.data, + }); + + factory SftpWritePacket.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + final offset = reader.readUint64(); + final data = reader.readString(); + return SftpWritePacket( + requestId: requestId, + handle: handle, + offset: offset, + data: data, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + writer.writeUint64(offset); + writer.writeString(data); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpWritePacket(requestId: $requestId, handle: ${hex.encode(handle)}, offset: $offset, data.length: ${data.length})'; + } +} + +class SftpLStatPacket implements SftpRequestPacket { + static const int packetType = 7; + + @override + final int requestId; + + final String path; + + SftpLStatPacket(this.requestId, this.path); + + factory SftpLStatPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpLStatPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpLStatPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpFStatPacket implements SftpRequestPacket { + static const int packetType = 8; + + @override + final int requestId; + + final Uint8List handle; + + SftpFStatPacket(this.requestId, this.handle); + + factory SftpFStatPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + return SftpFStatPacket(requestId, handle); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpFStatPacket(requestId: $requestId, handle: ${hex.encode(handle)})'; + } +} + +class SftpSetStatPacket implements SftpRequestPacket { + static const int packetType = 9; + + @override + final int requestId; + + final String path; + + final SftpFileAttrs attributes; + + SftpSetStatPacket(this.requestId, this.path, this.attributes); + + factory SftpSetStatPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + final attributes = SftpFileAttrs.readFrom(reader); + return SftpSetStatPacket(requestId, path, attributes); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + attributes.writeTo(writer); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpSetStatPacket(requestId: $requestId, path: $path, attributes: $attributes)'; + } +} + +class SftpFSetStatPacket implements SftpRequestPacket { + static const int packetType = 10; + + @override + final int requestId; + + final Uint8List handle; + + final SftpFileAttrs attributes; + + SftpFSetStatPacket(this.requestId, this.handle, this.attributes); + + factory SftpFSetStatPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + final attributes = SftpFileAttrs.readFrom(reader); + return SftpFSetStatPacket(requestId, handle, attributes); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + attributes.writeTo(writer); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpFSetStatPacket(requestId: $requestId, handle: ${hex.encode(handle)}, attributes: $attributes)'; + } +} + +class SftpOpenDirPacket implements SftpRequestPacket { + static const int packetType = 11; + + @override + final int requestId; + + final String path; + + SftpOpenDirPacket(this.requestId, this.path); + + factory SftpOpenDirPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpOpenDirPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpOpenDirPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpReadDirPacket implements SftpRequestPacket { + static const int packetType = 12; + + @override + final int requestId; + + final Uint8List handle; + + SftpReadDirPacket(this.requestId, this.handle); + + factory SftpReadDirPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + return SftpReadDirPacket(requestId, handle); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpReadDirPacket(requestId: $requestId, handle: ${hex.encode(handle)})'; + } +} + +class SftpRemovePacket implements SftpRequestPacket { + static const int packetType = 13; + + @override + final int requestId; + + final String filename; + + SftpRemovePacket(this.requestId, this.filename); + + factory SftpRemovePacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpRemovePacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(filename); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpRemovePacket(requestId: $requestId, filename: $filename)'; + } +} + +class SftpMkdirPacket implements SftpRequestPacket { + static const int packetType = 14; + + @override + final int requestId; + + final String path; + + final SftpFileAttrs attributes; + + SftpMkdirPacket(this.requestId, this.path, this.attributes); + + factory SftpMkdirPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + final attributes = SftpFileAttrs.readFrom(reader); + return SftpMkdirPacket(requestId, path, attributes); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + attributes.writeTo(writer); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpMkdirPacket(requestId: $requestId, path: $path, attributes: $attributes)'; + } +} + +class SftpRmdirPacket implements SftpRequestPacket { + static const int packetType = 15; + + @override + final int requestId; + + final String path; + + SftpRmdirPacket(this.requestId, this.path); + + factory SftpRmdirPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpRmdirPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpRmdirPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpRealpathPacket implements SftpRequestPacket { + static const int packetType = 16; + + @override + final int requestId; + + final String path; + + SftpRealpathPacket(this.requestId, this.path); + + factory SftpRealpathPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpRealpathPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpRealpathPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpStatPacket implements SftpRequestPacket { + static const int packetType = 17; + + @override + final int requestId; + + final String path; + + SftpStatPacket(this.requestId, this.path); + + factory SftpStatPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpStatPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpStatPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpRenamePacket implements SftpRequestPacket { + static const int packetType = 18; + + @override + final int requestId; + + final String oldPath; + + final String newPath; + + SftpRenamePacket(this.requestId, this.oldPath, this.newPath); + + factory SftpRenamePacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final oldPath = reader.readUtf8(); + final newPath = reader.readUtf8(); + return SftpRenamePacket(requestId, oldPath, newPath); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(oldPath); + writer.writeUtf8(newPath); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpRenamePacket(requestId: $requestId, oldPath: $oldPath, newPath: $newPath)'; + } +} + +class SftpReadlinkPacket implements SftpRequestPacket { + static const int packetType = 19; + + @override + final int requestId; + + final String path; + + SftpReadlinkPacket(this.requestId, this.path); + + factory SftpReadlinkPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final path = reader.readUtf8(); + return SftpReadlinkPacket(requestId, path); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(path); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpReadlinkPacket(requestId: $requestId, path: $path)'; + } +} + +class SftpSymlinkPacket implements SftpRequestPacket { + static const int packetType = 20; + + @override + final int requestId; + + final String linkPath; + + final String targetPath; + + SftpSymlinkPacket(this.requestId, this.linkPath, this.targetPath); + + factory SftpSymlinkPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final linkPath = reader.readUtf8(); + final targetPath = reader.readUtf8(); + return SftpSymlinkPacket(requestId, linkPath, targetPath); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUtf8(linkPath); + writer.writeUtf8(targetPath); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpSymlinkPacket(requestId: $requestId, linkPath: $linkPath, targetPath: $targetPath)'; + } +} + +class SftpStatusPacket implements SftpResponsePacket { + static const int packetType = 101; + + @override + final int requestId; + + final int code; + + final String message; + + final String language; + + SftpStatusPacket({ + required this.requestId, + required this.code, + required this.message, + this.language = '', + }); + + factory SftpStatusPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final code = reader.readUint32(); + final message = reader.readUtf8(); + final language = reader.readUtf8(); + return SftpStatusPacket( + requestId: requestId, + code: code, + message: message, + language: language, + ); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUint32(code); + writer.writeUtf8(message); + writer.writeUtf8(language); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpStatusPacket(requestId: $requestId, code: $code, message: $message, language: $language)'; + } +} + +class SftpHandlePacket implements SftpResponsePacket { + static const int packetType = 102; + + @override + final int requestId; + + final Uint8List handle; + + SftpHandlePacket(this.requestId, this.handle); + + factory SftpHandlePacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final handle = reader.readString(); + return SftpHandlePacket(requestId, handle); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(handle); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpHandlePacket(requestId: $requestId, handle: ${hex.encode(handle)})'; + } +} + +class SftpDataPacket implements SftpResponsePacket { + static const int packetType = 103; + + @override + final int requestId; + + final Uint8List data; + + SftpDataPacket(this.requestId, this.data); + + factory SftpDataPacket.decode(Uint8List bytes) { + final reader = SSHMessageReader(bytes); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final data = reader.readString(); + return SftpDataPacket(requestId, data); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(data); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpDataPacket(requestId: $requestId, data: $data)'; + } +} + +class SftpNamePacket implements SftpResponsePacket { + static const int packetType = 104; + + @override + final int requestId; + + final List names; + + SftpNamePacket(this.requestId, this.names); + + factory SftpNamePacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final nameCount = reader.readUint32(); + final names = []; + for (var i = 0; i < nameCount; i++) { + final name = SftpName.readFrom(reader); + names.add(name); + } + return SftpNamePacket(requestId, names); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeUint32(names.length); + for (final name in names) { + name.writeTo(writer); + } + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpNamePacket(requestId: $requestId, names: $names)'; + } +} + +class SftpAttrsPacket implements SftpResponsePacket { + static const int packetType = 105; + + @override + final int requestId; + + final SftpFileAttrs attrs; + + SftpAttrsPacket(this.requestId, this.attrs); + + factory SftpAttrsPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final attrs = SftpFileAttrs.readFrom(reader); + return SftpAttrsPacket(requestId, attrs); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + attrs.writeTo(writer); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpAttrsPacket(requestId: $requestId, attrs: $attrs)'; + } +} + +class SftpExtendedPacket implements SftpRequestPacket { + static const int packetType = 200; + + @override + final int requestId; + + final Uint8List payload; + + SftpExtendedPacket(this.requestId, this.payload); + + factory SftpExtendedPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final payload = reader.readToEnd(); + return SftpExtendedPacket(requestId, payload); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeBytes(payload); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpExtendedPacket(requestId: $requestId, payload: ${payload.length})'; + } +} + +class SftpExtendedReplyPacket implements SftpResponsePacket { + static const int packetType = 201; + + @override + final int requestId; + + final Uint8List payload; + + SftpExtendedReplyPacket(this.requestId, this.payload); + + factory SftpExtendedReplyPacket.decode(Uint8List data) { + final reader = SSHMessageReader(data); + reader.readUint8(); // packet type + final requestId = reader.readUint32(); + final payload = reader.readToEnd(); + return SftpExtendedReplyPacket(requestId, payload); + } + + @override + Uint8List encode() { + final writer = SSHMessageWriter(); + writer.writeUint8(packetType); + writer.writeUint32(requestId); + writer.writeString(payload); + return writer.takeBytes(); + } + + @override + String toString() { + return 'SftpExtendedReplyPacket(requestId: $requestId, payload: ${payload.length} bytes)'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_packet_ext.dart b/third_party/dartssh2/lib/src/sftp/sftp_packet_ext.dart new file mode 100644 index 0000000..9808d67 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_packet_ext.dart @@ -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; +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_request_id.dart b/third_party/dartssh2/lib/src/sftp/sftp_request_id.dart new file mode 100644 index 0000000..33cafad --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_request_id.dart @@ -0,0 +1,9 @@ +class SftpRequestId { + static const max = 0xFFFFFFFF; + + var _id = 0; + + int get next { + return _id++ % max; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_status_code.dart b/third_party/dartssh2/lib/src/sftp/sftp_status_code.dart new file mode 100644 index 0000000..fe6f4d9 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_status_code.dart @@ -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; +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_statvfs.dart b/third_party/dartssh2/lib/src/sftp/sftp_statvfs.dart new file mode 100644 index 0000000..d3b4a37 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_statvfs.dart @@ -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' + '}'; + } +} diff --git a/third_party/dartssh2/lib/src/sftp/sftp_stream_io.dart b/third_party/dartssh2/lib/src/sftp/sftp_stream_io.dart new file mode 100644 index 0000000..c8f43a5 --- /dev/null +++ b/third_party/dartssh2/lib/src/sftp/sftp_stream_io.dart @@ -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 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 _subscription; + + final _doneCompleter = Completer(); + + /// 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 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 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 _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 get done; + + @override + Stream asStream() => done.asStream(); + + @override + Future catchError( + Function onError, { + bool Function(Object error)? test, + }) => + done.catchError(onError, test: test); + + @override + Future then(FutureOr Function(void) onValue, {Function? onError}) => + done.then(onValue, onError: onError); + + @override + Future whenComplete(FutureOr Function() action) => + done.whenComplete(action); + + @override + Future timeout( + Duration timeLimit, { + FutureOr Function()? onTimeout, + }) => + done.timeout(timeLimit, onTimeout: onTimeout); +} diff --git a/third_party/dartssh2/lib/src/socket/ssh_socket.dart b/third_party/dartssh2/lib/src/socket/ssh_socket.dart new file mode 100644 index 0000000..764d882 --- /dev/null +++ b/third_party/dartssh2/lib/src/socket/ssh_socket.dart @@ -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 connect( + String host, + int port, { + Duration? timeout, + }) async { + return await connectNativeSocket(host, port, timeout: timeout); + } + + Stream get stream; + + StreamSink> get sink; + + /// A future that will complete when the consumer closes, or when an error occurs. + Future get done; + + /// Closes the socket, returning the same future as [done]. + Future close(); + + void destroy(); +} diff --git a/third_party/dartssh2/lib/src/socket/ssh_socket_io.dart b/third_party/dartssh2/lib/src/socket/ssh_socket_io.dart new file mode 100644 index 0000000..a8f155b --- /dev/null +++ b/third_party/dartssh2/lib/src/socket/ssh_socket_io.dart @@ -0,0 +1,45 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dartssh2/src/socket/ssh_socket.dart'; + +Future 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 get stream => _socket; + + @override + StreamSink> get sink => _socket; + + @override + Future close() async { + await _socket.close(); + } + + @override + Future get done => _socket.done; + + @override + void destroy() { + _socket.destroy(); + } + + @override + String toString() { + final address = '${_socket.remoteAddress.host}:${_socket.remotePort}'; + return '_SSHNativeSocket($address)'; + } +} diff --git a/third_party/dartssh2/lib/src/socket/ssh_socket_js.dart b/third_party/dartssh2/lib/src/socket/ssh_socket_js.dart new file mode 100644 index 0000000..8a6a817 --- /dev/null +++ b/third_party/dartssh2/lib/src/socket/ssh_socket_js.dart @@ -0,0 +1,13 @@ +import 'package:dartssh2/src/socket/ssh_socket.dart'; + +Future 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.', + ); +} diff --git a/third_party/dartssh2/lib/src/ssh_algorithm.dart b/third_party/dartssh2/lib/src/ssh_algorithm.dart new file mode 100644 index 0000000..35d3c7d --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_algorithm.dart @@ -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 on List { + List 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 kex; + + /// Algorithm used for the host key. + final List hostkey; + + /// Algorithm used for the encryption. + final List cipher; + + /// Algorithm used for the authentication. + final List 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, + ], + }); +} diff --git a/third_party/dartssh2/lib/src/ssh_channel.dart b/third_party/dartssh2/lib/src/ssh_channel.dart new file mode 100644 index 0000000..fb5daa7 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_channel.dart @@ -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( + onResume: _sendWindowAdjustIfNeeded, + ); + + /// A [StreamController] that accepts data from local end of the channel. + final _localStream = StreamController(); + + 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(); + + /// 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(); + + Future sendExec(String command) async { + sendMessage( + SSH_Message_Channel_Request.exec( + recipientChannel: remoteId, + wantReply: true, + command: command, + ), + ); + return await _requestReplyQueue.next; + } + + Future 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 sendShell() async { + sendMessage( + SSH_Message_Channel_Request.shell( + recipientChannel: remoteId, + wantReply: true, + ), + ); + return await _requestReplyQueue.next; + } + + Future 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 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 get stream => _controller._remoteStream.stream; + + /// A [StreamSink] that sends data to the remote side. Chucks must be + /// equal to or less than [maximumPacketSize]. + StreamSink get sink => _controller._localStream.sink; + + Future 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 sendExec(String command) async { + return await _controller.sendExec(command); + } + + Future 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 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 { + SSHChannelDataSplitter(this.maxSize); + + final int maxSize; + + @override + Stream bind(Stream 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 { + 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; + } + } +} diff --git a/third_party/dartssh2/lib/src/ssh_channel_id.dart b/third_party/dartssh2/lib/src/ssh_channel_id.dart new file mode 100644 index 0000000..e3944f2 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_channel_id.dart @@ -0,0 +1,32 @@ +typedef SSHChannelId = int; + +class SSHChannelIdAllocator { + SSHChannelIdAllocator(); + + static const _maxId = 0xFFFF; + + var _nextId = 0; + + final _allocated = {}; + + /// 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); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_client.dart b/third_party/dartssh2/lib/src/ssh_client.dart new file mode 100644 index 0000000..9ddc183 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_client.dart @@ -0,0 +1,1025 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:typed_data'; + +import 'package:dartssh2/src/http/http_client.dart'; +import 'package:dartssh2/src/sftp/sftp_client.dart'; +import 'package:dartssh2/src/ssh_algorithm.dart'; +import 'package:dartssh2/src/ssh_channel.dart'; +import 'package:dartssh2/src/ssh_channel_id.dart'; +import 'package:dartssh2/src/ssh_errors.dart'; +import 'package:dartssh2/src/ssh_forward.dart'; +import 'package:dartssh2/src/ssh_keepalive.dart'; +import 'package:dartssh2/src/ssh_key_pair.dart'; +import 'package:dartssh2/src/ssh_session.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/message/msg_request.dart'; +import 'package:dartssh2/src/message/msg_service.dart'; +import 'package:dartssh2/src/message/msg_userauth.dart'; +import 'package:dartssh2/src/ssh_message.dart'; +import 'package:dartssh2/src/socket/ssh_socket.dart'; +import 'package:dartssh2/src/ssh_userauth.dart'; + +/// https://datatracker.ietf.org/doc/html/rfc4252#section-8 +typedef SSHPasswordRequestHandler = FutureOr Function(); + +typedef SSHChangePasswordRequestHandler = FutureOr + Function(String prompt); + +/// https://datatracker.ietf.org/doc/html/rfc4256#section-3.3 +typedef SSHUserInfoRequestHandler = FutureOr?> Function( + SSHUserInfoRequest request, +); + +/// https://datatracker.ietf.org/doc/html/rfc4252#section-5.4 +typedef SSHUserauthBannerHandler = void Function(String banner); + +typedef SSHAuthenticatedHandler = void Function(); + +typedef SSHRemoteConnectionFilter = bool Function(String host, int port); + +// /// Function called when the host has sent additional host keys after the initial +// /// key exchange. +// typedef SSHHostKeysHandler = void Function(List); + +const _initialWindowSize = 1024 * 1024 * 2; + +const _maximumPacketSize = 32768; + +class SSHPtyConfig { + /// Type of terminal, for example 'xterm', 'xterm-256color'. + final String type; + + /// Width of the terminal in number of columns. + final int width; + + /// Height of the terminal in number of rows. + final int height; + + /// Width of the terminal in pixels. 0 if unknown. + final int pixelWidth; + + /// Height of the terminal in pixels. 0 if unknown. + final int pixelHeight; + + const SSHPtyConfig({ + this.type = 'xterm-256color', + this.width = 80, + this.height = 24, + this.pixelWidth = 0, + this.pixelHeight = 0, + }); +} + +class SSHClient { + final SSHSocket socket; + + /// The username to authenticate as. + final String username; + + /// Function invoked with debug messages. + final SSHPrintHandler? printDebug; + + /// Function invoked with network traffic messages. + final SSHPrintHandler? printTrace; + + /// Crypto algorithms available for the client. + final SSHAlgorithms algorithms; + + /// Function called when the first host key is received. Return true to accept + /// the host key, false to reject it and close the connection. If this is + /// null, the host key is accepted automatically. + final SSHHostkeyVerifyHandler? onVerifyHostKey; + + /// List of key pairs to use for authentication. Set this field to enable + /// authentication with public key. + final List? identities; + + /// Set this field to enable the 'password' authentication method. Return null + /// to skip to the next available authentication method. + final SSHPasswordRequestHandler? onPasswordRequest; + + /// Set this field to enable setting new passwords when the server requests + /// changing password when using the 'password' authentication method. Return + /// null to skip to the next available authentication method. + final SSHChangePasswordRequestHandler? onChangePasswordRequest; + + /// Set this field to enable the 'keyboard-interactive' authentication method. + /// This may be called multiple times to request additional prompts. Return + /// null to skip to the next available authentication method. + final SSHUserInfoRequestHandler? onUserInfoRequest; + + /// The SSH server may send banner message at any time before authentication + /// is successful. Set this field to receive the banner message. + final SSHUserauthBannerHandler? onUserauthBanner; + + /// A [Future] that completes normally when the client is connected to the + // Future get handshake => _handshakeCompleter.future; + + /// Function called when authentication is complete. + final SSHAuthenticatedHandler? onAuthenticated; + + /// The interval at which to send a keep-alive message through the [ping] + /// method. Set this to null to disable automatic keep-alive messages. + final Duration? keepAliveInterval; + + /// Function called when additional host keys are received. This is an OpenSSH + /// extension. May not be called if the server does not support the extension. + // final SSHHostKeysHandler? onHostKeys; + + /// 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 get done => _transport.done; + + /// true if the connection is closed normally or due to an error. + bool get isClosed => _transport.isClosed; + + SSHClient( + this.socket, { + required this.username, + this.printDebug, + this.printTrace, + this.algorithms = const SSHAlgorithms(), + this.onVerifyHostKey, + this.identities, + this.onPasswordRequest, + this.onChangePasswordRequest, + this.onUserInfoRequest, + this.onUserauthBanner, + this.onAuthenticated, + this.keepAliveInterval = const Duration(seconds: 10), + }) { + _transport = SSHTransport( + socket, + isServer: false, + printDebug: printDebug, + printTrace: printTrace, + algorithms: algorithms, + onVerifyHostKey: onVerifyHostKey, + onReady: _handleTransportReady, + onPacket: _handlePacket, + ); + + _transport.done.then( + (_) => _handleTransportClosed(), + onError: (_) => _handleTransportClosed(), + ); + + _authenticated.future.catchError( + (error, stackTrace) => _transport.closeWithError(error, stackTrace), + ); + + if (identities != null) { + _keyPairsLeft.addAll(identities!); + } + } + + late final SSHTransport _transport; + + /// A [Completer] that completes when the client has authenticated, or + /// completes with an error if the client could not authenticate. + final _authenticated = Completer(); + + final _globalRequestReplyQueue = AsyncQueue(); + + final _channelIdAllocator = SSHChannelIdAllocator(); + + final _channelOpenReplyWaiters = >{}; + + final _channels = {}; + + final _authMethodsLeft = Queue(); + + final _keyPairsLeft = Queue(); + + final _remoteForwards = {}; + + late final _keepAlive = keepAliveInterval != null + ? SSHKeepAlive(ping: ping, interval: keepAliveInterval!) + : null; + + SSHAuthMethod? _currentAuthMethod; + + /// A [Future] that completes when the client has authenticated, or + /// completes with an error if the client could not authenticate. + Future get authenticated => _authenticated.future; + + /// 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 => _transport.remoteVersion; + + /// Request connections to a port on the other side be forwarded to the local + /// side. + /// Set [host] to null to listen on all interfaces, `"0.0.0.0"` to + /// listen on all IPv4 interfaces, `"::"` to listen on all IPv6 interfaces, + /// and `"localhost"` to listen on the loopback interface on all protocols. + /// Set [port] to null to listen on a random port. + Future forwardRemote({ + String? host, + int? port, + SSHRemoteConnectionFilter? filter, + }) async { + await _authenticated.future; + + // Lisning on all interfaces if not specified. + host ??= ''; + + // Lisning on a random port if not specified. + port ??= 0; + + _sendMessage(SSH_Message_Global_Request.tcpipForward(host, port)); + final reply = await _globalRequestReplyQueue.next; + + if (reply is SSH_Message_Request_Failure) return null; + + if (reply is! SSH_Message_Request_Success) { + throw SSHStateError('Unexpected reply to tcpip-forward request: $reply'); + } + + final reader = SSHMessageReader(reply.requestData); + final assignedPort = port != 0 ? port : reader.readUint32(); + + final remoteForward = SSHRemoteForward(this, host, assignedPort, filter); + _remoteForwards.add(remoteForward); + + return remoteForward; + } + + /// Cancel a previous request to forward connections to a port on the other + /// side. Returns [true] if successful, [false] otherwise. + /// See also: [forwardRemote]. + Future cancelForwardRemote(SSHRemoteForward forward) async { + await _authenticated.future; + + if (!_remoteForwards.remove(forward)) return false; + + _sendMessage( + SSH_Message_Global_Request.cancelTcpipForward( + bindAddress: forward.host, + bindPort: forward.port, + ), + ); + + final reply = await _globalRequestReplyQueue.next; + if (reply is SSH_Message_Request_Failure) { + return false; + } + + return true; + } + + /// Forward connections to a [localHost]:[localPort] to [remoteHost]:[remotePort] + /// [localHost] and [localPort] are only required by the protocol and do not + /// need to be specified in most cases. + Future forwardLocal( + String remoteHost, + int remotePort, { + String localHost = 'localhost', + int localPort = 0, + }) async { + await _authenticated.future; + final channelController = await _openForwardLocalChannel( + localHost, + localPort, + remoteHost, + remotePort, + ); + return SSHForwardChannel(channelController.channel); + } + + /// Execute [command] on the remote side. Returns a [SSHChannel] that can be + /// used to read and write to the remote side. + Future execute( + String command, { + SSHPtyConfig? pty, + Map? environment, + }) async { + await _authenticated.future; + + final channelController = await _openSessionChannel(); + + if (environment != null) { + for (var pair in environment.entries) { + channelController.sendEnv(pair.key, pair.value); + } + } + + if (pty != null) { + final ptyOk = await channelController.sendPtyReq( + terminalType: pty.type, + terminalWidth: pty.width, + terminalHeight: pty.height, + terminalPixelWidth: pty.pixelWidth, + terminalPixelHeight: pty.pixelHeight, + ); + if (!ptyOk) { + channelController.close(); + throw SSHChannelRequestError('Failed to start pty'); + } + } + + final success = await channelController.sendExec(command); + if (!success) { + channelController.close(); + throw SSHChannelRequestError('Failed to execute'); + } + + return SSHSession(channelController.channel); + } + + /// Start a shell on the remote side. Returns a [SSHSession] that can be + /// used to read, write and control the pty on the remote side. + Future shell({ + SSHPtyConfig? pty = const SSHPtyConfig(), + Map? environment, + }) async { + await _authenticated.future; + + final channelController = await _openSessionChannel(); + + if (environment != null) { + for (var pair in environment.entries) { + channelController.sendEnv(pair.key, pair.value); + } + } + + if (pty != null) { + final ok = await channelController.sendPtyReq( + terminalType: pty.type, + terminalWidth: pty.width, + terminalHeight: pty.height, + terminalPixelWidth: pty.pixelWidth, + terminalPixelHeight: pty.pixelHeight, + ); + if (!ok) { + channelController.close(); + throw SSHChannelRequestError('Failed to start pty'); + } + } + + if (!await channelController.sendShell()) { + channelController.close(); + throw SSHChannelRequestError('Failed to start shell'); + } + + return SSHSession(channelController.channel); + } + + Future subsystem(String subsystem) async { + await _authenticated.future; + + final channelController = await _openSessionChannel(); + channelController.sendSubsystem(subsystem); + } + + /// Open a new SFTP session. Returns a [SftpClient] that can be used to + /// interact with the remote side. + Future sftp() async { + await _authenticated.future; + + final channelController = await _openSessionChannel(); + channelController.sendSubsystem('sftp'); + + return SftpClient( + channelController.channel, + printDebug: printDebug, + printTrace: printTrace, + ); + } + + /// Create a new [SSHHttpClient] that can be used to make HTTP requests + /// that are tunneled over the SSH connection. The returned [SSHHttpClient] + /// is a very basic implementation, only intended for making simple requests. + SSHHttpClient httpClient() { + return SSHHttpClient(this); + } + + /// Execute [command] on the remote side non-interactively. Returns a + /// [Future] that completes with the output of the command. + /// This is a convenience method over [execute]. If [stdout] is false, + /// the standard output of the command will be ignored. If [stderr] is + /// false, the standard error of the command will be ignored. + Future run( + String command, { + bool runInPty = false, + bool stdout = true, + bool stderr = true, + Map? environment, + }) async { + final session = await execute( + command, + pty: runInPty ? const SSHPtyConfig() : null, + environment: environment, + ); + + final result = BytesBuilder(copy: false); + final stdoutDone = Completer(); + final stderrDone = Completer(); + + session.stdout.listen( + stdout ? result.add : (_) {}, + onDone: stdoutDone.complete, + onError: stderrDone.completeError, + ); + + session.stderr.listen( + stderr ? result.add : (_) {}, + onDone: stderrDone.complete, + onError: stderrDone.completeError, + ); + + await stdoutDone.future; + await stderrDone.future; + + return result.takeBytes(); + } + + /// Send a empty message to the server to keep the connection alive. + Future ping() async { + await _authenticated.future; + _sendMessage(SSH_Message_Global_Request.keepAlive()); + await _globalRequestReplyQueue.next; + } + + /// Shutdown the entire SSH connection. Sessions and channels will also be + /// closed immediately. + void close() { + _closeChannels(); + _transport.close(); + } + + /// Close all channels that are currently open. + void _closeChannels() { + for (final channel in _channels.values) { + channel.destroy(); + _channelIdAllocator.release(channel.localId); + } + + _channels.clear(); + } + + void _handleTransportReady() { + printDebug?.call('SSHClient._onTransportReady'); + _requestAuthentication(); + } + + void _handleTransportClosed() { + printDebug?.call('SSHClient._onTransportClosed'); + if (!_authenticated.isCompleted) { + _authenticated.completeError( + SSHAuthAbortError('Connection closed before authentication'), + ); + } + _keepAlive?.stop(); + _closeChannels(); + } + + void _handlePacket(Uint8List payload) { + try { + _dispatchMessage(payload); + } catch (e) { + rethrow; + } + } + + void _sendMessage(SSHMessage message) { + printTrace?.call('-> $socket: $message'); + _transport.sendPacket(message.encode()); + } + + void _catch(FutureOr Function() fn) { + Future.sync(fn).catchError((e, st) { + _transport.closeWithError(SSHInternalError(e), st); + }); + } + + void _dispatchMessage(Uint8List message) { + final messageId = SSHMessage.readMessageId(message); + switch (messageId) { + case SSH_Message_Service_Accept.messageId: + return _handleServiceAccept(message); + case SSH_Message_Userauth_Success.messageId: + return _handleUserauthSuccess(); + case SSH_Message_Userauth_Failure.messageId: + return _handleUserauthFailure(message); + case SSH_Message_Userauth_Passwd_ChangeReq.messageId: + return _handleUserauthIntermidiate(message); + case SSH_Message_Userauth_Banner.messageId: + return _handleUserauthBanner(message); + case SSH_Message_Global_Request.messageId: + return _handleGlobalRequest(message); + case SSH_Message_Request_Success.messageId: + return _handleGlobalRequestSuccess(message); + case SSH_Message_Request_Failure.messageId: + return _handleGlobalRequestFailure(message); + case SSH_Message_Channel_Open.messageId: + return _handleChannelOpen(message); + case SSH_Message_Channel_Confirmation.messageId: + return _handleChannelConfirmation(message); + case SSH_Message_Channel_Open_Failure.messageId: + return _handleChannelOpenFailure(message); + case SSH_Message_Channel_Window_Adjust.messageId: + return _handleChannelWindowAdjust(message); + case SSH_Message_Channel_Success.messageId: + return _handleChannelSuccess(message); + case SSH_Message_Channel_Failure.messageId: + return _handleChannelFailure(message); + case SSH_Message_Channel_Data.messageId: + return _handleChannelData(message); + case SSH_Message_Channel_Extended_Data.messageId: + return _handleChannelExtendedData(message); + case SSH_Message_Channel_EOF.messageId: + return _handleChannelEOF(message); + case SSH_Message_Channel_Close.messageId: + return _handleChannelClose(message); + case SSH_Message_Channel_Request.messageId: + return _handleChannelRequest(message); + default: + printDebug?.call('unknown messageId: $messageId'); + } + } + + void _handleServiceAccept(Uint8List payload) { + final message = SSH_Message_Service_Accept.decode(payload); + printTrace?.call('<- $socket: $message'); + + switch (message.serviceName) { + case 'ssh-userauth': + return _startAuthentication(); + default: + printDebug?.call('unknown serviceName: ${message.serviceName}'); + } + } + + void _handleUserauthSuccess() { + printTrace?.call('<- $socket: SSH_Message_Userauth_Success'); + printDebug?.call('SSHClient._handleUserauthSuccess'); + _authenticated.complete(); + onAuthenticated?.call(); + _keepAlive?.start(); + } + + void _handleUserauthFailure(Uint8List payload) { + final message = SSH_Message_Userauth_Failure.decode(payload); + printTrace?.call('<- $socket: $message'); + printDebug?.call('SSHClient._handleUserauthFailure'); + _tryNextAuthMethod(); + } + + void _handleUserauthIntermidiate(Uint8List payload) { + printDebug?.call('SSHClient._handleUserauthIntermidiate'); + + switch (_currentAuthMethod) { + case SSHAuthMethod.password: + return _catch(() => _handleUserauthPasswordChangeRequest(payload)); + case SSHAuthMethod.keyboardInteractive: + return _catch(() => _handleUserauthInfoRequest(payload)); + default: + printDebug?.call('unknown auth method: $_currentAuthMethod'); + } + } + + Future _handleUserauthPasswordChangeRequest(Uint8List payload) async { + printDebug?.call('SSHClient._handleUserauthPasswordChangeRequest'); + final message = SSH_Message_Userauth_Passwd_ChangeReq.decode(payload); + printTrace?.call('<- $socket: $message'); + + final response = await onChangePasswordRequest!(message.prompt); + if (response == null) return _tryNextAuthMethod(); + + _sendMessage(SSH_Message_Userauth_Request.newPassword( + user: username, + oldPassword: response.oldPassword, + newPassword: response.newPassword, + )); + } + + Future _handleUserauthInfoRequest(Uint8List payload) async { + printDebug?.call('SSHClient._handleUserauthInfoRequest'); + final message = SSH_Message_Userauth_InfoRequest.decode(payload); + printTrace?.call('<- $socket: $message'); + + final responses = await onUserInfoRequest!( + SSHUserInfoRequest(message.name, message.instruction, message.prompts), + ); + + if (responses == null) return _tryNextAuthMethod(); + + if (responses.length != message.prompts.length) { + throw ArgumentError( + 'responses.length (${responses.length}) != message.prompts.length (${message.prompts.length})', + ); + } + + _sendMessage(SSH_Message_Userauth_InfoResponse(responses: responses)); + } + + void _handleUserauthBanner(Uint8List payload) { + final message = SSH_Message_Userauth_Banner.decode(payload); + printDebug?.call('<- $socket: $message'); + onUserauthBanner?.call(message.message); + } + + void _handleGlobalRequest(Uint8List payload) { + final message = SSH_Message_Global_Request.decode(payload); + printTrace?.call('<- $socket: $message'); + + // Currently we don't support any global requests on the client side. + if (message.wantReply) { + _sendMessage(SSH_Message_Request_Failure()); + } + } + + // void _handleGlobalRequestHostkey(SSH_Message_Global_Request request) { + // printDebug?.call('SSHClient._handleGlobalRequestHostkey'); + // // sendMessage(SSH_Message_Request_Success.e + // if (onHostKeys != null) { + // // onHostKeys(request.hostKeyAlgorithms); + // } + // } + + void _handleGlobalRequestSuccess(Uint8List payload) { + final message = SSH_Message_Request_Success.decode(payload); + printTrace?.call('<- $socket: $message'); + _globalRequestReplyQueue.add(message); + } + + void _handleGlobalRequestFailure(Uint8List payload) { + final message = SSH_Message_Request_Failure.decode(payload); + printTrace?.call('<- $socket: $message'); + _globalRequestReplyQueue.add(message); + } + + void _handleChannelOpen(Uint8List payload) { + final message = SSH_Message_Channel_Open.decode(payload); + printTrace?.call('<- $socket: $message'); + + switch (message.channelType) { + case 'forwarded-tcpip': + return _handleForwardedTcpipChannelOpen(message); + } + + printDebug?.call('unknown channelType: ${message.channelType}'); + final reply = SSH_Message_Channel_Open_Failure( + recipientChannel: message.senderChannel, + reasonCode: SSH_Message_Channel_Open_Failure.codeUnknownChannelType, + description: 'unknown channel type: ${message.channelType}', + ); + _sendMessage(reply); + } + + void _handleForwardedTcpipChannelOpen(SSH_Message_Channel_Open message) { + printDebug?.call('SSHClient._handleTcpipForwardChannelOpen'); + + final remoteForward = _findRemoteForward(message.host!, message.port!); + + if (remoteForward == null) { + printDebug?.call('unknown remote forward: $message'); + final reply = SSH_Message_Channel_Open_Failure( + recipientChannel: message.senderChannel, + reasonCode: SSH_Message_Channel_Open_Failure.codeUnknownChannelType, + description: 'unknown remote forward: $message', + ); + _sendMessage(reply); + return; + } + + if (remoteForward.filter != null) { + if (!remoteForward.filter!(message.host!, message.port!)) { + printDebug?.call('remote forward rejected by filter: $message'); + final reply = SSH_Message_Channel_Open_Failure( + recipientChannel: message.senderChannel, + reasonCode: 1, // SSH_OPEN_ADMINISTRATIVELY_PROHIBITED + description: 'rejected by filter', + ); + _sendMessage(reply); + return; + } + } + + final localChannelId = _channelIdAllocator.allocate(); + + final confirmation = SSH_Message_Channel_Confirmation( + recipientChannel: message.senderChannel, + senderChannel: localChannelId, + initialWindowSize: _initialWindowSize, + maximumPacketSize: _maximumPacketSize, + data: Uint8List(0), + ); + + _sendMessage(confirmation); + + final channelController = _acceptChannel( + localChannelId: localChannelId, + remoteChannelId: message.senderChannel, + remoteInitialWindowSize: message.initialWindowSize, + remoteMaximumPacketSize: message.maximumPacketSize, + ); + + remoteForward._connections.add( + SSHForwardChannel(channelController.channel), + ); + } + + /// Finds a remote forward that matches the given host and port. + SSHRemoteForward? _findRemoteForward(String host, int port) { + final result = _remoteForwards.where( + (forward) => forward.host == host && forward.port == port, + ); + return result.isEmpty ? null : result.first; + } + + void _handleChannelConfirmation(Uint8List payload) { + final message = SSH_Message_Channel_Confirmation.decode(payload); + printTrace?.call('<- $socket: $message'); + _dispatchChannelOpenReply(message.recipientChannel, message); + } + + void _handleChannelOpenFailure(Uint8List payload) { + final message = SSH_Message_Channel_Open_Failure.decode(payload); + printTrace?.call('<- $socket: $message'); + _dispatchChannelOpenReply(message.recipientChannel, message); + } + + void _handleChannelWindowAdjust(Uint8List payload) { + final message = SSH_Message_Channel_Window_Adjust.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelRequest(Uint8List payload) { + final message = SSH_Message_Channel_Request.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelSuccess(Uint8List payload) { + final message = SSH_Message_Channel_Success.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelFailure(Uint8List payload) { + final message = SSH_Message_Channel_Failure.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelData(Uint8List payload) { + final message = SSH_Message_Channel_Data.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelExtendedData(Uint8List payload) { + final message = SSH_Message_Channel_Extended_Data.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelEOF(Uint8List payload) { + final message = SSH_Message_Channel_EOF.decode(payload); + printTrace?.call('<- $socket: $message'); + _channels[message.recipientChannel]?.handleMessage(message); + } + + void _handleChannelClose(Uint8List payload) { + final message = SSH_Message_Channel_Close.decode(payload); + printTrace?.call('<- $socket: $message'); + final channel = _channels[message.recipientChannel]; + if (channel != null) { + channel.close(); + _channels.remove(message.recipientChannel); + _channelIdAllocator.release(message.recipientChannel); + } + } + + void _requestAuthentication() { + printDebug?.call('SSHClient._requestAuthentication'); + _sendMessage(SSH_Message_Service_Request('ssh-userauth')); + } + + void _startAuthentication() { + printDebug?.call('SSHClient._startAuthentication'); + + if (identities != null && identities!.isNotEmpty) { + _authMethodsLeft.add(SSHAuthMethod.publicKey); + } + + if (onPasswordRequest != null) { + _authMethodsLeft.add(SSHAuthMethod.password); + } + + if (onUserInfoRequest != null) { + _authMethodsLeft.add(SSHAuthMethod.keyboardInteractive); + } + + _authMethodsLeft.add(SSHAuthMethod.none); + + _tryNextAuthMethod(); + } + + void _tryNextAuthMethod() { + printDebug?.call('SSHClient._tryNextAuthenticationMethod'); + + if (_currentAuthMethod == SSHAuthMethod.publicKey) { + if (_keyPairsLeft.isNotEmpty) { + return _authWithNextPublicKey(); + } + } + + if (_authMethodsLeft.isEmpty) { + return _authenticated.completeError( + SSHAuthFailError('All authentication methods failed'), + StackTrace.current, + ); + } + + _currentAuthMethod = _authMethodsLeft.removeFirst(); + printDebug?.call('_currentAuthMethod = $_currentAuthMethod'); + + switch (_currentAuthMethod!) { + case SSHAuthMethod.none: + return _authWithNone(); + case SSHAuthMethod.password: + return _catch(() => _authWithPassword()); + case SSHAuthMethod.publicKey: + return _authWithNextPublicKey(); + case SSHAuthMethod.keyboardInteractive: + return _authWithKeyboardInteractive(); + } + } + + void _authWithNone() { + printDebug?.call('SSHClient._authWithNone'); + _sendMessage(SSH_Message_Userauth_Request.none(user: username)); + } + + Future _authWithPassword() async { + printDebug?.call('SSHClient._authWithPassword'); + + final password = await onPasswordRequest!(); + if (password == null) { + _tryNextAuthMethod(); + return; + } + + _sendMessage( + SSH_Message_Userauth_Request.password(user: username, password: password), + ); + } + + void _authWithNextPublicKey() { + printDebug?.call('SSHClient._authWithPublicKey'); + + final keyPair = _keyPairsLeft.removeFirst(); + + final challenge = _transport.composeChallenge( + username: username, + service: 'ssh-connection', + publicKeyAlgorithm: keyPair.type, + publicKey: keyPair.toPublicKey().encode(), + ); + + _sendMessage( + SSH_Message_Userauth_Request.publicKey( + username: username, + publicKeyAlgorithm: keyPair.type, + publicKey: keyPair.toPublicKey().encode(), + signature: keyPair.sign(challenge).encode(), + // signature: null, + ), + ); + } + + void _authWithKeyboardInteractive() { + printDebug?.call('SSHClient._authWithKeyboardInteractive'); + _sendMessage( + SSH_Message_Userauth_Request.keyboardInteractive(user: username), + ); + } + + Future _openSessionChannel() async { + final localChannelId = _channelIdAllocator.allocate(); + + final request = SSH_Message_Channel_Open.session( + senderChannel: localChannelId, + initialWindowSize: _initialWindowSize, + maximumPacketSize: _maximumPacketSize, + ); + _sendMessage(request); + + return await _waitChannelOpen(localChannelId); + } + + Future _openForwardLocalChannel( + String bindAddress, + int bindPort, + String remoteAddress, + int remotePort, + ) async { + final localChannelId = _channelIdAllocator.allocate(); + + final request = SSH_Message_Channel_Open.directTcpip( + senderChannel: localChannelId, + initialWindowSize: _initialWindowSize, + maximumPacketSize: _maximumPacketSize, + host: remoteAddress, + port: remotePort, + originatorIP: bindAddress, + originatorPort: bindPort, + ); + _sendMessage(request); + + return await _waitChannelOpen(localChannelId); + } + + Future _waitChannelOpen( + SSHChannelId localChannelId, + ) async { + final message = await _waitChannelOpenReply(localChannelId); + if (message is SSH_Message_Channel_Open_Failure) { + throw SSHChannelOpenError(message.reasonCode, message.description); + } + + final reply = message as SSH_Message_Channel_Confirmation; + if (reply.recipientChannel != localChannelId) { + throw SSHStateError('Unexpected channel confirmation'); + } + + return _acceptChannel( + localChannelId: localChannelId, + remoteChannelId: reply.senderChannel, + remoteInitialWindowSize: reply.initialWindowSize, + remoteMaximumPacketSize: reply.maximumPacketSize, + ); + } + + SSHChannelController _acceptChannel({ + required SSHChannelId localChannelId, + required SSHChannelId remoteChannelId, + required int remoteInitialWindowSize, + required int remoteMaximumPacketSize, + }) { + final channelController = SSHChannelController( + localId: localChannelId, + localInitialWindowSize: _initialWindowSize, + localMaximumPacketSize: _maximumPacketSize, + remoteId: remoteChannelId, + remoteInitialWindowSize: remoteInitialWindowSize, + remoteMaximumPacketSize: remoteMaximumPacketSize, + sendMessage: _sendMessage, + printDebug: printDebug, + ); + + _channels[localChannelId] = channelController; + return channelController; + } + + Future _waitChannelOpenReply(SSHChannelId id) async { + if (_channelOpenReplyWaiters.containsKey(id)) { + printDebug?.call('_waitChannelOpenReply: already waiting for $id'); + return _channelOpenReplyWaiters[id]!.future; + } + final replyCompleter = Completer(); + _channelOpenReplyWaiters[id] = replyCompleter; + return replyCompleter.future; + } + + void _dispatchChannelOpenReply(SSHChannelId id, SSHMessage message) { + if (!_channelOpenReplyWaiters.containsKey(id)) { + printDebug?.call('_dispatchChannelOpenReply: no pending request for $id'); + return; + } + final replyCompleter = _channelOpenReplyWaiters.remove(id)!; + replyCompleter.complete(message); + } +} + +class SSHRemoteForward { + final String host; + + final int port; + + final SSHRemoteConnectionFilter? filter; + + SSHRemoteForward(this._client, this.host, this.port, this.filter); + + final SSHClient _client; + + final _connections = StreamController(); + + Stream get connections => _connections.stream; + + void close() { + _connections.close(); + _client.cancelForwardRemote(this); + } + + @override + String toString() => '$runtimeType($host:$port)'; +} diff --git a/third_party/dartssh2/lib/src/ssh_errors.dart b/third_party/dartssh2/lib/src/ssh_errors.dart new file mode 100644 index 0000000..68407de --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_errors.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/ssh_forward.dart b/third_party/dartssh2/lib/src/ssh_forward.dart new file mode 100644 index 0000000..2494df3 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_forward.dart @@ -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>(); + + /// Data received from the remote host. + @override + Stream get stream => _channel.stream.map((data) => data.bytes); + + /// Write to this sink to send data to the remote host. + @override + StreamSink> get sink => _sinkController.sink; + + /// Close our end of the channel. Returns a future that waits for the + /// other side to close. + @override + Future close() => _channel.close(); + + /// A future that completes when both ends of the channel are closed. + @override + Future get done => _channel.done; + + /// Destroys the socket in both directions. + @override + void destroy() { + _channel.destroy(); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_hostkey.dart b/third_party/dartssh2/lib/src/ssh_hostkey.dart new file mode 100644 index 0000000..81fa4d2 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_hostkey.dart @@ -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(); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_keepalive.dart b/third_party/dartssh2/lib/src/ssh_keepalive.dart new file mode 100644 index 0000000..a6bc75d --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_keepalive.dart @@ -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; + } +} diff --git a/third_party/dartssh2/lib/src/ssh_kex.dart b/third_party/dartssh2/lib/src/ssh_kex.dart new file mode 100644 index 0000000..414bbd5 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_kex.dart @@ -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); +} diff --git a/third_party/dartssh2/lib/src/ssh_kex_utils.dart b/third_party/dartssh2/lib/src/ssh_kex_utils.dart new file mode 100644 index 0000000..1ab3fca --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_kex_utils.dart @@ -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({ + required List localAlgorithms, + required List 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; + } + } +} diff --git a/third_party/dartssh2/lib/src/ssh_key_pair.dart b/third_party/dartssh2/lib/src/ssh_key_pair.dart new file mode 100644 index 0000000..ee8acb0 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_key_pair.dart @@ -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 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 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 = []; + 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 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 = []; + 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(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(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)'; + } +} diff --git a/third_party/dartssh2/lib/src/ssh_message.dart b/third_party/dartssh2/lib/src/ssh_message.dart new file mode 100644 index 0000000..10f9398 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_message.dart @@ -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 readNameList() { + final string = utf8.decode(readString()); + final list = string.split(','); + return list; + } + + List readStringList() { + final list = []; + 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 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(); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_packet.dart b/third_party/dartssh2/lib/src/ssh_packet.dart new file mode 100644 index 0000000..e130a82 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_packet.dart @@ -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++; + } + } +} diff --git a/third_party/dartssh2/lib/src/ssh_pem.dart b/third_party/dartssh2/lib/src/ssh_pem.dart new file mode 100644 index 0000000..a5c0e07 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_pem.dart @@ -0,0 +1,94 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +class SSHPem { + final String type; + + final Map 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 = {}; + + final pemBodyLines = []; + + 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})'; + } +} diff --git a/third_party/dartssh2/lib/src/ssh_session.dart b/third_party/dartssh2/lib/src/ssh_session.dart new file mode 100644 index 0000000..f22d2bc --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_session.dart @@ -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 get stdin => _stdinController.sink; + + /// Stdout of the remote process. + Stream 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 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 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(); + + late final _stdoutController = StreamController( + onPause: _pauseChannelData, + onResume: _resumeChannelData, + ); + + late final _stderrController = StreamController( + 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)'; + } +} diff --git a/third_party/dartssh2/lib/src/ssh_signal.dart b/third_party/dartssh2/lib/src/ssh_signal.dart new file mode 100644 index 0000000..34c0b8f --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_signal.dart @@ -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'); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_transport.dart b/third_party/dartssh2/lib/src/ssh_transport.dart new file mode 100644 index 0000000..03540b6 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_transport.dart @@ -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 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 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(); + + /// 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(); + } +} diff --git a/third_party/dartssh2/lib/src/ssh_userauth.dart b/third_party/dartssh2/lib/src/ssh_userauth.dart new file mode 100644 index 0000000..cfb6f69 --- /dev/null +++ b/third_party/dartssh2/lib/src/ssh_userauth.dart @@ -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 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; +} diff --git a/third_party/dartssh2/lib/src/utils/async_queue.dart b/third_party/dartssh2/lib/src/utils/async_queue.dart new file mode 100644 index 0000000..cc23550 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/async_queue.dart @@ -0,0 +1,36 @@ +import 'dart:async'; + +import 'dart:collection'; + +/// A queue that consumers can wait asynchronously for items to be added. +class AsyncQueue { + final _data = Queue(); + + final _completers = Queue>(); + + /// 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 get next { + if (_data.isNotEmpty) { + return _data.removeFirst(); + } else { + final completer = Completer(); + _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); + } + } +} diff --git a/third_party/dartssh2/lib/src/utils/bcrypt.dart b/third_party/dartssh2/lib/src/utils/bcrypt.dart new file mode 100644 index 0000000..75c69d5 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/bcrypt.dart @@ -0,0 +1,1369 @@ +// ignore_for_file: non_constant_identifier_names, constant_identifier_names + +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ + +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:pinenacl/tweetnacl.dart'; + +int crypto_hash_sha512(Uint8List out, Uint8List m, int mlen) { + return TweetNaCl.crypto_hash(out, Uint8List.sublistView(m, 0, mlen)); +} + +var BLF_J = 0; + +class Blowfish { + List S = [ + Uint32List.fromList([ + 0xd1310ba6, + 0x98dfb5ac, + 0x2ffd72db, + 0xd01adfb7, + 0xb8e1afed, + 0x6a267e96, + 0xba7c9045, + 0xf12c7f99, + 0x24a19947, + 0xb3916cf7, + 0x0801f2e2, + 0x858efc16, + 0x636920d8, + 0x71574e69, + 0xa458fea3, + 0xf4933d7e, + 0x0d95748f, + 0x728eb658, + 0x718bcd58, + 0x82154aee, + 0x7b54a41d, + 0xc25a59b5, + 0x9c30d539, + 0x2af26013, + 0xc5d1b023, + 0x286085f0, + 0xca417918, + 0xb8db38ef, + 0x8e79dcb0, + 0x603a180e, + 0x6c9e0e8b, + 0xb01e8a3e, + 0xd71577c1, + 0xbd314b27, + 0x78af2fda, + 0x55605c60, + 0xe65525f3, + 0xaa55ab94, + 0x57489862, + 0x63e81440, + 0x55ca396a, + 0x2aab10b6, + 0xb4cc5c34, + 0x1141e8ce, + 0xa15486af, + 0x7c72e993, + 0xb3ee1411, + 0x636fbc2a, + 0x2ba9c55d, + 0x741831f6, + 0xce5c3e16, + 0x9b87931e, + 0xafd6ba33, + 0x6c24cf5c, + 0x7a325381, + 0x28958677, + 0x3b8f4898, + 0x6b4bb9af, + 0xc4bfe81b, + 0x66282193, + 0x61d809cc, + 0xfb21a991, + 0x487cac60, + 0x5dec8032, + 0xef845d5d, + 0xe98575b1, + 0xdc262302, + 0xeb651b88, + 0x23893e81, + 0xd396acc5, + 0x0f6d6ff3, + 0x83f44239, + 0x2e0b4482, + 0xa4842004, + 0x69c8f04a, + 0x9e1f9b5e, + 0x21c66842, + 0xf6e96c9a, + 0x670c9c61, + 0xabd388f0, + 0x6a51a0d2, + 0xd8542f68, + 0x960fa728, + 0xab5133a3, + 0x6eef0b6c, + 0x137a3be4, + 0xba3bf050, + 0x7efb2a98, + 0xa1f1651d, + 0x39af0176, + 0x66ca593e, + 0x82430e88, + 0x8cee8619, + 0x456f9fb4, + 0x7d84a5c3, + 0x3b8b5ebe, + 0xe06f75d8, + 0x85c12073, + 0x401a449f, + 0x56c16aa6, + 0x4ed3aa62, + 0x363f7706, + 0x1bfedf72, + 0x429b023d, + 0x37d0d724, + 0xd00a1248, + 0xdb0fead3, + 0x49f1c09b, + 0x075372c9, + 0x80991b7b, + 0x25d479d8, + 0xf6e8def7, + 0xe3fe501a, + 0xb6794c3b, + 0x976ce0bd, + 0x04c006ba, + 0xc1a94fb6, + 0x409f60c4, + 0x5e5c9ec2, + 0x196a2463, + 0x68fb6faf, + 0x3e6c53b5, + 0x1339b2eb, + 0x3b52ec6f, + 0x6dfc511f, + 0x9b30952c, + 0xcc814544, + 0xaf5ebd09, + 0xbee3d004, + 0xde334afd, + 0x660f2807, + 0x192e4bb3, + 0xc0cba857, + 0x45c8740f, + 0xd20b5f39, + 0xb9d3fbdb, + 0x5579c0bd, + 0x1a60320a, + 0xd6a100c6, + 0x402c7279, + 0x679f25fe, + 0xfb1fa3cc, + 0x8ea5e9f8, + 0xdb3222f8, + 0x3c7516df, + 0xfd616b15, + 0x2f501ec8, + 0xad0552ab, + 0x323db5fa, + 0xfd238760, + 0x53317b48, + 0x3e00df82, + 0x9e5c57bb, + 0xca6f8ca0, + 0x1a87562e, + 0xdf1769db, + 0xd542a8f6, + 0x287effc3, + 0xac6732c6, + 0x8c4f5573, + 0x695b27b0, + 0xbbca58c8, + 0xe1ffa35d, + 0xb8f011a0, + 0x10fa3d98, + 0xfd2183b8, + 0x4afcb56c, + 0x2dd1d35b, + 0x9a53e479, + 0xb6f84565, + 0xd28e49bc, + 0x4bfb9790, + 0xe1ddf2da, + 0xa4cb7e33, + 0x62fb1341, + 0xcee4c6e8, + 0xef20cada, + 0x36774c01, + 0xd07e9efe, + 0x2bf11fb4, + 0x95dbda4d, + 0xae909198, + 0xeaad8e71, + 0x6b93d5a0, + 0xd08ed1d0, + 0xafc725e0, + 0x8e3c5b2f, + 0x8e7594b7, + 0x8ff6e2fb, + 0xf2122b64, + 0x8888b812, + 0x900df01c, + 0x4fad5ea0, + 0x688fc31c, + 0xd1cff191, + 0xb3a8c1ad, + 0x2f2f2218, + 0xbe0e1777, + 0xea752dfe, + 0x8b021fa1, + 0xe5a0cc0f, + 0xb56f74e8, + 0x18acf3d6, + 0xce89e299, + 0xb4a84fe0, + 0xfd13e0b7, + 0x7cc43b81, + 0xd2ada8d9, + 0x165fa266, + 0x80957705, + 0x93cc7314, + 0x211a1477, + 0xe6ad2065, + 0x77b5fa86, + 0xc75442f5, + 0xfb9d35cf, + 0xebcdaf0c, + 0x7b3e89a0, + 0xd6411bd3, + 0xae1e7e49, + 0x00250e2d, + 0x2071b35e, + 0x226800bb, + 0x57b8e0af, + 0x2464369b, + 0xf009b91e, + 0x5563911d, + 0x59dfa6aa, + 0x78c14389, + 0xd95a537f, + 0x207d5ba2, + 0x02e5b9c5, + 0x83260376, + 0x6295cfa9, + 0x11c81968, + 0x4e734a41, + 0xb3472dca, + 0x7b14a94a, + 0x1b510052, + 0x9a532915, + 0xd60f573f, + 0xbc9bc6e4, + 0x2b60a476, + 0x81e67400, + 0x08ba6fb5, + 0x571be91f, + 0xf296ec6b, + 0x2a0dd915, + 0xb6636521, + 0xe7b9f9b6, + 0xff34052e, + 0xc5855664, + 0x53b02d5d, + 0xa99f8fa1, + 0x08ba4799, + 0x6e85076a, + ]), + Uint32List.fromList([ + 0x4b7a70e9, + 0xb5b32944, + 0xdb75092e, + 0xc4192623, + 0xad6ea6b0, + 0x49a7df7d, + 0x9cee60b8, + 0x8fedb266, + 0xecaa8c71, + 0x699a17ff, + 0x5664526c, + 0xc2b19ee1, + 0x193602a5, + 0x75094c29, + 0xa0591340, + 0xe4183a3e, + 0x3f54989a, + 0x5b429d65, + 0x6b8fe4d6, + 0x99f73fd6, + 0xa1d29c07, + 0xefe830f5, + 0x4d2d38e6, + 0xf0255dc1, + 0x4cdd2086, + 0x8470eb26, + 0x6382e9c6, + 0x021ecc5e, + 0x09686b3f, + 0x3ebaefc9, + 0x3c971814, + 0x6b6a70a1, + 0x687f3584, + 0x52a0e286, + 0xb79c5305, + 0xaa500737, + 0x3e07841c, + 0x7fdeae5c, + 0x8e7d44ec, + 0x5716f2b8, + 0xb03ada37, + 0xf0500c0d, + 0xf01c1f04, + 0x0200b3ff, + 0xae0cf51a, + 0x3cb574b2, + 0x25837a58, + 0xdc0921bd, + 0xd19113f9, + 0x7ca92ff6, + 0x94324773, + 0x22f54701, + 0x3ae5e581, + 0x37c2dadc, + 0xc8b57634, + 0x9af3dda7, + 0xa9446146, + 0x0fd0030e, + 0xecc8c73e, + 0xa4751e41, + 0xe238cd99, + 0x3bea0e2f, + 0x3280bba1, + 0x183eb331, + 0x4e548b38, + 0x4f6db908, + 0x6f420d03, + 0xf60a04bf, + 0x2cb81290, + 0x24977c79, + 0x5679b072, + 0xbcaf89af, + 0xde9a771f, + 0xd9930810, + 0xb38bae12, + 0xdccf3f2e, + 0x5512721f, + 0x2e6b7124, + 0x501adde6, + 0x9f84cd87, + 0x7a584718, + 0x7408da17, + 0xbc9f9abc, + 0xe94b7d8c, + 0xec7aec3a, + 0xdb851dfa, + 0x63094366, + 0xc464c3d2, + 0xef1c1847, + 0x3215d908, + 0xdd433b37, + 0x24c2ba16, + 0x12a14d43, + 0x2a65c451, + 0x50940002, + 0x133ae4dd, + 0x71dff89e, + 0x10314e55, + 0x81ac77d6, + 0x5f11199b, + 0x043556f1, + 0xd7a3c76b, + 0x3c11183b, + 0x5924a509, + 0xf28fe6ed, + 0x97f1fbfa, + 0x9ebabf2c, + 0x1e153c6e, + 0x86e34570, + 0xeae96fb1, + 0x860e5e0a, + 0x5a3e2ab3, + 0x771fe71c, + 0x4e3d06fa, + 0x2965dcb9, + 0x99e71d0f, + 0x803e89d6, + 0x5266c825, + 0x2e4cc978, + 0x9c10b36a, + 0xc6150eba, + 0x94e2ea78, + 0xa5fc3c53, + 0x1e0a2df4, + 0xf2f74ea7, + 0x361d2b3d, + 0x1939260f, + 0x19c27960, + 0x5223a708, + 0xf71312b6, + 0xebadfe6e, + 0xeac31f66, + 0xe3bc4595, + 0xa67bc883, + 0xb17f37d1, + 0x018cff28, + 0xc332ddef, + 0xbe6c5aa5, + 0x65582185, + 0x68ab9802, + 0xeecea50f, + 0xdb2f953b, + 0x2aef7dad, + 0x5b6e2f84, + 0x1521b628, + 0x29076170, + 0xecdd4775, + 0x619f1510, + 0x13cca830, + 0xeb61bd96, + 0x0334fe1e, + 0xaa0363cf, + 0xb5735c90, + 0x4c70a239, + 0xd59e9e0b, + 0xcbaade14, + 0xeecc86bc, + 0x60622ca7, + 0x9cab5cab, + 0xb2f3846e, + 0x648b1eaf, + 0x19bdf0ca, + 0xa02369b9, + 0x655abb50, + 0x40685a32, + 0x3c2ab4b3, + 0x319ee9d5, + 0xc021b8f7, + 0x9b540b19, + 0x875fa099, + 0x95f7997e, + 0x623d7da8, + 0xf837889a, + 0x97e32d77, + 0x11ed935f, + 0x16681281, + 0x0e358829, + 0xc7e61fd6, + 0x96dedfa1, + 0x7858ba99, + 0x57f584a5, + 0x1b227263, + 0x9b83c3ff, + 0x1ac24696, + 0xcdb30aeb, + 0x532e3054, + 0x8fd948e4, + 0x6dbc3128, + 0x58ebf2ef, + 0x34c6ffea, + 0xfe28ed61, + 0xee7c3c73, + 0x5d4a14d9, + 0xe864b7e3, + 0x42105d14, + 0x203e13e0, + 0x45eee2b6, + 0xa3aaabea, + 0xdb6c4f15, + 0xfacb4fd0, + 0xc742f442, + 0xef6abbb5, + 0x654f3b1d, + 0x41cd2105, + 0xd81e799e, + 0x86854dc7, + 0xe44b476a, + 0x3d816250, + 0xcf62a1f2, + 0x5b8d2646, + 0xfc8883a0, + 0xc1c7b6a3, + 0x7f1524c3, + 0x69cb7492, + 0x47848a0b, + 0x5692b285, + 0x095bbf00, + 0xad19489d, + 0x1462b174, + 0x23820e00, + 0x58428d2a, + 0x0c55f5ea, + 0x1dadf43e, + 0x233f7061, + 0x3372f092, + 0x8d937e41, + 0xd65fecf1, + 0x6c223bdb, + 0x7cde3759, + 0xcbee7460, + 0x4085f2a7, + 0xce77326e, + 0xa6078084, + 0x19f8509e, + 0xe8efd855, + 0x61d99735, + 0xa969a7aa, + 0xc50c06c2, + 0x5a04abfc, + 0x800bcadc, + 0x9e447a2e, + 0xc3453484, + 0xfdd56705, + 0x0e1e9ec9, + 0xdb73dbd3, + 0x105588cd, + 0x675fda79, + 0xe3674340, + 0xc5c43465, + 0x713e38d8, + 0x3d28f89e, + 0xf16dff20, + 0x153e21e7, + 0x8fb03d4a, + 0xe6e39f2b, + 0xdb83adf7, + ]), + Uint32List.fromList([ + 0xe93d5a68, + 0x948140f7, + 0xf64c261c, + 0x94692934, + 0x411520f7, + 0x7602d4f7, + 0xbcf46b2e, + 0xd4a20068, + 0xd4082471, + 0x3320f46a, + 0x43b7d4b7, + 0x500061af, + 0x1e39f62e, + 0x97244546, + 0x14214f74, + 0xbf8b8840, + 0x4d95fc1d, + 0x96b591af, + 0x70f4ddd3, + 0x66a02f45, + 0xbfbc09ec, + 0x03bd9785, + 0x7fac6dd0, + 0x31cb8504, + 0x96eb27b3, + 0x55fd3941, + 0xda2547e6, + 0xabca0a9a, + 0x28507825, + 0x530429f4, + 0x0a2c86da, + 0xe9b66dfb, + 0x68dc1462, + 0xd7486900, + 0x680ec0a4, + 0x27a18dee, + 0x4f3ffea2, + 0xe887ad8c, + 0xb58ce006, + 0x7af4d6b6, + 0xaace1e7c, + 0xd3375fec, + 0xce78a399, + 0x406b2a42, + 0x20fe9e35, + 0xd9f385b9, + 0xee39d7ab, + 0x3b124e8b, + 0x1dc9faf7, + 0x4b6d1856, + 0x26a36631, + 0xeae397b2, + 0x3a6efa74, + 0xdd5b4332, + 0x6841e7f7, + 0xca7820fb, + 0xfb0af54e, + 0xd8feb397, + 0x454056ac, + 0xba489527, + 0x55533a3a, + 0x20838d87, + 0xfe6ba9b7, + 0xd096954b, + 0x55a867bc, + 0xa1159a58, + 0xcca92963, + 0x99e1db33, + 0xa62a4a56, + 0x3f3125f9, + 0x5ef47e1c, + 0x9029317c, + 0xfdf8e802, + 0x04272f70, + 0x80bb155c, + 0x05282ce3, + 0x95c11548, + 0xe4c66d22, + 0x48c1133f, + 0xc70f86dc, + 0x07f9c9ee, + 0x41041f0f, + 0x404779a4, + 0x5d886e17, + 0x325f51eb, + 0xd59bc0d1, + 0xf2bcc18f, + 0x41113564, + 0x257b7834, + 0x602a9c60, + 0xdff8e8a3, + 0x1f636c1b, + 0x0e12b4c2, + 0x02e1329e, + 0xaf664fd1, + 0xcad18115, + 0x6b2395e0, + 0x333e92e1, + 0x3b240b62, + 0xeebeb922, + 0x85b2a20e, + 0xe6ba0d99, + 0xde720c8c, + 0x2da2f728, + 0xd0127845, + 0x95b794fd, + 0x647d0862, + 0xe7ccf5f0, + 0x5449a36f, + 0x877d48fa, + 0xc39dfd27, + 0xf33e8d1e, + 0x0a476341, + 0x992eff74, + 0x3a6f6eab, + 0xf4f8fd37, + 0xa812dc60, + 0xa1ebddf8, + 0x991be14c, + 0xdb6e6b0d, + 0xc67b5510, + 0x6d672c37, + 0x2765d43b, + 0xdcd0e804, + 0xf1290dc7, + 0xcc00ffa3, + 0xb5390f92, + 0x690fed0b, + 0x667b9ffb, + 0xcedb7d9c, + 0xa091cf0b, + 0xd9155ea3, + 0xbb132f88, + 0x515bad24, + 0x7b9479bf, + 0x763bd6eb, + 0x37392eb3, + 0xcc115979, + 0x8026e297, + 0xf42e312d, + 0x6842ada7, + 0xc66a2b3b, + 0x12754ccc, + 0x782ef11c, + 0x6a124237, + 0xb79251e7, + 0x06a1bbe6, + 0x4bfb6350, + 0x1a6b1018, + 0x11caedfa, + 0x3d25bdd8, + 0xe2e1c3c9, + 0x44421659, + 0x0a121386, + 0xd90cec6e, + 0xd5abea2a, + 0x64af674e, + 0xda86a85f, + 0xbebfe988, + 0x64e4c3fe, + 0x9dbc8057, + 0xf0f7c086, + 0x60787bf8, + 0x6003604d, + 0xd1fd8346, + 0xf6381fb0, + 0x7745ae04, + 0xd736fccc, + 0x83426b33, + 0xf01eab71, + 0xb0804187, + 0x3c005e5f, + 0x77a057be, + 0xbde8ae24, + 0x55464299, + 0xbf582e61, + 0x4e58f48f, + 0xf2ddfda2, + 0xf474ef38, + 0x8789bdc2, + 0x5366f9c3, + 0xc8b38e74, + 0xb475f255, + 0x46fcd9b9, + 0x7aeb2661, + 0x8b1ddf84, + 0x846a0e79, + 0x915f95e2, + 0x466e598e, + 0x20b45770, + 0x8cd55591, + 0xc902de4c, + 0xb90bace1, + 0xbb8205d0, + 0x11a86248, + 0x7574a99e, + 0xb77f19b6, + 0xe0a9dc09, + 0x662d09a1, + 0xc4324633, + 0xe85a1f02, + 0x09f0be8c, + 0x4a99a025, + 0x1d6efe10, + 0x1ab93d1d, + 0x0ba5a4df, + 0xa186f20f, + 0x2868f169, + 0xdcb7da83, + 0x573906fe, + 0xa1e2ce9b, + 0x4fcd7f52, + 0x50115e01, + 0xa70683fa, + 0xa002b5c4, + 0x0de6d027, + 0x9af88c27, + 0x773f8641, + 0xc3604c06, + 0x61a806b5, + 0xf0177a28, + 0xc0f586e0, + 0x006058aa, + 0x30dc7d62, + 0x11e69ed7, + 0x2338ea63, + 0x53c2dd94, + 0xc2c21634, + 0xbbcbee56, + 0x90bcb6de, + 0xebfc7da1, + 0xce591d76, + 0x6f05e409, + 0x4b7c0188, + 0x39720a3d, + 0x7c927c24, + 0x86e3725f, + 0x724d9db9, + 0x1ac15bb4, + 0xd39eb8fc, + 0xed545578, + 0x08fca5b5, + 0xd83d7cd3, + 0x4dad0fc4, + 0x1e50ef5e, + 0xb161e6f8, + 0xa28514d9, + 0x6c51133c, + 0x6fd5c7e7, + 0x56e14ec4, + 0x362abfce, + 0xddc6c837, + 0xd79a3234, + 0x92638212, + 0x670efa8e, + 0x406000e0, + ]), + Uint32List.fromList([ + 0x3a39ce37, + 0xd3faf5cf, + 0xabc27737, + 0x5ac52d1b, + 0x5cb0679e, + 0x4fa33742, + 0xd3822740, + 0x99bc9bbe, + 0xd5118e9d, + 0xbf0f7315, + 0xd62d1c7e, + 0xc700c47b, + 0xb78c1b6b, + 0x21a19045, + 0xb26eb1be, + 0x6a366eb4, + 0x5748ab2f, + 0xbc946e79, + 0xc6a376d2, + 0x6549c2c8, + 0x530ff8ee, + 0x468dde7d, + 0xd5730a1d, + 0x4cd04dc6, + 0x2939bbdb, + 0xa9ba4650, + 0xac9526e8, + 0xbe5ee304, + 0xa1fad5f0, + 0x6a2d519a, + 0x63ef8ce2, + 0x9a86ee22, + 0xc089c2b8, + 0x43242ef6, + 0xa51e03aa, + 0x9cf2d0a4, + 0x83c061ba, + 0x9be96a4d, + 0x8fe51550, + 0xba645bd6, + 0x2826a2f9, + 0xa73a3ae1, + 0x4ba99586, + 0xef5562e9, + 0xc72fefd3, + 0xf752f7da, + 0x3f046f69, + 0x77fa0a59, + 0x80e4a915, + 0x87b08601, + 0x9b09e6ad, + 0x3b3ee593, + 0xe990fd5a, + 0x9e34d797, + 0x2cf0b7d9, + 0x022b8b51, + 0x96d5ac3a, + 0x017da67d, + 0xd1cf3ed6, + 0x7c7d2d28, + 0x1f9f25cf, + 0xadf2b89b, + 0x5ad6b472, + 0x5a88f54c, + 0xe029ac71, + 0xe019a5e6, + 0x47b0acfd, + 0xed93fa9b, + 0xe8d3c48d, + 0x283b57cc, + 0xf8d56629, + 0x79132e28, + 0x785f0191, + 0xed756055, + 0xf7960e44, + 0xe3d35e8c, + 0x15056dd4, + 0x88f46dba, + 0x03a16125, + 0x0564f0bd, + 0xc3eb9e15, + 0x3c9057a2, + 0x97271aec, + 0xa93a072a, + 0x1b3f6d9b, + 0x1e6321f5, + 0xf59c66fb, + 0x26dcf319, + 0x7533d928, + 0xb155fdf5, + 0x03563482, + 0x8aba3cbb, + 0x28517711, + 0xc20ad9f8, + 0xabcc5167, + 0xccad925f, + 0x4de81751, + 0x3830dc8e, + 0x379d5862, + 0x9320f991, + 0xea7a90c2, + 0xfb3e7bce, + 0x5121ce64, + 0x774fbe32, + 0xa8b6e37e, + 0xc3293d46, + 0x48de5369, + 0x6413e680, + 0xa2ae0810, + 0xdd6db224, + 0x69852dfd, + 0x09072166, + 0xb39a460a, + 0x6445c0dd, + 0x586cdecf, + 0x1c20c8ae, + 0x5bbef7dd, + 0x1b588d40, + 0xccd2017f, + 0x6bb4e3bb, + 0xdda26a7e, + 0x3a59ff45, + 0x3e350a44, + 0xbcb4cdd5, + 0x72eacea8, + 0xfa6484bb, + 0x8d6612ae, + 0xbf3c6f47, + 0xd29be463, + 0x542f5d9e, + 0xaec2771b, + 0xf64e6370, + 0x740e0d8d, + 0xe75b1357, + 0xf8721671, + 0xaf537d5d, + 0x4040cb08, + 0x4eb4e2cc, + 0x34d2466a, + 0x0115af84, + 0xe1b00428, + 0x95983a1d, + 0x06b89fb4, + 0xce6ea048, + 0x6f3f3b82, + 0x3520ab82, + 0x011a1d4b, + 0x277227f8, + 0x611560b1, + 0xe7933fdc, + 0xbb3a792b, + 0x344525bd, + 0xa08839e1, + 0x51ce794b, + 0x2f32c9b7, + 0xa01fbac9, + 0xe01cc87e, + 0xbcc7d1f6, + 0xcf0111c3, + 0xa1e8aac7, + 0x1a908749, + 0xd44fbd9a, + 0xd0dadecb, + 0xd50ada38, + 0x0339c32a, + 0xc6913667, + 0x8df9317c, + 0xe0b12b4f, + 0xf79e59b7, + 0x43f5bb3a, + 0xf2d519ff, + 0x27d9459c, + 0xbf97222c, + 0x15e6fc2a, + 0x0f91fc71, + 0x9b941525, + 0xfae59361, + 0xceb69ceb, + 0xc2a86459, + 0x12baa8d1, + 0xb6c1075e, + 0xe3056a0c, + 0x10d25065, + 0xcb03a442, + 0xe0ec6e0e, + 0x1698db3b, + 0x4c98a0be, + 0x3278e964, + 0x9f1f9532, + 0xe0d392df, + 0xd3a0342b, + 0x8971f21e, + 0x1b0a7441, + 0x4ba3348c, + 0xc5be7120, + 0xc37632d8, + 0xdf359f8d, + 0x9b992f2e, + 0xe60b6f47, + 0x0fe3f11d, + 0xe54cda54, + 0x1edad891, + 0xce6279cf, + 0xcd3e7e6f, + 0x1618b166, + 0xfd2c1d05, + 0x848fd2c5, + 0xf6fb2299, + 0xf523f357, + 0xa6327623, + 0x93a83531, + 0x56cccd02, + 0xacf08162, + 0x5a75ebb5, + 0x6e163697, + 0x88d273cc, + 0xde966292, + 0x81b949d0, + 0x4c50901b, + 0x71c65614, + 0xe6c6c7bd, + 0x327a140a, + 0x45e1d006, + 0xc3f27b9a, + 0xc9aa53fd, + 0x62a80f00, + 0xbb25bfe2, + 0x35bdd2f6, + 0x71126905, + 0xb2040222, + 0xb6cbcf7c, + 0xcd769c2b, + 0x53113ec0, + 0x1640e3d3, + 0x38abbd60, + 0x2547adf0, + 0xba38209c, + 0xf746ce76, + 0x77afa1c5, + 0x20756060, + 0x85cbfe4e, + 0x8ae88dd8, + 0x7aaaf9b0, + 0x4cf9aa7e, + 0x1948c25c, + 0x02fb8a8c, + 0x01c36ae4, + 0xd6ebe1f9, + 0x90d4f869, + 0xa65cdea0, + 0x3f09252d, + 0xc208e69f, + 0xb74e6132, + 0xce77e25b, + 0x578fdfe3, + 0x3ac372e6, + ]), + ]; + Uint32List P = Uint32List.fromList([ + 0x243f6a88, + 0x85a308d3, + 0x13198a2e, + 0x03707344, + 0xa4093822, + 0x299f31d0, + 0x082efa98, + 0xec4e6c89, + 0x452821e6, + 0x38d01377, + 0xbe5466cf, + 0x34e90c6c, + 0xc0ac29b7, + 0xc97c50dd, + 0x3f84d5b5, + 0xb5470917, + 0x9216d5d9, + 0x8979fb1b, + ]); + + void encipher(Uint32List x, [Uint8List? x8]) { + x8 ??= Uint8List.sublistView(x); + x[0] ^= P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(S, x8, 0) ^ P[i]; + x[0] ^= F(S, x8, 4) ^ P[i + 1]; + } + var t = x[0]; + x[0] = x[1] ^ P[17]; + x[1] = t; + } + + void decipher(Uint32List x) { + // var x8 = x.buffer.asUint8List(); + // if (x.offsetInBytes != 0) x8 = x8.sublist(x.offsetInBytes); + final x8 = Uint8List.sublistView(x); + x[0] ^= P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(S, x8, 0) ^ P[i]; + x[0] ^= F(S, x8, 4) ^ P[i - 1]; + } + var t = x[0]; + x[0] = x[1] ^ P[0]; + x[1] = t; + } + + void expand0state(Uint8List key, int keybytes) { + var d = Uint32List(2); + var d8 = d.buffer.asUint8List(); + + BLF_J = 0; + for (var i = 0; i < 18; i++) { + P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; + + for (var i = 0; i < 18; i += 2) { + encipher(d, d8); + P[i] = d[0]; + P[i + 1] = d[1]; + } + + for (var i = 0; i < 4; i++) { + for (var k = 0; k < 256; k += 2) { + encipher(d, d8); + S[i][k] = d[0]; + S[i][k + 1] = d[1]; + } + } + } + + void expandstate(Uint8List data, int databytes, Uint8List key, int keybytes) { + var d = Uint32List(2); + + BLF_J = 0; + for (var i = 0; i < 18; i++) { + P[i] ^= stream2word(key, keybytes); + } + + BLF_J = 0; + for (var i = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + encipher(d); + P[i] = d[0]; + P[i + 1] = d[1]; + } + + for (var i = 0; i < 4; i++) { + for (var k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + encipher(d); + S[i][k] = d[0]; + S[i][k + 1] = d[1]; + } + } + BLF_J = 0; + } + + void enc(Uint32List data, int blocks) { + for (var i = 0; i < blocks; i++) { + encipher(Uint32List.sublistView(data, i * 2)); + } + } + + void dec(Uint32List data, int blocks) { + for (var i = 0; i < blocks; i++) { + encipher(Uint32List.sublistView(data, i * 2)); + } + } +} + +int F(List S, x8, i) { + return (((S[0][x8[i + 3]] + S[1][x8[i + 2]]) ^ S[2][x8[i + 1]]) + + S[3][x8[i]]); +} + +int stream2word(Uint8List data, int databytes) { + var temp = 0; + for (var i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +} + +const BCRYPT_BLOCKS = 8; +const BCRYPT_HASHSIZE = 32; + +void bcrypt_hash(Uint8List sha2pass, Uint8List sha2salt, Uint8List out) { + final state = Blowfish(); + final cdata = Uint32List(BCRYPT_BLOCKS); + final ciphertext = + Uint8List.fromList('OxychromaticBlowfishSwatDynamite'.codeUnits); + + state.expandstate(sha2salt, 64, sha2pass, 64); + for (var i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } + + for (var i = 0; i < BCRYPT_BLOCKS; i++) { + cdata[i] = stream2word(ciphertext, ciphertext.lengthInBytes); + } + + for (var i = 0; i < 64; i++) { + state.enc(cdata, cdata.lengthInBytes ~/ 8); + } + + for (var i = 0; i < BCRYPT_BLOCKS; i++) { + out[4 * i + 3] = cdata[i] >>> 24; + out[4 * i + 2] = cdata[i] >>> 16; + out[4 * i + 1] = cdata[i] >>> 8; + out[4 * i + 0] = cdata[i]; + } +} + +int bcrypt_pbkdf( + Uint8List pass, + int passlen, + Uint8List salt, + int saltlen, + Uint8List key, + int keylen, + int rounds, +) { + final sha2pass = Uint8List(64); + final sha2salt = Uint8List(64); + final out = Uint8List(BCRYPT_HASHSIZE); + final tmpout = Uint8List(BCRYPT_HASHSIZE); + final countsalt = Uint8List(saltlen + 4); + final origkeylen = keylen; + + if (rounds < 1) { + return -1; + } + + if (passlen == 0 || + saltlen == 0 || + keylen == 0 || + keylen > (out.lengthInBytes * out.lengthInBytes) || + saltlen > (1 << 20)) { + return -1; + } + + var stride = ((keylen + out.lengthInBytes - 1) / out.lengthInBytes).floor(); + var amt = ((keylen + stride - 1) / stride).floor(); + + // console.log('stride', stride); + // console.log('amt', amt); + + for (var i = 0; i < saltlen; i++) { + countsalt[i] = salt[i]; + } + + crypto_hash_sha512(sha2pass, pass, passlen); + + for (var count = 1; keylen > 0; count++) { + countsalt[saltlen + 0] = count >>> 24; + countsalt[saltlen + 1] = count >>> 16; + countsalt[saltlen + 2] = count >>> 8; + countsalt[saltlen + 3] = count; + + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + + bcrypt_hash(sha2pass, sha2salt, tmpout); + + for (var i = 0; i < tmpout.lengthInBytes; i++) { + out[i] = tmpout[i]; + } + + for (var i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.lengthInBytes); + bcrypt_hash(sha2pass, sha2salt, tmpout); + + for (var j = 0; j < out.lengthInBytes; j++) { + out[j] ^= tmpout[j]; + } + } + + amt = math.min(amt, keylen); + + var i = 0; + for (i = 0; i < amt; i++) { + final dest = i * stride + (count - 1); + if (dest >= origkeylen) break; + key[dest] = out[i]; + } + keylen -= i; + } + + return 0; +} + +// module.exports = { +// BLOCKS: BCRYPT_BLOCKS, +// HASHSIZE: BCRYPT_HASHSIZE, +// hash: bcrypt_hash, +// pbkdf: bcrypt_pbkdf +// }; diff --git a/third_party/dartssh2/lib/src/utils/bigint.dart b/third_party/dartssh2/lib/src/utils/bigint.dart new file mode 100644 index 0000000..712f020 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/bigint.dart @@ -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 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; +} diff --git a/third_party/dartssh2/lib/src/utils/chunk_buffer.dart b/third_party/dartssh2/lib/src/utils/chunk_buffer.dart new file mode 100644 index 0000000..4da28ca --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/chunk_buffer.dart @@ -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)'; + } +} diff --git a/third_party/dartssh2/lib/src/utils/cipher_ext.dart b/third_party/dartssh2/lib/src/utils/cipher_ext.dart new file mode 100644 index 0000000..2a3fb30 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/cipher_ext.dart @@ -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; + } +} diff --git a/third_party/dartssh2/lib/src/utils/int.dart b/third_party/dartssh2/lib/src/utils/int.dart new file mode 100644 index 0000000..c4b741f --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/int.dart @@ -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]}'); + } +} diff --git a/third_party/dartssh2/lib/src/utils/list.dart b/third_party/dartssh2/lib/src/utils/list.dart new file mode 100644 index 0000000..2626b7b --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/list.dart @@ -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 on List { + bool equals(List other) { + if (other.length != length) return false; + for (int i = 0; i < length; i++) { + if (this[i] != other[i]) return false; + } + return true; + } +} diff --git a/third_party/dartssh2/lib/src/utils/stream.dart b/third_party/dartssh2/lib/src/utils/stream.dart new file mode 100644 index 0000000..cf0b4ae --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/stream.dart @@ -0,0 +1,150 @@ +import 'dart:async'; +import 'dart:math'; + +import 'dart:typed_data'; + +import 'package:meta/meta.dart'; + +class MaxChunkSize extends StreamTransformerBase { + MaxChunkSize(this.size); + + final int size; + + @override + Stream bind(Stream 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 { + MinChunkSize(this.size); + + final int size; + + var _yielded = false; + + @override + Stream bind(Stream 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 { + /// Creates a new [StreamConsumer] that reads from [stream]. + /// + /// The underlying [stream] is paused during calls to [read]. + StreamConsumerBase(Stream stream) : _stream = StreamIterator(stream); + + /// The underlying stream being read from. + final StreamIterator _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 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 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 { + 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); + } +} diff --git a/third_party/dartssh2/lib/src/utils/string.dart b/third_party/dartssh2/lib/src/utils/string.dart new file mode 100644 index 0000000..20dad65 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/string.dart @@ -0,0 +1,3 @@ +extension StirngX on String { + int get octal => int.parse(this, radix: 8); +} diff --git a/third_party/dartssh2/lib/src/utils/utf8.dart b/third_party/dartssh2/lib/src/utils/utf8.dart new file mode 100644 index 0000000..85393e6 --- /dev/null +++ b/third_party/dartssh2/lib/src/utils/utf8.dart @@ -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); +} diff --git a/third_party/dartssh2/media/showcase-1-serverbox.1.jpg b/third_party/dartssh2/media/showcase-1-serverbox.1.jpg new file mode 100644 index 0000000..f76a9f0 Binary files /dev/null and b/third_party/dartssh2/media/showcase-1-serverbox.1.jpg differ diff --git a/third_party/dartssh2/media/showcase-1-serverbox.2.png b/third_party/dartssh2/media/showcase-1-serverbox.2.png new file mode 100644 index 0000000..dfe4c45 Binary files /dev/null and b/third_party/dartssh2/media/showcase-1-serverbox.2.png differ diff --git a/third_party/dartssh2/pubspec.yaml b/third_party/dartssh2/pubspec.yaml new file mode 100644 index 0000000..077fc0b --- /dev/null +++ b/third_party/dartssh2/pubspec.yaml @@ -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 diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa new file mode 100644 index 0000000..c61fa08 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa @@ -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----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa.pub new file mode 100644 index 0000000..184c8a3 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/id_ecdsa.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBIDzNQ9fRA/YZ3bSGba7hcDVnBMBV7Mf+j3Hz9FSOL0HPMQvmT5qk/AodXqJd7tyhGW6fxl5ioHRWOqh2qAznI= jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key new file mode 100644 index 0000000..5b6b2fa --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key @@ -0,0 +1,9 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS +1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQR6CRv2GHU23gai7jw8YQ5IwOj09tOS +MoG6b6hRQnC9BseB427xHD2y4xYUZeOoeD+k5vAgWzG5XSis/U1mEWf0AAAAuOLU2yri1N +sqAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHoJG/YYdTbeBqLu +PDxhDkjA6PT205IygbpvqFFCcL0Gx4HjbvEcPbLjFhRl46h4P6Tm8CBbMbldKKz9TWYRZ/ +QAAAAhAMOqFkndoggSsAYprv9Ur+sHi4LVhJ0VjTp4CHi9+nriAAAAGWpmb3V0dHNAVVNB +SkZPVVRUU00ubG9jYWwBAgMEBQY= +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key.pub new file mode 100644 index 0000000..b327d77 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp256/ssh_host_ecdsa_key.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHoJG/YYdTbeBqLuPDxhDkjA6PT205IygbpvqFFCcL0Gx4HjbvEcPbLjFhRl46h4P6Tm8CBbMbldKKz9TWYRZ/Q= jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa new file mode 100644 index 0000000..62f2ca0 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa @@ -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----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa.pub new file mode 100644 index 0000000..93a7e8d --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/id_ecdsa.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBFKfFTCIzLubGU9qnMlItiI43AMafP5q4XDWbkVDz7kg1iuFRkXdY8VGSg5sUUetExbJ9QIZ3ECCdt+1IZZFY8WWLUt/rTKVBMj2LR19RpQiE/Z+UxHaANa8OuHkLOfv8A== jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key new file mode 100644 index 0000000..e0b98fd --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key @@ -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----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key.pub new file mode 100644 index 0000000..9a6d67d --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp384/ssh_host_ecdsa_key.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBPQXq8J3HkWEQ/j9h2XUA7BjAmCkZ66IMvFup7XW0C1q4gUcw0QY9Y6vw3Rv7WIBFCEgc776JjwgGNAIa9rcVPeN/Xgj5VLVtbWE1ejsWmr7jO5mNbMhA5/+BD7QCtjvJg== jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa new file mode 100644 index 0000000..2192540 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa @@ -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----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa.pub new file mode 100644 index 0000000..f4162d4 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/id_ecdsa.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACzzUbyb+q8Rwi/2+1T7kwuacfs5J6OddP5JA/WtU3TsLP9DTiCTYZoJ/3EMJGhL7rWx3l5vFFQE40lmxk+hXHGgwDzURw7eDQfZiZgKBDgQBmAS4WERfJu38zKBmdeV4Ouy/5sVIGjT1vkA1Rexnj98tUuT0Ijg3eZOK+SbI8rp/QXxw== jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key new file mode 100644 index 0000000..24d7ff3 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key @@ -0,0 +1,12 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAArAAAABNlY2RzYS +1zaGEyLW5pc3RwNTIxAAAACG5pc3RwNTIxAAAAhQQBO/iOTkpxtAp+EHd/zEfEhou8B2nR +SqAe37MX/LoJc4KsBIkUwKGPF0g3uMpI3KREsV7U/MeI0dxTuxRwCuY/h9cBv0y02GDkxo +V0JVIH2xTuxvHyMZRa59NWTKTHpSCMquAGomjG6ohZWQxmWTdVRo73Qqm5FiQ9juGF/C/X +8G/F9OcAAAEYXiXViV4l1YkAAAATZWNkc2Etc2hhMi1uaXN0cDUyMQAAAAhuaXN0cDUyMQ +AAAIUEATv4jk5KcbQKfhB3f8xHxIaLvAdp0UqgHt+zF/y6CXOCrASJFMChjxdIN7jKSNyk +RLFe1PzHiNHcU7sUcArmP4fXAb9MtNhg5MaFdCVSB9sU7sbx8jGUWufTVkykx6UgjKrgBq +JoxuqIWVkMZlk3VUaO90KpuRYkPY7hhfwv1/BvxfTnAAAAQgHLFn0sOZzvMDmSZQYK5LaB +gK5dDqeiBhygJLciE/KPYFlrHAYPJpzduApUulnIbK6fPMbM4snm6eTwAtFDTDcxQwAAAB +lqZm91dHRzQFVTQUpGT1VUVFNNLmxvY2FsAQ== +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key.pub b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key.pub new file mode 100644 index 0000000..b5b33af --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ecdsa-sha2-nistp521/ssh_host_ecdsa_key.pub @@ -0,0 +1 @@ +ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAE7+I5OSnG0Cn4Qd3/MR8SGi7wHadFKoB7fsxf8uglzgqwEiRTAoY8XSDe4ykjcpESxXtT8x4jR3FO7FHAK5j+H1wG/TLTYYOTGhXQlUgfbFO7G8fIxlFrn01ZMpMelIIyq4AaiaMbqiFlZDGZZN1VGjvdCqbkWJD2O4YX8L9fwb8X05w== jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519 b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519 new file mode 100644 index 0000000..71494de --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519 @@ -0,0 +1,8 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABC0l9Iobg +dIkpFRXIVcSMo9AAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIDl6gJA/mTwGajQU +GysVNxbg5DLxNkxNMr1N6nMqmILLAAAAoAheLDCmikMrd30h6Z3ug4h7WsK8TjBYToUkhO +1fu5qRd6pgCCeQt0C5eeJMkCSNTP+HZyWT9Vc67VCvzaECjFfXYJUsRYdknAXEO4oFc9fg +v8qGMQTFoIajXQk8Gk9QLqGQ0nupn4fZ3BhHhMoDIx7DWLhlvHddSJzgkORIt4bV8ntzh8 +AK9jJFzpo0q4FnYkalW4fo/nosGUM/bq5LR2M= +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519.pub b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519.pub new file mode 100644 index 0000000..0fe95a6 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/id_ed25519.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDl6gJA/mTwGajQUGysVNxbg5DLxNkxNMr1N6nMqmILL xuty@TydeMacBook-Pro.local diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/passphrase b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/passphrase new file mode 100644 index 0000000..4632e06 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519-passphrase/passphrase @@ -0,0 +1 @@ +123456 \ No newline at end of file diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519 b/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519 new file mode 100644 index 0000000..ec4e50b --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519 @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpAAAAKBQ6gOSUOoD +kgAAAAtzc2gtZWQyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpA +AAAEAP8fq0hjlR3jhL7pg+26PSaMiC1V/RrinVbo/4eBMRNFmeedhmMVDtm3SAzInZhiYM +g1O5wsVZjzX9a6/Zo4ikAAAAGWpmb3V0dHNAVVNBSkZPVVRUU00ubG9jYWwBAgME +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519.pub b/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519.pub new file mode 100644 index 0000000..3013d22 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519/id_ed25519.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFmeedhmMVDtm3SAzInZhiYMg1O5wsVZjzX9a6/Zo4ik jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key b/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key new file mode 100644 index 0000000..ca693bd --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACDQJ65EwdaizNomzJhQcqzhsAhA+Td3X//b2D07tkuH5QAAAKAk6jnzJOo5 +8wAAAAtzc2gtZWQyNTUxOQAAACDQJ65EwdaizNomzJhQcqzhsAhA+Td3X//b2D07tkuH5Q +AAAECPVGo7eCpp7D0hyrw+wKTI2LGyPud3JhnexFpn+vhuhdAnrkTB1qLM2ibMmFByrOGw +CED5N3df/9vYPTu2S4flAAAAGWpmb3V0dHNAVVNBSkZPVVRUU00ubG9jYWwBAgME +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key.pub b/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key.pub new file mode 100644 index 0000000..9f4131c --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-ed25519/ssh_host_ed25519_key.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINAnrkTB1qLM2ibMmFByrOGwCED5N3df/9vYPTu2S4fl jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa new file mode 100644 index 0000000..6db41b0 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,FB1AD0F158BF11B3E14A5331C6D14A6D + +ZhN5hG0+sEFsrPRD1bZnFIMmHgKvpfWD/OObv3lcPLygQXOETNIRMiiizH8GdAX8 +lc6nEZuBMw14A6Ef6Hm2HyTxd9eR6JS4vG9EBTOH4lyTLboO0EqUS3KfOw1RVLs4 +aNG7My+KQbIMUevL2ZZwZNojQIgRg8Nu3zTEY/O1zn/ugdJPPvwZmHmbKgqvAcsP +rjvtcPn8CwXNoAsWxk+vhpNE6ths/MjFRdYnUDPKfvONepu9DpP8II+B2JQBP44u +VyESk9JyoAHp2nHfgjCEpc7Bv5D1fgQlI8mrVj2gtw2fr+hlNpezH/YutEdi/syK +Lzd2xyMUsKDtCqSIjT7hILMGoKEeIOv/y2qcJYILLfDGHmrFEyOwLNE2ISu9K4Qk +koZky7keqhnM4piszKjtWoSwTJwLEF/XiwfbJTxDdxFSWDCb4dOIkql4w6gs59Cg +4NucKenMVzjKensvIq5PaDXUZV88zP/m8i4Vn2dmV1J9WdHETawL5x6ny7uAKZCS +JDp7GyPSQU/lvjS78fkVq3wHZA0eSE+oRWt3bcIjrX5ZjHskGUXDjxSuSPXlKiXn +HaQNJ5xdGp6noH30RILTfur2UjgWGXFw+6AYkzcahGMab35pk1+D4uUETyBI0KtX +atKO7/540RAi8ewQ1oo0oTWQRdqaO0KAgzqde1sY+wvA+o5Gd2tvjgfAARSL3sT6 +rgHVNY3LKOJb8ulh5VPdV61bNblzHsNU8qMTlxHotFUZw1vZ7ScVNn0xsMSWGKq2 +F2sROVgGMhmKPlG5SfewlHLop9W9DyMQPhmvNKM3KFB3aYoulBbYMpAk2imBph+6 +Odan7KqxIVoAnironvZEkGdez6Uh6LGDXSh8DQDJcfcqPWgc9XCq2lBkzsFDjRoy +Xrn2htsv0BsaIzyxSH15H60Aawwe7hnhnO1wFJCbV7cL6l6dczZyH4xszHZp53Jq +HLJ7LXjpChw5ZgbG6ISujVIBo+gvpq8LV1MmpX3/B1BEkoYGfXlNQ9R03vz8LFnb +BufSv1lw51KfnaUwms1ma9dhwMePMoiG7CGU7v2rBFzP6jbFyzA/C/Tq66aFbUtx +6ozuVxPhJ7Of2XC0a2L2YXIRI/pvCCzIzOGFlPnLaTJC/+toZPAlET6aicIHpsPO +ihA8RdTLsO/HNLX6q61z5Z22/HaxAMtcGLez5jkAKqSQGlIy+phHSm3uDY7yWX99 +OPkPFCbQCgcjXR8iZmOCNf1ThIV/rfLPmuOiBUsj40DOnqdz/w9J21bRC4h9CEDA +dDCRnWEvMJgJzjAMQHti//OW0Elh28p9gbGgsmLQeSAiGiMiseO3SNdY0Y/KKqPu +RETahfSCImfu+upykJAqWUABxUFWuDWEj4H2oU95cV0fpsleFatYrqAycb6dRGGV +w0vDDTBLhD/NVuIaqhzh3D8z25vM5ArbTUOXL07DnRFMtjgJwl/ZVlAMvPUnXocO +yQNiFax2/YOxWZ7KfgDT2Zkh4vipZAaOGkksVEfY6U49M6twUxvbQsq5gp26W819 +3P4yyIQE669imnHlnvLgIIR8zMdlE0XJfW+AxNcGBRqoRUnJ6wNTpL1JO059ZIhM +-----END RSA PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa.pub b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa.pub new file mode 100644 index 0000000..38b7bb5 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/id_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3w4x/pBiKFJuuuluT3rg8oKS/tWQvPoLk4bVIe0cEgZqxJ//XTVURCE+UqiIRC4sEwu0KEz30FNjVrznc/e+7oN8F83lyCAo1ARoZ0JZPxaApa7wIkSQNCwynYOX/LuPxmUfhnQZWJkh8AtN/eR6jeLWZQtgLt133qLtBtoBBqLulUvJvEVFTuQaHprOJkMMPPypQgpkQUhlPEPx1xdFREwUJrlIBhVMXTLEO0vIcq3eu06ISsfxEx2PNe/O93Y2a5vsp5aQKJ5Nirapr9JamN42Qp2FiJm9ZtZAgSYoxJJujB0/C6w3ZyA8dwGKIaF6INa+BwbyF7IDSj/GETGWT jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/passphrase b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/passphrase new file mode 100644 index 0000000..82b88c1 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa-passphrase/passphrase @@ -0,0 +1 @@ +CustedNG \ No newline at end of file diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa new file mode 100644 index 0000000..3254fbd --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAt8OMf6QYihSbrrpbk964PKCkv7VkLz6C5OG1SHtHBIGasSf/ +101VEQhPlKoiEQuLBMLtChM99BTY1a853P3vu6DfBfN5cggKNQEaGdCWT8WgKWu8 +CJEkDQsMp2Dl/y7j8ZlH4Z0GViZIfALTf3keo3i1mULYC7dd96i7QbaAQai7pVLy +bxFRU7kGh6aziZDDDz8qUIKZEFIZTxD8dcXRURMFCa5SAYVTF0yxDtLyHKt3rtOi +ErH8RMdjzXvzvd2Nmub7KeWkCieTYq2qa/SWpjeNkKdhYiZvWbWQIEmKMSSbowdP +wusN2cgPHcBiiGheiDWvgcG8heyA0o/xhExlkwIDAQABAoIBAAUzjMOEIomuAaYV +ckgiMrbMmT0v5jEMJOpTlS0DCESRYo6HIk+2yaScxpvfoO04lWvCFLGHT+abvHN3 +7TxbF7EI4acqeBKJNbjAWjvG0qpZXqoteXoImaug12/ZZ0ksy5joDMfPCQHhPYX9 +En12MS7RWNqIsNLMEuXSqdI3VzQEhVL9TttHrcOyFoQYTd4gmXPVgMhO8/RgG2ha +Kl30/sw+CeATOlnMquFrROf4rvbgXVyjHfsa8kPvfFgAZGudHhbHccplhIDygzjV +QoUbst7laKkuGj792fvAgOCMmsE3TiuKzN/1Y3b0B4sGr82ABLg9P15SlT7h9sgL +jG97ONECgYEA6dhHfBADBieIeTifrLq8iTpAhKLLI9JVv6BDsI7CmfjePvDEtkCa +Bvtq/MQnInsfJKTObUHrlluGXT+hTCJB1X7dGf8DAEffJT2vJ6+QJlpAWd1vmatk +1wiypS9H1CwFIFp+GLq07uU6uFaDezixxYXYmbR0TA5t6+JvKXq95SsCgYEAySyY +Yxt/UF16Wwyr8rzS52IK2DbuNbbetYfxfh6UJ9rregpoYGhRMH7y6Pn+n4ckyZXk +RpZopCr6mrRk4L3CZtavrvSbTf5QIpucwRBE+fGr6YKI3lVy73PcDSjVF+P+Tpc0 +AhI/3GO3XLRv/Tp8MOroP61KvSItnnWIohTrnTkCgYBOeVcb6h+prBCfZYIoLA5j +GtpV6G+1WLuP8A9nK7FgjGTAyHmrE6jc2PiBVK4xYxIDcQ8ZGTsfHR3NIzJU41Ym +eElolOyD5pqa28Vw0vjT9guMXMQ71Imlo/SXfHNlX1RlFBkm4Vkgpmp7PAUpj9AQ +kicrBaTVdS4sL7PQPrGFOwKBgQCMmep3egRlOrAFarnSkT4mEVPbAalDSWgmH7kc +mGqb4FmrlhKVLtNvvYowYmkfPejsKyK8YusHsjIsZeALYxS3o1xuPu88d32ycmgA +V0qeFdY9Acp++eG2kZc+a0djxyk57FuhBvgzJE5HMKUEqxeZaNShjJAr1/NiSGsS +POTfoQKBgGnsKDLpfKrem3CjISnPhTExkLV6oipcLdL9vhimUOWeoXPp5ckrkkdC +qfLaJTu1VpiMYCjmGVvlTDZzVhryqpAnYBdVOrZsOOZi3+Z5pR7JlWZd4PCpWb7Q +Ldc5E6XkJW/RmMjKAzZsadNAIfyLwqI9kmaEGtkKSJpsWdqamjvm +-----END RSA PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.openssh b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.openssh new file mode 100644 index 0000000..1e50f70 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.openssh @@ -0,0 +1,27 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn +NhAAAAAwEAAQAAAQEAt8OMf6QYihSbrrpbk964PKCkv7VkLz6C5OG1SHtHBIGasSf/101V +EQhPlKoiEQuLBMLtChM99BTY1a853P3vu6DfBfN5cggKNQEaGdCWT8WgKWu8CJEkDQsMp2 +Dl/y7j8ZlH4Z0GViZIfALTf3keo3i1mULYC7dd96i7QbaAQai7pVLybxFRU7kGh6aziZDD +Dz8qUIKZEFIZTxD8dcXRURMFCa5SAYVTF0yxDtLyHKt3rtOiErH8RMdjzXvzvd2Nmub7Ke +WkCieTYq2qa/SWpjeNkKdhYiZvWbWQIEmKMSSbowdPwusN2cgPHcBiiGheiDWvgcG8heyA +0o/xhExlkwAAA9CdjgBfnY4AXwAAAAdzc2gtcnNhAAABAQC3w4x/pBiKFJuuuluT3rg8oK +S/tWQvPoLk4bVIe0cEgZqxJ//XTVURCE+UqiIRC4sEwu0KEz30FNjVrznc/e+7oN8F83ly +CAo1ARoZ0JZPxaApa7wIkSQNCwynYOX/LuPxmUfhnQZWJkh8AtN/eR6jeLWZQtgLt133qL +tBtoBBqLulUvJvEVFTuQaHprOJkMMPPypQgpkQUhlPEPx1xdFREwUJrlIBhVMXTLEO0vIc +q3eu06ISsfxEx2PNe/O93Y2a5vsp5aQKJ5Nirapr9JamN42Qp2FiJm9ZtZAgSYoxJJujB0 +/C6w3ZyA8dwGKIaF6INa+BwbyF7IDSj/GETGWTAAAAAwEAAQAAAQAFM4zDhCKJrgGmFXJI +IjK2zJk9L+YxDCTqU5UtAwhEkWKOhyJPtsmknMab36DtOJVrwhSxh0/mm7xzd+08WxexCO +GnKngSiTW4wFo7xtKqWV6qLXl6CJmroNdv2WdJLMuY6AzHzwkB4T2F/RJ9djEu0VjaiLDS +zBLl0qnSN1c0BIVS/U7bR63DshaEGE3eIJlz1YDITvP0YBtoWipd9P7MPgngEzpZzKrha0 +Tn+K724F1cox37GvJD73xYAGRrnR4Wx3HKZYSA8oM41UKFG7Le5WipLho+/dn7wIDgjJrB +N04riszf9WN29AeLBq/NgAS4PT9eUpU+4fbIC4xvezjRAAAAgGnsKDLpfKrem3CjISnPhT +ExkLV6oipcLdL9vhimUOWeoXPp5ckrkkdCqfLaJTu1VpiMYCjmGVvlTDZzVhryqpAnYBdV +OrZsOOZi3+Z5pR7JlWZd4PCpWb7QLdc5E6XkJW/RmMjKAzZsadNAIfyLwqI9kmaEGtkKSJ +psWdqamjvmAAAAgQDp2Ed8EAMGJ4h5OJ+suryJOkCEossj0lW/oEOwjsKZ+N4+8MS2QJoG ++2r8xCciex8kpM5tQeuWW4ZdP6FMIkHVft0Z/wMAR98lPa8nr5AmWkBZ3W+Zq2TXCLKlL0 +fULAUgWn4YurTu5Tq4VoN7OLHFhdiZtHRMDm3r4m8per3lKwAAAIEAySyYYxt/UF16Wwyr +8rzS52IK2DbuNbbetYfxfh6UJ9rregpoYGhRMH7y6Pn+n4ckyZXkRpZopCr6mrRk4L3CZt +avrvSbTf5QIpucwRBE+fGr6YKI3lVy73PcDSjVF+P+Tpc0AhI/3GO3XLRv/Tp8MOroP61K +vSItnnWIohTrnTkAAAAZamZvdXR0c0BVU0FKRk9VVFRTTS5sb2NhbAEC +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.pub b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.pub new file mode 100644 index 0000000..38b7bb5 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa/id_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3w4x/pBiKFJuuuluT3rg8oKS/tWQvPoLk4bVIe0cEgZqxJ//XTVURCE+UqiIRC4sEwu0KEz30FNjVrznc/e+7oN8F83lyCAo1ARoZ0JZPxaApa7wIkSQNCwynYOX/LuPxmUfhnQZWJkh8AtN/eR6jeLWZQtgLt133qLtBtoBBqLulUvJvEVFTuQaHprOJkMMPPypQgpkQUhlPEPx1xdFREwUJrlIBhVMXTLEO0vIcq3eu06ISsfxEx2PNe/O93Y2a5vsp5aQKJ5Nirapr9JamN42Qp2FiJm9ZtZAgSYoxJJujB0/C6w3ZyA8dwGKIaF6INa+BwbyF7IDSj/GETGWT jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key b/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key new file mode 100644 index 0000000..08cb4cd --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key @@ -0,0 +1,27 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn +NhAAAAAwEAAQAAAQEA8438q4ZuPdkyk/eC1A4Zx/9WjFX7CXqHxTqNzK3j2ozhZN901j6s +knwThU+wuqXT6cqPStspvIiARcK4CsecSnvxXEEeHjzjG4hYRoDSiEczcrUlgGUWZED64E +nhZupmSdezJP6v+69e4BnL5zKd9BXIU5YD6w/b4CV9x9GxduY3VCeleAzzT5+yaI+6wtnx +b0xt2wzPL6DsRALL3UdttVTexDBA205nN8xX2Uf1LSGfd41VUuaWLssZT5NCkVeNoqPQWc +IvQEWOSjWNzvoLsiEI+UmREtBJP4E9pQvFrwce/rzke9Tr5fbRJV7C7DX7acU6kCnowRTf +KCanBSubuQAAA9C6EgSZuhIEmQAAAAdzc2gtcnNhAAABAQDzjfyrhm492TKT94LUDhnH/1 +aMVfsJeofFOo3MrePajOFk33TWPqySfBOFT7C6pdPpyo9K2ym8iIBFwrgKx5xKe/FcQR4e +POMbiFhGgNKIRzNytSWAZRZkQPrgSeFm6mZJ17Mk/q/7r17gGcvnMp30FchTlgPrD9vgJX +3H0bF25jdUJ6V4DPNPn7Joj7rC2fFvTG3bDM8voOxEAsvdR221VN7EMEDbTmc3zFfZR/Ut +IZ93jVVS5pYuyxlPk0KRV42io9BZwi9ARY5KNY3O+guyIQj5SZES0Ek/gT2lC8WvBx7+vO +R71Ovl9tElXsLsNftpxTqQKejBFN8oJqcFK5u5AAAAAwEAAQAAAQEA25xOFwQSZ6ZvWsi1 +qSxFxvbQPZ5RzAw2XHsd3U92w1yA6IotOfotdbB3kZ93xfU9DfReHKteCOg0cbLQbLfsj6 +UOz5bP54gTaIIaxwflzogVNfttI0cDV8bX8GHt4vS84xyiJluYp6NMM1pPZ9tWXf8+MVB1 +nAEizAxCTGkiUggl0FXYIednoiHe7vuGmRhDptMZRBBWr6HcKkV+RRK2qa4Tyw6yvep0iC +kIZW4GalDMmk32QU6rg2x+eiV3HqICw3MNPXmkeuldaJ7ZQpmHFSVCbOKfWiSZxrPjUBtp +SK0VuRh/Dimg0tOpjjjuLxHO1cp+Horjdw0BnfkcMs2eYQAAAIEAkiZm0IfSBl2nqVRri1 +6Ugs+3ybbg6YiYqmC7ExaWHISubq0DBzMVurV9l94X2RDAFcQYIRXNykAnrMqlk5z+6xz3 +qSM+mrzfBlebzhUXGTaHkKzPrp1wVlBJ+zEmg6Yt/O7qKEk8FSOr6YEeWCSnHMgnP7wc4/ +jCh9QrNduIhyoAAACBAPnEgU5iGlQC0uTDKUsa/cSLIjxYp0WAQ4BPi2ReP40HxdeO+h37 +L63Tmj6IA8gj6tPcsKceRGEMBfHyp5oXz1888hPy2b9Q71FE0KTw2mcsx7tkbLsXx1wn6K +14KpqyvCfDwA+jwNO2i5lxtrPKPWUGkObvtC8iyQ2Ep8EEYWUVAAAAgQD5octDyq8l1Jh3 +lwY48o8I+3WhwdiTy9U/ePpD9A/gNVlSQH114ldt3zPj1OG8AHmtvlJuxQ+qwpSgT9i4r1 +lNVKTd3o5kC5dkN8IBrykSFcDBSDcFJR3trPnp5IoR2bQy7Pu0VVDlMdWCA8oJxzs3HAXG +RnGKTbngeeMiJmtNFQAAABlqZm91dHRzQFVTQUpGT1VUVFNNLmxvY2Fs +-----END OPENSSH PRIVATE KEY----- diff --git a/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key.pub b/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key.pub new file mode 100644 index 0000000..ab89483 --- /dev/null +++ b/third_party/dartssh2/test/fixtures/ssh-rsa/ssh_host_rsa_key.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDzjfyrhm492TKT94LUDhnH/1aMVfsJeofFOo3MrePajOFk33TWPqySfBOFT7C6pdPpyo9K2ym8iIBFwrgKx5xKe/FcQR4ePOMbiFhGgNKIRzNytSWAZRZkQPrgSeFm6mZJ17Mk/q/7r17gGcvnMp30FchTlgPrD9vgJX3H0bF25jdUJ6V4DPNPn7Joj7rC2fFvTG3bDM8voOxEAsvdR221VN7EMEDbTmc3zFfZR/UtIZ93jVVS5pYuyxlPk0KRV42io9BZwi9ARY5KNY3O+guyIQj5SZES0Ek/gT2lC8WvBx7+vOR71Ovl9tElXsLsNftpxTqQKejBFN8oJqcFK5u5 jfoutts@USAJFOUTTSM.local diff --git a/third_party/dartssh2/test/src/algorithm/ssh_cipher_type_test.dart b/third_party/dartssh2/test/src/algorithm/ssh_cipher_type_test.dart new file mode 100644 index 0000000..15ae2fd --- /dev/null +++ b/third_party/dartssh2/test/src/algorithm/ssh_cipher_type_test.dart @@ -0,0 +1,121 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:dartssh2/src/ssh_algorithm.dart'; +import 'package:dartssh2/src/utils/cipher_ext.dart'; +import 'package:test/test.dart'; + +void main() { + testCipher(SSHCipherType.aes128cbc); + testCipher(SSHCipherType.aes192cbc); + testCipher(SSHCipherType.aes256cbc); + testCipher(SSHCipherType.aes128ctr); + testCipher(SSHCipherType.aes192ctr); + testCipher(SSHCipherType.aes256ctr); + group('SSHAlgorithm', () { + test('toString() returns correct format', () { + final algorithm = SSHKexType.x25519; + expect(algorithm.toString(), equals(SSHKexType.x25519.toString())); + }); + }); + + group('SSHAlgorithmList extension', () { + test('toNameList() returns list of names', () { + final algorithms = [SSHKexType.x25519, SSHKexType.nistp521]; + final names = algorithms.toNameList(); + expect(names, equals([SSHKexType.x25519.name, SSHKexType.nistp521.name])); + }); + + test('getByName() returns correct algorithm', () { + final algorithms = [SSHKexType.x25519, SSHKexType.nistp521]; + final algorithm = algorithms.getByName(SSHKexType.nistp521.name); + expect(algorithm, isNotNull); + expect(algorithm!.name, equals(SSHKexType.nistp521.name)); + }); + + test('getByName() returns null when not found', () { + final algorithms = [SSHKexType.x25519, SSHKexType.nistp521]; + final algorithm = algorithms.getByName('nonexistent'); + expect(algorithm, isNull); + }); + }); + + test('Default values are set correctly', () { + final algorithms = SSHAlgorithms(); + + expect( + algorithms.kex, + equals([ + SSHKexType.x25519, + SSHKexType.nistp521, + SSHKexType.nistp384, + SSHKexType.nistp256, + SSHKexType.dhGexSha256, + SSHKexType.dh14Sha256, + SSHKexType.dh14Sha1, + SSHKexType.dhGexSha1, + SSHKexType.dh1Sha1, + ])); + + expect( + algorithms.hostkey, + equals([ + SSHHostkeyType.ed25519, + SSHHostkeyType.rsaSha512, + SSHHostkeyType.rsaSha256, + SSHHostkeyType.rsaSha1, + SSHHostkeyType.ecdsa521, + SSHHostkeyType.ecdsa384, + SSHHostkeyType.ecdsa256, + ])); + + expect( + algorithms.cipher, + equals([ + SSHCipherType.aes128ctr, + SSHCipherType.aes128cbc, + SSHCipherType.aes256ctr, + SSHCipherType.aes256cbc, + ])); + + expect( + algorithms.mac, + equals([ + SSHMacType.hmacSha1, + SSHMacType.hmacSha256, + SSHMacType.hmacSha512, + SSHMacType.hmacMd5, + ])); + }); +} + +void testCipher(SSHCipherType type) { + test('$type encrypt/decrypt', () { + final key = Uint8List(type.keySize); + final iv = Uint8List(type.blockSize); + final encrypter = type.createCipher(key, iv, forEncryption: true); + final decrypter = type.createCipher(key, iv, forEncryption: false); + + final plainText = Uint8List(type.blockSize * 100); + for (var i = 0; i < plainText.length; i++) { + plainText[i] = i & 0xff; + } + + final cipherText = encrypter.processAll(plainText); + final decrypted = decrypter.processAll(cipherText); + + expect(decrypted, plainText); + }); + + // test('$type needs init after reset', () { + // final key = Uint8List(type.keySize); + // final iv = Uint8List(type.blockSize); + // final encrypter = type.createCipher(key, iv, forEncryption: true); + // encrypter.processAll(Uint8List(type.blockSize)); + // encrypter.reset(); + // expect( + // () => encrypter.processAll(Uint8List(type.blockSize)), + // throwsA(isA()), + // ); + // }); +} diff --git a/third_party/dartssh2/test/src/algorithm/ssh_hostkey_type_test.dart b/third_party/dartssh2/test/src/algorithm/ssh_hostkey_type_test.dart new file mode 100644 index 0000000..8de7382 --- /dev/null +++ b/third_party/dartssh2/test/src/algorithm/ssh_hostkey_type_test.dart @@ -0,0 +1,33 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHHostkeyType', () { + test('Static constants are defined correctly', () { + expect(SSHHostkeyType.rsaSha1.name, equals('ssh-rsa')); + expect(SSHHostkeyType.rsaSha256.name, equals('rsa-sha2-256')); + expect(SSHHostkeyType.rsaSha512.name, equals('rsa-sha2-512')); + expect(SSHHostkeyType.ecdsa256.name, equals('ecdsa-sha2-nistp256')); + expect(SSHHostkeyType.ecdsa384.name, equals('ecdsa-sha2-nistp384')); + expect(SSHHostkeyType.ecdsa521.name, equals('ecdsa-sha2-nistp521')); + expect(SSHHostkeyType.ed25519.name, equals('ssh-ed25519')); + }); + + test('toString() returns correct format', () { + expect( + SSHHostkeyType.rsaSha1.toString(), equals('SSHHostkeyType(ssh-rsa)')); + expect(SSHHostkeyType.rsaSha256.toString(), + equals('SSHHostkeyType(rsa-sha2-256)')); + expect(SSHHostkeyType.rsaSha512.toString(), + equals('SSHHostkeyType(rsa-sha2-512)')); + expect(SSHHostkeyType.ecdsa256.toString(), + equals('SSHHostkeyType(ecdsa-sha2-nistp256)')); + expect(SSHHostkeyType.ecdsa384.toString(), + equals('SSHHostkeyType(ecdsa-sha2-nistp384)')); + expect(SSHHostkeyType.ecdsa521.toString(), + equals('SSHHostkeyType(ecdsa-sha2-nistp521)')); + expect(SSHHostkeyType.ed25519.toString(), + equals('SSHHostkeyType(ssh-ed25519)')); + }); + }); +} diff --git a/third_party/dartssh2/test/src/algorithm/ssh_kex_type_test.dart b/third_party/dartssh2/test/src/algorithm/ssh_kex_type_test.dart new file mode 100644 index 0000000..64845db --- /dev/null +++ b/third_party/dartssh2/test/src/algorithm/ssh_kex_type_test.dart @@ -0,0 +1,68 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:pointycastle/export.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHKexType', () { + test('Static constants are defined correctly', () { + expect(SSHKexType.x25519.name, equals('curve25519-sha256@libssh.org')); + expect(SSHKexType.nistp256.name, equals('ecdh-sha2-nistp256')); + expect(SSHKexType.nistp384.name, equals('ecdh-sha2-nistp384')); + expect(SSHKexType.nistp521.name, equals('ecdh-sha2-nistp521')); + expect(SSHKexType.dhGexSha256.name, + equals('diffie-hellman-group-exchange-sha256')); + expect(SSHKexType.dhGexSha1.name, + equals('diffie-hellman-group-exchange-sha1')); + expect(SSHKexType.dh14Sha1.name, equals('diffie-hellman-group14-sha1')); + expect( + SSHKexType.dh14Sha256.name, equals('diffie-hellman-group14-sha256')); + expect(SSHKexType.dh1Sha1.name, equals('diffie-hellman-group1-sha1')); + }); + + test( + 'Static constants have correct digestFactory and isGroupExchange values', + () { + expect(SSHKexType.x25519.digestFactory, equals(digestSha256)); + expect(SSHKexType.nistp256.digestFactory, equals(digestSha256)); + expect(SSHKexType.nistp384.digestFactory, equals(digestSha384)); + expect(SSHKexType.nistp521.digestFactory, equals(digestSha512)); + expect(SSHKexType.dhGexSha256.digestFactory, equals(digestSha256)); + expect(SSHKexType.dhGexSha1.digestFactory, equals(digestSha1)); + expect(SSHKexType.dh14Sha1.digestFactory, equals(digestSha1)); + expect(SSHKexType.dh14Sha256.digestFactory, equals(digestSha256)); + expect(SSHKexType.dh1Sha1.digestFactory, equals(digestSha1)); + + expect(SSHKexType.dhGexSha256.isGroupExchange, isTrue); + expect(SSHKexType.dhGexSha1.isGroupExchange, isTrue); + expect(SSHKexType.dh14Sha1.isGroupExchange, isFalse); + expect(SSHKexType.dh14Sha256.isGroupExchange, isFalse); + expect(SSHKexType.dh1Sha1.isGroupExchange, isFalse); + }); + + test('createDigest() returns correct Digest instance', () { + final kexType = SSHKexType.x25519; + final digest = kexType.createDigest(); + expect(digest, isA()); + }); + + test( + 'createDigest() returns correct Digest instance for different algorithms', + () { + final kexTypeSha1 = SSHKexType.dhGexSha1; + final digestSha1 = kexTypeSha1.createDigest(); + expect(digestSha1, isA()); + + final kexTypeSha256 = SSHKexType.dhGexSha256; + final digestSha256 = kexTypeSha256.createDigest(); + expect(digestSha256, isA()); + + final kexTypeSha384 = SSHKexType.nistp384; + final digestSha384 = kexTypeSha384.createDigest(); + expect(digestSha384, isA()); + + final kexTypeSha512 = SSHKexType.nistp521; + final digestSha512 = kexTypeSha512.createDigest(); + expect(digestSha512, isA()); + }); + }); +} diff --git a/third_party/dartssh2/test/src/algorithm/ssh_mac_type_test.dart b/third_party/dartssh2/test/src/algorithm/ssh_mac_type_test.dart new file mode 100644 index 0000000..a1b14c0 --- /dev/null +++ b/third_party/dartssh2/test/src/algorithm/ssh_mac_type_test.dart @@ -0,0 +1,53 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:pointycastle/export.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHMacType', () { + test('Static constants are defined correctly', () { + expect(SSHMacType.hmacMd5.name, equals('hmac-md5')); + expect(SSHMacType.hmacSha1.name, equals('hmac-sha1')); + expect(SSHMacType.hmacSha256.name, equals('hmac-sha2-256')); + expect(SSHMacType.hmacSha512.name, equals('hmac-sha2-512')); + + expect(SSHMacType.hmacMd5.keySize, equals(16)); + expect(SSHMacType.hmacSha1.keySize, equals(20)); + expect(SSHMacType.hmacSha256.keySize, equals(32)); + expect(SSHMacType.hmacSha512.keySize, equals(64)); + }); + + test('createMac() returns correct Mac instance', () { + final key = Uint8List(16); // 16 bytes key for hmacMd5 + final mac = SSHMacType.hmacMd5.createMac(key); + expect(mac, isA()); + }); + + test('createMac() throws ArgumentError for incorrect key length', () { + final shortKey = Uint8List(15); // One byte too short for hmacMd5 + expect( + () => SSHMacType.hmacMd5.createMac(shortKey), + throwsArgumentError, + ); + + final longKey = Uint8List(17); // One byte too long for hmacMd5 + expect( + () => SSHMacType.hmacMd5.createMac(longKey), + throwsArgumentError, + ); + }); + + test('createMac() initializes Mac with correct key length', () { + final key = Uint8List(32); // 32 bytes key for hmacSha256 + final mac = SSHMacType.hmacSha256.createMac(key); + expect(mac, isA()); + }); + + test('createMac() initializes Mac with correct MAC factory', () { + final key = Uint8List(64); // 64 bytes key for hmacSha512 + final mac = SSHMacType.hmacSha512.createMac(key); + expect(mac, isA()); + }); + }); +} diff --git a/third_party/dartssh2/test/src/http/http_content_type_test.dart b/third_party/dartssh2/test/src/http/http_content_type_test.dart new file mode 100644 index 0000000..a0ea47d --- /dev/null +++ b/third_party/dartssh2/test/src/http/http_content_type_test.dart @@ -0,0 +1,81 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHContentType', () { + test('should return predefined text content type', () { + final contentType = SSHContentType.text; + + expect(contentType.primaryType, equals('text')); + expect(contentType.subType, equals('plain')); + expect(contentType.charset, equals('utf-8')); + }); + + test('should return predefined html content type', () { + final contentType = SSHContentType.html; + + expect(contentType.primaryType, equals('text')); + expect(contentType.subType, equals('html')); + expect(contentType.charset, equals('utf-8')); + }); + + test('should return predefined json content type', () { + final contentType = SSHContentType.json; + + expect(contentType.primaryType, equals('application')); + expect(contentType.subType, equals('json')); + expect(contentType.charset, equals('utf-8')); + }); + + test('should return predefined binary content type', () { + final contentType = SSHContentType.binary; + + expect(contentType.primaryType, equals('application')); + expect(contentType.subType, equals('octet-stream')); + expect(contentType.charset, isNull); + }); + + test('should create content type with charset', () { + final contentType = SSHContentType( + 'application', + 'xml', + charset: 'ISO-8859-1', + ); + + expect(contentType.primaryType, equals('application')); + expect(contentType.subType, equals('xml')); + expect(contentType.charset, equals('iso-8859-1')); + }); + + test('should parse content type string without parameters', () { + final contentType = SSHContentType.parse('text/html'); + + expect(contentType.primaryType, equals('text')); + expect(contentType.subType, equals('html')); + expect(contentType.charset, isNull); + }); + + test('should parse content type string with charset', () { + final contentType = SSHContentType.parse('text/html; charset=utf-8'); + + expect(contentType.primaryType, equals('text')); + expect(contentType.subType, equals('html')); + expect(contentType.charset, equals('utf-8')); + }); + + test('should parse content type string with additional parameters', () { + final contentType = SSHContentType.parse( + 'application/json; charset=utf-8; custom-param=value'); + + expect(contentType.primaryType, equals('application')); + expect(contentType.subType, equals('json')); + expect(contentType.charset, equals('utf-8')); + }); + + test('should handle invalid content type strings gracefully', () { + expect(SSHContentType.parse('invalid/type'), isA()); + expect(SSHContentType.parse('text/html;charset=utf-8;invalid'), + isA()); + }); + }); +} diff --git a/third_party/dartssh2/test/src/http/http_exception_test.dart b/third_party/dartssh2/test/src/http/http_exception_test.dart new file mode 100644 index 0000000..38bcedb --- /dev/null +++ b/third_party/dartssh2/test/src/http/http_exception_test.dart @@ -0,0 +1,59 @@ +import 'package:dartssh2/src/http/http_exception.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHHttpException', () { + test('should store and return the message correctly', () { + // Arrange + final message = 'An error occurred'; + final exception = SSHHttpException(message); + + // Act + final resultMessage = exception.message; + + // Assert + expect(resultMessage, equals(message)); + }); + + test('should store and return the URI correctly', () { + // Arrange + final message = 'An error occurred'; + final uri = Uri.parse('http://example.com/'); + final exception = SSHHttpException(message, uri: uri); + + // Act + final resultUri = exception.uri; + + // Assert + expect(resultUri, equals(uri)); + }); + + test('should return correct string representation with URI', () { + // Arrange + final message = 'An error occurred'; + final uri = Uri.parse('http://example.com/'); + final exception = SSHHttpException(message, uri: uri); + + // Act + final resultString = exception.toString(); + + // Assert + expect( + resultString, + equals( + 'SSHHttpException: An error occurred, uri = http://example.com/')); + }); + + test('should return correct string representation without URI', () { + // Arrange + final message = 'An error occurred'; + final exception = SSHHttpException(message); + + // Act + final resultString = exception.toString(); + + // Assert + expect(resultString, equals('SSHHttpException: An error occurred')); + }); + }); +} diff --git a/third_party/dartssh2/test/src/http/http_headers_test.dart b/third_party/dartssh2/test/src/http/http_headers_test.dart new file mode 100644 index 0000000..4ccfc9f --- /dev/null +++ b/third_party/dartssh2/test/src/http/http_headers_test.dart @@ -0,0 +1,61 @@ +import 'package:test/test.dart'; + +import '../mocks/mock_ssh_http_headers.dart'; + +void main() { + group('SSHHttpHeaders', () { + late MockSSHHttpHeaders headers; + + setUp(() { + headers = MockSSHHttpHeaders(); + }); + + test('should add and retrieve headers correctly', () { + headers.add('Content-Type', 'application/json'); + expect(headers['content-type'], equals(['application/json'])); + }); + + test('should set headers correctly, replacing existing values', () { + headers.add('Content-Type', 'text/plain'); + headers.set('Content-Type', 'application/json'); + expect(headers['content-type'], equals(['application/json'])); + }); + + test('should retrieve the correct single value for a header', () { + headers.set('Content-Length', 100); + expect(headers.value('Content-Length'), equals('100')); + }); + + test('should remove a specific header value', () { + headers.add('Cache-Control', 'no-cache'); + headers.add('Cache-Control', 'no-store'); + headers.remove('Cache-Control', 'no-cache'); + expect(headers['cache-control'], equals(['no-store'])); + }); + + test('should remove all values for a header', () { + headers.add('Cache-Control', 'no-cache'); + headers.removeAll('Cache-Control'); + expect(headers['cache-control'], isNull); + }); + + test('should perform action on each header correctly', () { + headers.set('Content-Type', 'application/json'); + headers.set('Accept', 'text/html'); + final collectedHeaders = >{}; + headers.forEach((name, values) { + collectedHeaders[name] = values; + }); + expect(collectedHeaders['content-type'], equals(['application/json'])); + expect(collectedHeaders['accept'], equals(['text/html'])); + }); + + test('should clear all headers', () { + headers.set('Content-Type', 'application/json'); + headers.clear(); + expect(headers['content-type'], isNull); + }); + + // Agrega más pruebas según los métodos y comportamientos específicos que quieras verificar + }); +} diff --git a/third_party/dartssh2/test/src/http/line_decoder_test.dart b/third_party/dartssh2/test/src/http/line_decoder_test.dart new file mode 100644 index 0000000..8b5de13 --- /dev/null +++ b/third_party/dartssh2/test/src/http/line_decoder_test.dart @@ -0,0 +1,88 @@ +import 'dart:convert'; + +import 'package:dartssh2/src/http/line_decoder.dart'; +import 'package:test/test.dart'; + +void main() { + group('LineDecoder', () { + late LineDecoder decoder; + late List linesReceived; + late List lengthsReceived; + + setUp(() { + linesReceived = []; + lengthsReceived = []; + decoder = + LineDecoder.withCallback((String line, int length, LineDecoder self) { + linesReceived.add(line); + lengthsReceived.add(length); + }); + }); + + test('should process complete lines correctly', () { + decoder.add(utf8.encode('line 1\nline 2\n')); + expect(linesReceived, equals(['line 1\n', 'line 2\n'])); + expect(lengthsReceived, equals([7, 7])); + }); + + test('should process partial lines and buffer correctly', () { + decoder.add(utf8.encode('partial line')); + expect(linesReceived, isEmpty); + expect(decoder.bufferedBytes, + equals(12)); // Verifica que la línea esté en el buffer + + decoder.add(utf8.encode(' complete\n')); + expect(linesReceived, equals(['partial line complete\n'])); + expect(lengthsReceived, equals([22])); + }); + + test('should handle lines split across multiple chunks', () { + decoder.add(utf8.encode('line part 1')); + decoder.add(utf8.encode(' part 2\n')); + expect(linesReceived, equals(['line part 1 part 2\n'])); + expect(lengthsReceived, equals([19])); + }); + + test('should handle an empty chunk correctly', () { + decoder.add([]); + expect(linesReceived, isEmpty); + }); + + test('should correctly call callback on close with remaining buffered data', + () { + decoder.add(utf8.encode('final line without newline')); + decoder.close(); + expect(linesReceived, equals(['final line without newline'])); + expect(lengthsReceived, equals([26])); + }); + + test('should process multiple lines in a single chunk', () { + decoder.add(utf8.encode('line 1\nline 2\nline 3\n')); + expect(linesReceived, equals(['line 1\n', 'line 2\n', 'line 3\n'])); + expect(lengthsReceived, equals([7, 7, 7])); + }); + + test('should handle expected byte count processing correctly', () { + decoder.expectedByteCount = 10; + decoder.add(utf8.encode('short\nlongerline\n')); + + // Check that 'short\n' is processed correctly + expect( + linesReceived, + equals([ + 'short\n' + 'long', + 'erline\n' + '' + ])); + expect(lengthsReceived, equals([10, 7])); + + // Check the buffer is empty + expect(decoder.bufferedBytes, equals(0)); + + // On closing, ensure the remaining buffered line is processed + decoder.close(); + expect(linesReceived.last, equals('')); + }); + }); +} diff --git a/third_party/dartssh2/test/src/kex/kex_dh_test.dart b/third_party/dartssh2/test/src/kex/kex_dh_test.dart new file mode 100644 index 0000000..8f9990c --- /dev/null +++ b/third_party/dartssh2/test/src/kex/kex_dh_test.dart @@ -0,0 +1,459 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/src/kex/kex_dh.dart'; +import 'package:dartssh2/src/utils/bigint.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHKexDH', () { + test('SSHKexDH.group1', () { + final kex1 = SSHKexDH.group1(); + final kex2 = SSHKexDH.group1(); + final secret1 = kex1.computeSecret(kex2.e); + final secret2 = kex2.computeSecret(kex1.e); + expect(secret1, secret2); + }); + + test('SSHKexDH.group14', () { + final kex1 = SSHKexDH.group14(); + final kex2 = SSHKexDH.group14(); + final secret1 = kex1.computeSecret(kex2.e); + final secret2 = kex2.computeSecret(kex1.e); + expect(secret1, secret2); + }); + test('should initialize with valid parameters (Group 1)', () { + final kex = SSHKexDH.group1(); + expect(kex.p, equals(_group1Prime)); + expect(kex.g, equals(BigInt.from(2))); + expect(kex.secretBits, equals(160)); + expect(kex.x, isNotNull); + expect(kex.e, isNotNull); + }); + + test('should initialize with valid parameters (Group 14)', () { + final kex = SSHKexDH.group14(); + expect(kex.p, equals(_group14Prime)); + expect(kex.g, equals(BigInt.from(2))); + expect(kex.secretBits, equals(224)); + expect(kex.x, isNotNull); + expect(kex.e, isNotNull); + }); + + test('should throw ArgumentError for invalid secretBits', () { + expect( + () => SSHKexDH(p: _group1Prime, g: BigInt.from(2), secretBits: 159), + throwsA(isA()), + ); + }); + + test('should compute shared secret correctly', () { + final kex = SSHKexDH.group14(); + + // Example public key f, manually set to a valid value for testing. + // This should be a known good value for testing purposes. + final f = BigInt.from( + 1234567890123456789); // Replace with a known valid value if possible + + final computedSecret = kex.computeSecret(f); + expect(computedSecret, equals(isA())); + }); + }); +} + +// Predefined group 1 prime +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, + ]), +); + +// Predefined group 14 prime +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, + ]), +); diff --git a/third_party/dartssh2/test/src/kex/kex_nist_test.dart b/third_party/dartssh2/test/src/kex/kex_nist_test.dart new file mode 100644 index 0000000..ebe24dd --- /dev/null +++ b/third_party/dartssh2/test/src/kex/kex_nist_test.dart @@ -0,0 +1,70 @@ +import 'package:dartssh2/src/kex/kex_nist.dart'; +import 'package:test/test.dart'; + +void main() { + test('SSHKexECDH.nistp256', () { + final kex1 = SSHKexNist.p256(); + final kex2 = SSHKexNist.p256(); + final secret1 = kex1.computeSecret(kex2.publicKey); + final secret2 = kex2.computeSecret(kex1.publicKey); + expect(secret1, secret2); + }); + + test('SSHKexECDH.nistp384', () { + final kex1 = SSHKexNist.p384(); + final kex2 = SSHKexNist.p384(); + final secret1 = kex1.computeSecret(kex2.publicKey); + final secret2 = kex2.computeSecret(kex1.publicKey); + expect(secret1, secret2); + }); + + test('SSHKexECDH.nistp521', () { + final kex1 = SSHKexNist.p521(); + final kex2 = SSHKexNist.p521(); + final secret1 = kex1.computeSecret(kex2.publicKey); + final secret2 = kex2.computeSecret(kex1.publicKey); + expect(secret1, secret2); + }); + + group('SSHKexNist', () { + test('generate keys and compute shared secret (P-256)', () { + final kex = SSHKexNist.p256(); + final remoteKex = SSHKexNist.p256(); + + final secret1 = kex.computeSecret(remoteKex.publicKey); + final secret2 = remoteKex.computeSecret(kex.publicKey); + + expect(secret1, equals(secret2), reason: 'Shared secrets do not match.'); + }); + + test('generate keys and compute shared secret (P-384)', () { + final kex = SSHKexNist.p384(); + final remoteKex = SSHKexNist.p384(); + + final secret1 = kex.computeSecret(remoteKex.publicKey); + final secret2 = remoteKex.computeSecret(kex.publicKey); + + expect(secret1, equals(secret2), reason: 'Shared secrets do not match.'); + }); + + test('generate keys and compute shared secret (P-521)', () { + final kex = SSHKexNist.p521(); + final remoteKex = SSHKexNist.p521(); + + final secret1 = kex.computeSecret(remoteKex.publicKey); + final secret2 = remoteKex.computeSecret(kex.publicKey); + + expect(secret1, equals(secret2), reason: 'Shared secrets do not match.'); + }); + + test('generate private key within valid range', () { + final kex = SSHKexNist.p256(); + final privateKey = kex.privateKey; + + expect(privateKey, isNot(equals(BigInt.zero)), + reason: 'Private key should not be zero.'); + expect(privateKey < kex.curve.n, isTrue, + reason: 'Private key should be less than curve order.'); + }); + }); +} diff --git a/third_party/dartssh2/test/src/kex/kex_x25519_test.dart b/third_party/dartssh2/test/src/kex/kex_x25519_test.dart new file mode 100644 index 0000000..f6ded39 --- /dev/null +++ b/third_party/dartssh2/test/src/kex/kex_x25519_test.dart @@ -0,0 +1,64 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/src/kex/kex_x25519.dart'; +import 'package:test/test.dart'; + +void main() { + test('SSHKexX25519', () { + final kex1 = SSHKexX25519(); + final kex2 = SSHKexX25519(); + final secret1 = kex1.computeSecret(kex2.publicKey); + final secret2 = kex2.computeSecret(kex1.publicKey); + expect(secret1, secret2); + }); + group('SSHKexX25519', () { + late SSHKexX25519 kex; + + setUp(() { + kex = SSHKexX25519(); + }); + + test('should generate a 32-byte private key', () { + expect(kex.privateKey.length, equals(32)); + }); + + test('should generate a 32-byte public key', () { + expect(kex.publicKey.length, equals(32)); + }); + + test('should compute shared secret correctly', () { + // Generate a new SSHKexX25519 instance to act as the remote party + final remoteKex = SSHKexX25519(); + + // Compute the shared secret using the local private key and remote public key + final sharedSecret = kex.computeSecret(remoteKex.publicKey); + + // Compute the shared secret using the remote private key and local public key + final remoteSharedSecret = remoteKex.computeSecret(kex.publicKey); + + // Assert that both shared secrets are equal + expect(sharedSecret, equals(remoteSharedSecret)); + }); + + test('should handle invalid public key length in computeSecret', () { + final invalidPublicKey = Uint8List(31); // Invalid length + + expect(() => kex.computeSecret(invalidPublicKey), + throwsA(isA())); + }); + + test('should handle valid inputs for scalar multiplication indirectly', () { + // This test is intended to indirectly verify the behavior of scalar multiplication + // through the public method computeSecret. + + final validPublicKey = kex.publicKey; + + // Test valid scenario using computeSecret + final validKex = SSHKexX25519(); + final validSharedSecret = validKex.computeSecret(validPublicKey); + + expect(validSharedSecret, isNotNull); + expect(validSharedSecret.bitLength, greaterThan(0)); + }); + }); +} diff --git a/third_party/dartssh2/test/src/mocks/mock_ssh_http_headers.dart b/third_party/dartssh2/test/src/mocks/mock_ssh_http_headers.dart new file mode 100644 index 0000000..3225c2d --- /dev/null +++ b/third_party/dartssh2/test/src/mocks/mock_ssh_http_headers.dart @@ -0,0 +1,62 @@ +import 'package:dartssh2/dartssh2.dart'; + +class MockSSHHttpHeaders extends SSHHttpHeaders { + final Map> _headers = {}; + + @override + List? operator [](String name) => _headers[name.toLowerCase()]; + + @override + String? value(String name) { + final values = _headers[name.toLowerCase()]; + if (values != null && values.length == 1) { + return values.first; + } + return null; + } + + @override + void add(String name, Object value, {bool preserveHeaderCase = false}) { + final headerName = preserveHeaderCase ? name : name.toLowerCase(); + final valueStr = + value is DateTime ? value.toIso8601String() : value.toString(); + _headers.putIfAbsent(headerName, () => []).add(valueStr); + } + + @override + void set(String name, Object value, {bool preserveHeaderCase = false}) { + final headerName = preserveHeaderCase ? name : name.toLowerCase(); + final valueStr = + value is DateTime ? value.toIso8601String() : value.toString(); + _headers[headerName] = [valueStr]; + } + + @override + void remove(String name, Object value) { + final values = _headers[name.toLowerCase()]; + values?.remove(value.toString()); + if (values != null && values.isEmpty) { + _headers.remove(name.toLowerCase()); + } + } + + @override + void removeAll(String name) { + _headers.remove(name.toLowerCase()); + } + + @override + void forEach(void Function(String name, List values) action) { + _headers.forEach(action); + } + + @override + void noFolding(String name) { + // Implementar comportamiento de no fold + } + + @override + void clear() { + _headers.clear(); + } +} diff --git a/third_party/dartssh2/test/src/sftp/sftp_client_test.dart b/third_party/dartssh2/test/src/sftp/sftp_client_test.dart new file mode 100644 index 0000000..5368622 --- /dev/null +++ b/third_party/dartssh2/test/src/sftp/sftp_client_test.dart @@ -0,0 +1,22 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +import '../../test_utils.dart'; + +void main() { + group('SftpClient.statVFS', () { + test('throws if the extension is not supported by the server', () async { + final client = await getTestClient(); + final sftp = await client.sftp(); + expect(() => sftp.statvfs('/root'), throwsA(isA())); + }); + }); + + group('SftpFile.statVFS', () { + test('throws if the extension is not supported by the server', () async { + final client = await getTestClient(); + final sftp = await client.sftp(); + expect(() => sftp.statvfs('/root/a'), throwsA(isA())); + }); + }); +} diff --git a/third_party/dartssh2/test/src/sftp/sftp_stream_io_test.dart b/third_party/dartssh2/test/src/sftp/sftp_stream_io_test.dart new file mode 100644 index 0000000..5693fea --- /dev/null +++ b/third_party/dartssh2/test/src/sftp/sftp_stream_io_test.dart @@ -0,0 +1,71 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +import '../../test_utils.dart'; + +void main() { + late SSHClient client; + + setUp(() async { + client = await getTestClient(); + }); + + tearDown(() async { + client.close(); + await client.done; + }); + + /* + group('SftpFileWriter', () { + test('can pause & resume', () async { + final sftp = await client.sftp(); + + final dataController = StreamController( + onListen: () => print('onListen'), + onPause: () => print('onPause'), + onResume: () => print('onResume'), + onCancel: () => print('onCancel'), + ); + final dataToUpload = dataController.stream; + + final file = await sftp.open( + 'a.out', + mode: SftpFileOpenMode.create | SftpFileOpenMode.write, + ); + final writer = file.write(dataToUpload); + + dataController.add(Uint8List(100)); + + await Future.delayed(Duration(milliseconds: 1)); + expect(dataController.isPaused, isFalse); + + dataController.add(Uint8List(100)); + writer.pause(); + + await Future.delayed(Duration(milliseconds: 1)); + expect(dataController.isPaused, isTrue); + + dataController.add(Uint8List(100)); + writer.resume(); + + await Future.delayed(Duration(milliseconds: 1)); + expect(dataController.isPaused, isFalse); + + await dataController.close(); + await writer.done; + }); + + test('can be awaited', () async { + final sftp = await client.sftp(); + final file = await sftp.open( + 'a.out', + mode: SftpFileOpenMode.create | SftpFileOpenMode.write, + ); + + final uploader = file.write(Stream.value(Uint8List(100))); + await uploader; + expect(uploader.progress, 100); + }); + }); + */ +} diff --git a/third_party/dartssh2/test/src/socket/ssh_socket_io_test.dart b/third_party/dartssh2/test/src/socket/ssh_socket_io_test.dart new file mode 100644 index 0000000..82c4be9 --- /dev/null +++ b/third_party/dartssh2/test/src/socket/ssh_socket_io_test.dart @@ -0,0 +1,13 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +void main() { + group('SSHSocket', () { + test('can establish tcp connections', () async { + final socket = await SSHSocket.connect('time.nist.gov', 13); + final firstPacket = await socket.stream.first; + expect(firstPacket, isNotEmpty); + await socket.close(); + }); + }); +} diff --git a/third_party/dartssh2/test/src/ssh_client_test.dart b/third_party/dartssh2/test/src/ssh_client_test.dart new file mode 100644 index 0000000..8a6abd8 --- /dev/null +++ b/third_party/dartssh2/test/src/ssh_client_test.dart @@ -0,0 +1,127 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +import '../test_utils.dart'; + +void main() { + group('SSHClient', () { + test('can connect to a ssh server', () async { + var client = await getHoneypotClient(); + await client.authenticated; + client.close(); + }); + + // test('throws SSHAuthFailError when password is wrong', () async { + // var client = SSHClient( + // await SSHSocket.connect('test.rebex.net', 22), + // username: 'root', + // onPasswordRequest: () => 'bad-password', + // ); + // try { + // await client.authenticated; + // fail('should have thrown'); + // } catch (e) { + // expect(e, isA()); + // } + // client.close(); + // }); + + test('throws SSHAuthFailError when public key is wrong', () async { + var client = SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'demos', + identities: await getTestKeyPairs(), + ); + try { + await client.authenticated; + fail('should have thrown'); + } catch (e) { + expect(e, isA()); + } + client.close(); + }); + + test('throws SSHAuthFailError when all public keys are wrong', () async { + var client = SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'bad-user', + identities: [ + ...await getTestKeyPairs(), + ...await getTestKeyPairs(), + ], + ); + try { + await client.authenticated; + fail('should have thrown'); + } catch (e) { + expect(e, isA()); + } + client.close(); + }); + + test( + 'throws SSHAuthFailError when both password and public key are wrong', + () async { + var client = SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'demo', + onPasswordRequest: () => 'bad-password', + identities: await getTestKeyPairs(), + ); + try { + await client.authenticated; + fail('should have thrown'); + } catch (e) { + expect(e, isA()); + } + client.close(); + }, + ); + + test('throws SSHAuthFailError when identity is empty', () async { + var client = SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'demo', + identities: [], + ); + try { + await client.authenticated; + fail('should have thrown'); + } catch (e) { + expect(e, isA()); + } + client.close(); + }); + + test('throws SSHAuthAbortError when the handshake is aborted', () async { + var client = SSHClient( + await SSHSocket.connect('bing.com', 443), + username: 'root', + onPasswordRequest: () => 'bad-password', + ); + + try { + await client.authenticated; + fail('should have thrown'); + } catch (e) { + expect(e, isA()); + } + + client.close(); + }); + + test('can get remote ssh software version after handshaking', () async { + var client = await getHoneypotClient(); + await client.authenticated; + expect(client.remoteVersion, startsWith('SSH-2.0')); + client.close(); + }); + }); + + group('SSHClient.ping', () { + test('works', () async { + final client = await getTestClient(); + await client.ping(); + }); + }); +} diff --git a/third_party/dartssh2/test/src/ssh_key_pair_test.dart b/third_party/dartssh2/test/src/ssh_key_pair_test.dart new file mode 100644 index 0000000..7045819 --- /dev/null +++ b/third_party/dartssh2/test/src/ssh_key_pair_test.dart @@ -0,0 +1,149 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:test/test.dart'; + +import '../test_utils.dart'; + +// extension StringReadAsFile on String { +// String readFile() => File(this).readAsStringSync(); +// } + +void main() { + final rsaPrivate = fixture('ssh-rsa/id_rsa'); + final rsaPrivateOpenSSH = fixture('ssh-rsa/id_rsa.openssh'); + + final rsaPrivateEncrypted = fixture('ssh-rsa-passphrase/id_rsa'); + final rsaPassphrase = fixture('ssh-rsa-passphrase/passphrase'); + + final ecdsaNistP256Private = fixture('ecdsa-sha2-nistp256/id_ecdsa'); + // final ecdsaNistP384Private = fixture('ecdsa-sha2-nistp384/id_ecdsa'); + // final ecdsaNistP521Private = fixture('ecdsa-sha2-nistp521/id_ecdsa'); + + final ed25519Private = fixture('ssh-ed25519/id_ed25519'); + final ed25519PrivateEncrypted = fixture('ssh-ed25519-passphrase/id_ed25519'); + final ed25519PrivatePassphrase = fixture('ssh-ed25519-passphrase/passphrase'); + + test('SSHKeyPair.fromPem works with RSA private key', () async { + final pem = rsaPrivate; + final keypair = SSHKeyPair.fromPem(pem); + expect(keypair.length, 1); + expect(keypair.single, isA()); + }); + + test('SSHKeyPair.fromPem works with ECdSA private key', () async { + final pem = ecdsaNistP256Private; + final keypair = SSHKeyPair.fromPem(pem); + expect(keypair.length, 1); + expect(keypair.single, isA()); + }); + + test('SSHKeyPair.fromPem works with Ed25519 private key', () async { + final pem = ed25519Private; + final keypairs = SSHKeyPair.fromPem(pem); + expect(keypairs.length, 1); + expect(keypairs.single, isA()); + }); + + test('SSHKeyPair.isEncryptedPem works with RSA private key', () async { + final pem = rsaPrivate; + final pemEncrypted = rsaPrivateEncrypted; + expect(SSHKeyPair.isEncryptedPem(pem), false); + expect(SSHKeyPair.isEncryptedPem(pemEncrypted), true); + }); + + test('SSHKeyPair.isEncryptedPem works with ed25519 private key', () async { + final pem = ed25519Private; + final pemEncrypted = ed25519PrivateEncrypted; + expect(SSHKeyPair.isEncryptedPem(pem), false); + expect(SSHKeyPair.isEncryptedPem(pemEncrypted), true); + }); + + test('SSHKeyPair.fromPem can decrypt RSA private key', () async { + final pem = rsaPrivateEncrypted; + final passphrase = rsaPassphrase; + final keypair = SSHKeyPair.fromPem(pem, passphrase); + expect(keypair.length, 1); + expect(keypair.single, isA()); + expect(keypair.single.toPem(), rsaPrivate); + }); + + test('SSHKeyPair.fromPem can decrypt ed25519 private key', () async { + final pem = ed25519PrivateEncrypted; + final passphrase = ed25519PrivatePassphrase; + final keypairs = SSHKeyPair.fromPem(pem, passphrase); + expect(keypairs.length, 1); + expect(keypairs.single, isA()); + }); + + test('SSHKeyPair.fromPem with wrong passphrase throws on RSA key', () async { + final pem = rsaPrivateEncrypted; + final passphrase = 'wrong'; + expect( + () => SSHKeyPair.fromPem(pem, passphrase), + throwsA(isA()), + ); + }); + + test('SSHKeyPair.fromPem with wrong passphrase throws on ed25519', () async { + final pem = ed25519PrivateEncrypted; + final passphrase = 'wrong'; + expect( + () => SSHKeyPair.fromPem(pem, passphrase), + throwsA(isA()), + ); + }); + + test('RsaPrivateKey.toPem() works', () async { + final pem = rsaPrivate; + final keypair = SSHKeyPair.fromPem(pem).single; + expect(keypair.toPem(), pem); + }); + + test('OpenSSHRsaKeyPair.toPem() works', () async { + final pem1 = rsaPrivateOpenSSH; + final keypair1 = SSHKeyPair.fromPem(pem1).single as OpenSSHRsaKeyPair; + + final pem2 = keypair1.toPem(); + final keypair2 = SSHKeyPair.fromPem(pem2).single as OpenSSHRsaKeyPair; + + expect(pem1.length, pem2.length); + + final dataToSign = Uint8List.fromList('random-data-to-sign'.codeUnits); + final signature1 = keypair1.sign(dataToSign); + final signature2 = keypair2.sign(dataToSign); + + expect(signature1.type, signature2.type); + expect(signature1.signature, signature2.signature); + }); + + test('OpenSSHEcdsaKeyPair.toPem() works', () async { + final pem1 = ecdsaNistP256Private; + final keypair1 = SSHKeyPair.fromPem(pem1).single as OpenSSHEcdsaKeyPair; + + final pem2 = keypair1.toPem(); + final keypair2 = SSHKeyPair.fromPem(pem2).single as OpenSSHEcdsaKeyPair; + + expect(pem1.length, pem2.length); + + expect(keypair1.curveId, keypair2.curveId); + expect(keypair1.d, keypair2.d); + expect(keypair1.q, keypair2.q); + }); + + test('OpenSSHEd25519KeyPair.toPem() works', () async { + final pem1 = ed25519Private; + final keypair1 = SSHKeyPair.fromPem(pem1).single as OpenSSHEd25519KeyPair; + + final pem2 = keypair1.toPem(); + final keypair2 = SSHKeyPair.fromPem(pem2).single as OpenSSHEd25519KeyPair; + + expect(pem1.length, pem2.length); + + final dataToSign = Uint8List.fromList('random-data-to-sign'.codeUnits); + final signature1 = keypair1.sign(dataToSign); + final signature2 = keypair2.sign(dataToSign); + + expect(signature1.signature, signature2.signature); + }); +} diff --git a/third_party/dartssh2/test/src/ssh_pem_test.dart b/third_party/dartssh2/test/src/ssh_pem_test.dart new file mode 100644 index 0000000..563afe9 --- /dev/null +++ b/third_party/dartssh2/test/src/ssh_pem_test.dart @@ -0,0 +1,38 @@ +import 'package:dartssh2/dartssh2.dart'; + +import 'package:test/test.dart'; + +void main() { + test('SSHPem.decode works', () { + final pem = SSHPem.decode(r'''-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpAAAAKBQ6gOSUOoD +kgAAAAtzc2gtZWQyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpA +AAAEAP8fq0hjlR3jhL7pg+26PSaMiC1V/RrinVbo/4eBMRNFmeedhmMVDtm3SAzInZhiYM +g1O5wsVZjzX9a6/Zo4ikAAAAGWpmb3V0dHNAVVNBSkZPVVRUU00ubG9jYWwBAgME +-----END OPENSSH PRIVATE KEY-----'''); + + expect(pem.type, 'OPENSSH PRIVATE KEY'); + }); + + test('SSHPem.decode can parse header', () { + final pem = SSHPem.decode(r'''-----BEGIN OPENSSH PRIVATE KEY----- +Header1: Value1 +Header2: Value2 +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpAAAAKBQ6gOSUOoD +kgAAAAtzc2gtZWQyNTUxOQAAACBZnnnYZjFQ7Zt0gMyJ2YYmDINTucLFWY81/Wuv2aOIpA +AAAEAP8fq0hjlR3jhL7pg+26PSaMiC1V/RrinVbo/4eBMRNFmeedhmMVDtm3SAzInZhiYM +g1O5wsVZjzX9a6/Zo4ikAAAAGWpmb3V0dHNAVVNBSkZPVVRUU00ubG9jYWwBAgME +-----END OPENSSH PRIVATE KEY-----'''); + + expect(pem.headers, { + 'Header1': 'Value1', + 'Header2': 'Value2', + }); + }); + + test('SSHPem.decode throws on invalid PEM', () { + expect(() => SSHPem.decode(''), throwsA(isA())); + }); +} diff --git a/third_party/dartssh2/test/src/utils/bcrypt_test.dart b/third_party/dartssh2/test/src/utils/bcrypt_test.dart new file mode 100644 index 0000000..e9ec7ec --- /dev/null +++ b/third_party/dartssh2/test/src/utils/bcrypt_test.dart @@ -0,0 +1,82 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/src/utils/bcrypt.dart'; +import 'package:test/test.dart'; + +void main() { + test('bcrypt_pbkdf', () { + final passphrase = Uint8List.fromList( + [49, 50, 51, 52, 53, 54], + ); + + final salt = Uint8List.fromList( + [180, 151, 210, 40, 110, 7, 72, 146, 145, 81, 92, 133, 92, 72, 202, 61], + ); + + final output = Uint8List(48); + + bcrypt_pbkdf( + passphrase, + passphrase.lengthInBytes, + salt, + salt.lengthInBytes, + output, + output.lengthInBytes, + 16, + ); + + expect( + output, + Uint8List.fromList([ + 176, + 247, + 9, + 83, + 159, + 104, + 252, + 200, + 108, + 121, + 127, + 254, + 249, + 17, + 36, + 46, + 110, + 105, + 124, + 105, + 58, + 131, + 59, + 151, + 33, + 134, + 88, + 36, + 11, + 191, + 130, + 97, + 65, + 69, + 243, + 216, + 159, + 223, + 179, + 176, + 185, + 5, + 228, + 254, + 245, + 2, + 178, + 59, + ]), + ); + }); +} diff --git a/third_party/dartssh2/test/src/utils/stream_test.dart b/third_party/dartssh2/test/src/utils/stream_test.dart new file mode 100644 index 0000000..0de8774 --- /dev/null +++ b/third_party/dartssh2/test/src/utils/stream_test.dart @@ -0,0 +1,54 @@ +import 'dart:typed_data'; + +import 'package:dartssh2/src/utils/stream.dart'; +import 'package:test/test.dart'; + +void main() { + group('StreamConsumer', () { + test('works', () async { + final stream = Stream.fromIterable([ + Uint8List.fromList([1, 2, 3, 4, 5]), + Uint8List.fromList([6, 7, 8, 9, 10]), + ]); + final consumer = StreamConsumer(stream); + + expect( + await consumer.read(3), + equals(Uint8List.fromList([1, 2, 3])), + ); + expect( + await consumer.read(3), + equals(Uint8List.fromList([4, 5])), + ); + expect( + await consumer.read(5), + equals(Uint8List.fromList([6, 7, 8, 9, 10])), + ); + expect(await consumer.read(1), isNull); + }); + + test('has a fast path to read entire chunk', () async { + final chunk1 = Uint8List.fromList([1, 2, 3, 4, 5]); + final chunk2 = Uint8List.fromList([6, 7, 8, 9, 10]); + final stream = Stream.fromIterable([chunk1, chunk2]); + final consumer = StreamConsumer(stream); + + expect(identical(await consumer.read(5), chunk1), isTrue); + expect(identical(await consumer.read(6), chunk2), isTrue); + expect(await consumer.read(1), isNull); + }); + + test('always return null after done', () async { + final stream = Stream.fromIterable([ + Uint8List.fromList([1, 2, 3, 4, 5]), + ]); + + final consumer = StreamConsumer(stream); + await consumer.read(5); + + expect(await consumer.read(1), isNull); + expect(await consumer.read(1), isNull); + expect(await consumer.read(1), isNull); + }); + }); +} diff --git a/third_party/dartssh2/test/test_utils.dart b/third_party/dartssh2/test/test_utils.dart new file mode 100644 index 0000000..0550184 --- /dev/null +++ b/third_party/dartssh2/test/test_utils.dart @@ -0,0 +1,42 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; + +/// A honeypot that accepts all passwords and public-keys +Future getHoneypotClient() async { + return SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'demo', + onPasswordRequest: () => 'password', + ); +} + +/// A honeypot that denies all passwords and public-keys +Future getDenyingHoneypotClient() async { + return SSHClient( + await SSHSocket.connect('honeypot.terminal.studio', 2023), + username: 'root', + onPasswordRequest: () => 'random', + ); +} + +/// A test server provided by test.rebex.net. +Future getTestClient() async { + return SSHClient( + await SSHSocket.connect('test.rebex.net', 22), + username: 'demo', + onPasswordRequest: () => 'password', + ); +} + +Future> getTestKeyPairs() async { + final ed25519Private = fixture('ssh-ed25519/id_ed25519'); + return SSHKeyPair.fromPem(ed25519Private); +} + +/// Get the contents of a test fixture. +/// +/// The path is relative to the test/fixtures directory. +String fixture(String path) { + return File('test/fixtures/$path').readAsStringSync(); +}