fix: harden local proxy and import boundaries
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
# Functionality and Next Steps Report
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
This fix pass improved robustness around local proxying, file imports, remote downloads, SSH key management, and frontend rendering. The app now fails earlier and more predictably when inputs are malformed or too large.
|
||||
|
||||
Highest-impact next steps:
|
||||
|
||||
- Manually verify packaged VNC connections after the new Origin allowlist.
|
||||
- Add UI copy for newly enforced limits.
|
||||
- Add CI coverage for the security checks run in this pass.
|
||||
- Continue frontend cleanup around dynamic `innerHTML`.
|
||||
|
||||
## 2. Current Functional Risks
|
||||
|
||||
VNC runtime compatibility:
|
||||
|
||||
- The backend now allows missing, `wails://`, and loopback HTTP(S) origins. This should work for Wails/noVNC, but packaged app validation is still needed.
|
||||
|
||||
Large-file and large-download behavior:
|
||||
|
||||
- GitHub archive downloads now stop at 2 GiB. Very large repositories will fail fast.
|
||||
- SSH config imports now reject files above 5 MiB or more than 5000 Host blocks.
|
||||
|
||||
SSH key generation:
|
||||
|
||||
- RSA key generation is limited to 2048, 3072, and 4096 bits and times out after 30 seconds.
|
||||
- Slow systems should be checked with RSA 4096 to ensure the timeout is not too tight.
|
||||
|
||||
Frontend:
|
||||
|
||||
- SSH key manager dynamic rendering is safer. Other static `innerHTML` templates remain and should be reviewed when they take dynamic data.
|
||||
|
||||
## 3. Code Quality Improvements
|
||||
|
||||
Completed:
|
||||
|
||||
- Added focused helper functions for VNC Origin validation.
|
||||
- Centralized GitHub endpoint construction and owner/repo parsing.
|
||||
- Added reusable archive stream limiting.
|
||||
- Added backend SSH key generation option validation.
|
||||
- Added import bounds to the SSH config parser.
|
||||
- Replaced SSH key manager dynamic modal HTML with DOM construction.
|
||||
|
||||
Recommended refactors:
|
||||
|
||||
- Move file-size and stream-size caps into named settings or a shared limits package if more subsystems need them.
|
||||
- Add a small frontend helper for safe modal construction so feature code stops hand-rolling modal `innerHTML`.
|
||||
- Consider a common backend "safe basename" helper for local and remote file operations.
|
||||
|
||||
## 4. Frontend Interaction and Error-Handling Improvements
|
||||
|
||||
Recommended:
|
||||
|
||||
- Show a specific VNC connection error if the proxy rejects an unexpected Origin in packaged builds.
|
||||
- Show clear messages for SSH config files that exceed size or Host-block limits.
|
||||
- Show clear messages for GitHub archives above the cap.
|
||||
- Add a hostile-filename E2E test for the SSH key delete confirmation modal.
|
||||
- Continue converting dynamic modal content to DOM nodes or `textContent`.
|
||||
|
||||
## 5. Testing Roadmap
|
||||
|
||||
Added in this pass:
|
||||
|
||||
- VNC Origin allowlist tests.
|
||||
- SFTP upload parent-directory rejection tests.
|
||||
- SSH config file and Host-block limit tests.
|
||||
- SSH key generation option validation tests.
|
||||
- GitHub path escaping and archive cap tests.
|
||||
- Frontend regression checks for SSH key manager text rendering.
|
||||
|
||||
Next tests:
|
||||
|
||||
- Packaged Wails VNC smoke test on macOS, Windows, and Linux.
|
||||
- Browser/E2E test for SSH key filenames containing `<`, `>`, quotes, and ampersands.
|
||||
- HTTP integration test for GitHub archive download caps and escaped branch refs.
|
||||
- UI tests for limit-aware error messages.
|
||||
- CI job that runs Go tests, frontend tests, frontend build, `npm audit --omit=dev`, `govulncheck`, and `git diff --check`.
|
||||
|
||||
## 6. Recommended New Functionality
|
||||
|
||||
Useful additions:
|
||||
|
||||
- Preferences for maximum GitHub archive download size.
|
||||
- A pre-download confirmation for large GitHub archives when Content-Length is known.
|
||||
- Import preview for OpenSSH config showing Host count before persistence.
|
||||
- A diagnostics panel for VNC proxy status, including local URL redaction, Origin decisions, and connection state.
|
||||
- A unified "Limits" help page that lists SFTP upload caps, GitHub archive cap, SSH config import cap, and Leviathan file caps.
|
||||
|
||||
## 7. Next-Level Opportunities
|
||||
|
||||
Architecture:
|
||||
|
||||
- Centralize resource limits and expose them to both Go and frontend UI copy.
|
||||
- Add a secure modal builder and migrate risky frontend dialogs gradually.
|
||||
- Add structured security regression tests for every Wails method that accepts file paths, filenames, URLs, or base64 payloads.
|
||||
|
||||
Operations:
|
||||
|
||||
- Generate checksums for release artifacts.
|
||||
- Generate an SBOM during release.
|
||||
- Publish a short security hardening checklist in `docs/build-and-release.md`.
|
||||
|
||||
Developer experience:
|
||||
|
||||
- Add a `make security-check` target that runs the same commands used in this audit.
|
||||
- Add pre-commit or CI checks for `gofmt`, `go test`, frontend regression tests, and `git diff --check`.
|
||||
|
||||
## 8. Prioritised Action Plan
|
||||
|
||||
Immediate:
|
||||
|
||||
- Manually test packaged VNC on all supported platforms.
|
||||
- Keep the security patch tests in CI before release.
|
||||
|
||||
Short-term:
|
||||
|
||||
- Add user-facing messages for the new SSH config, GitHub archive, and SSH keygen limits.
|
||||
- Add E2E coverage for hostile SSH key filenames.
|
||||
- Add an HTTP test around GitHub archive download behavior.
|
||||
|
||||
Medium-term:
|
||||
|
||||
- Centralize app resource limits and expose them to UI/help.
|
||||
- Migrate high-risk frontend dynamic HTML patterns to safe modal helpers.
|
||||
- Add release checksums and SBOM generation.
|
||||
|
||||
Long-term:
|
||||
|
||||
- Add progressive/streaming UX for large GitHub and SFTP transfers.
|
||||
- Build a cross-platform packaged-app smoke test suite for Wails integrations.
|
||||
|
||||
## 9. Caveats and Validation Needed
|
||||
|
||||
- VNC Origin compatibility must be validated in packaged builds, not only unit tests.
|
||||
- The 2 GiB GitHub archive cap may need product tuning for users with very large repositories.
|
||||
- RSA 4096 key generation timeout should be checked on lower-powered machines.
|
||||
- The frontend build passed, but this pass did not interactively click through the SSH key modal in a real browser/WebView.
|
||||
@@ -0,0 +1,641 @@
|
||||
# Security Audit Report
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
This fix-mode audit reviewed the Wails API surface, local proxy behavior, file import paths, SSH key management, GitHub integration, frontend DOM sinks, dependency manifests, tests, and release workflow.
|
||||
|
||||
Six concrete issues were fixed:
|
||||
|
||||
- The local VNC WebSocket proxy accepted any browser `Origin` and did not cap client-to-proxy WebSocket message size.
|
||||
- SFTP browser uploads accepted the special filename `..`, allowing a Wails caller to escape the selected remote directory when the name was joined.
|
||||
- SSH config import parsed line-by-line but had no total file or Host-block cap.
|
||||
- Backend SSH key generation trusted caller-supplied key type and RSA bit count and had no process timeout.
|
||||
- GitHub repo/ref values were interpolated into API paths without escaping, and archive downloads had no explicit stream cap.
|
||||
- SSH key manager UI interpolated backend errors and filesystem-derived key names into `innerHTML`.
|
||||
|
||||
Verification passed with targeted Go tests, full Go tests, frontend regression checks, frontend build, `npm audit --omit=dev`, `govulncheck`, and `git diff --check`.
|
||||
|
||||
## 2. Scope Reviewed
|
||||
|
||||
Reviewed:
|
||||
|
||||
- Go backend packages under `internal/`: API bindings, VNC proxy, GitHub client, SSH config import, SSH key management, SFTP upload helpers, validation, sessions, storage, secrets, updater, recording, Leviathan parser bounds, and tests.
|
||||
- Browser-facing JavaScript under `frontend/src/js`, especially SSH key management, SFTP upload flows, VNC integration, and dynamic HTML usage.
|
||||
- Frontend package manifest, lockfile, build scripts, and regression script.
|
||||
- Go module dependencies and reachable vulnerability state.
|
||||
- GitHub Actions release workflow.
|
||||
|
||||
Not fully live-tested:
|
||||
|
||||
- A packaged Wails desktop binary.
|
||||
- Real noVNC connections inside the packaged WebView after the new Origin policy.
|
||||
- Real GitHub Enterprise archive downloads above normal repository sizes.
|
||||
|
||||
## 3. Methodology
|
||||
|
||||
The review used static analysis, targeted source searches, dependency/advisory tooling, and focused regression tests. I mapped attacker-controlled inputs from the renderer and local files into Go methods, network clients, local HTTP/WebSocket services, subprocesses, remote SFTP paths, and DOM sinks. I prioritized issues that could be fixed with small behavior-preserving changes and backed by tests.
|
||||
|
||||
Commands run:
|
||||
|
||||
- `go test ./internal/vncclient ./internal/api ./internal/sshconfig ./internal/githubclient -count=1`
|
||||
- `npm --prefix frontend test`
|
||||
- `git diff --check`
|
||||
- `go test ./... -count=1`
|
||||
- `npm --prefix frontend run build`
|
||||
- `npm --prefix frontend audit --omit=dev`
|
||||
- `go run golang.org/x/vuln/cmd/govulncheck@latest ./...`
|
||||
|
||||
## 4. Risk Rating Method
|
||||
|
||||
Severity reflects exploit prerequisite, affected trust boundary, likely impact, and availability/confidentiality/integrity outcome:
|
||||
|
||||
- Critical: remote unauthenticated compromise or secret disclosure.
|
||||
- High: practical compromise of credentials, host access, or arbitrary code execution.
|
||||
- Medium: meaningful local, renderer, remote service, or connected-server abuse with realistic prerequisites.
|
||||
- Low: local robustness issues, bounded DoS, or defense-in-depth gaps.
|
||||
- Informational: observations and hardening opportunities.
|
||||
|
||||
Confidence reflects direct code evidence and testability. Findings fixed here are High confidence because they map to concrete files and new regression tests.
|
||||
|
||||
## 5. Attack Surface Map
|
||||
|
||||
Entry points:
|
||||
|
||||
- Wails-bound `api.Service` methods callable from the renderer.
|
||||
- Local VNC WebSocket proxy bound to `127.0.0.1` on a random port and random token path.
|
||||
- SSH, Telnet, RAW TCP, VNC, SFTP, GitHub, updater, and Leviathan binary-analysis workflows.
|
||||
- Profile import/export, encrypted `.nexus` import, OpenSSH config import, recording playback, SSH key generation/deletion, and drag/drop upload flows.
|
||||
|
||||
Trust boundaries:
|
||||
|
||||
- Renderer to Go backend.
|
||||
- Local browser/WebView to loopback VNC proxy.
|
||||
- Local filesystem files selected or scanned by the app.
|
||||
- Remote SSH/SFTP/VNC/GitHub/update endpoints.
|
||||
- OS keychain/encrypted vault to profile storage and session runtime.
|
||||
|
||||
Attacker starting positions considered:
|
||||
|
||||
- Malicious local webpage attempting loopback WebSocket access.
|
||||
- Malicious or compromised renderer script.
|
||||
- Malicious local filename or selected config/import file.
|
||||
- Malicious GitHub Enterprise/API endpoint or unusual repo/ref metadata.
|
||||
- Malicious connected SSH/SFTP/VNC host.
|
||||
|
||||
## 6. Findings Summary Table
|
||||
|
||||
| ID | Severity | Confidence | Title | Component | Status |
|
||||
|---|---|---|---|---|---|
|
||||
| SEC-20260616-1702-001 | Medium | High | VNC proxy allowed all origins and uncapped WebSocket frames | `internal/vncclient` | Fixed |
|
||||
| SEC-20260616-1702-002 | Medium | High | SFTP upload name `..` escaped selected remote directory | `internal/api` SFTP upload helpers | Fixed |
|
||||
| SEC-20260616-1702-003 | Low | High | SSH config import lacked total file and Host-block bounds | `internal/sshconfig` | Fixed |
|
||||
| SEC-20260616-1702-004 | Low | High | SSH key generation allowed expensive caller-controlled options without timeout | `internal/api` SSH key management | Fixed |
|
||||
| SEC-20260616-1702-005 | Medium | High | GitHub repo/ref path interpolation and uncapped archive stream | `internal/githubclient` | Fixed |
|
||||
| SEC-20260616-1702-006 | Medium | High | SSH key manager rendered key names/errors through dynamic `innerHTML` | `frontend/src/js/sshkeys.js` | Fixed |
|
||||
|
||||
## 7. Detailed Findings
|
||||
|
||||
### Finding ID: SEC-20260616-1702-001
|
||||
|
||||
#### Title
|
||||
|
||||
VNC proxy allowed all origins and uncapped WebSocket frames
|
||||
|
||||
#### Severity
|
||||
|
||||
Medium
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `internal/vncclient/vncclient.go`
|
||||
- `internal/vncclient/vncclient_test.go`
|
||||
- Local noVNC WebSocket proxy
|
||||
|
||||
#### Description
|
||||
|
||||
The VNC proxy was bound to loopback and protected by a random token path, but its Gorilla WebSocket upgrader accepted every `Origin`. It also read WebSocket messages without an explicit message size limit. If a proxy URL token leaked through logs, UI state, injected renderer code, or another local channel, a non-local browser origin could attempt to drive the active VNC TCP connection or send oversized frames that force memory allocation.
|
||||
|
||||
#### Evidence
|
||||
|
||||
Before the fix, `websocket.Upgrader.CheckOrigin` returned `true` for every request, and the proxy called `ws.ReadMessage()` without `SetReadLimit`.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A malicious local webpage or injected renderer script obtains an active `ws://127.0.0.1:<port>/<token>` URL. Because all origins were accepted, it could connect from a non-app origin and send very large WebSocket messages or VNC protocol bytes into the bridged TCP connection.
|
||||
|
||||
#### Impact
|
||||
|
||||
Potential local cross-origin abuse of active VNC sessions if the token is exposed, and avoidable memory pressure from oversized client-to-proxy WebSocket frames.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Allow only Wails and loopback browser origins, keep accepting missing origins for non-browser clients, and cap inbound WebSocket message size.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented `allowProxyOrigin`, `isLoopbackHost`, and `ws.SetReadLimit(maxWebSocketMessageBytes)`.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added `TestAllowProxyOrigin` for missing, Wails, loopback, remote, lookalike, and malformed origins.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-346: Origin Validation Error
|
||||
- CWE-400: Uncontrolled Resource Consumption
|
||||
- OWASP ASVS 14.4: HTTP security configuration
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
The packaged Wails WebView should be manually tested to confirm its runtime Origin is covered by the `wails://` allow rule.
|
||||
|
||||
### Finding ID: SEC-20260616-1702-002
|
||||
|
||||
#### Title
|
||||
|
||||
SFTP upload name `..` escaped selected remote directory
|
||||
|
||||
#### Severity
|
||||
|
||||
Medium
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `internal/api/api.go`
|
||||
- `internal/api/api_test.go`
|
||||
- `SFTPUploadData`
|
||||
- `SFTPUploadStart`
|
||||
|
||||
#### Description
|
||||
|
||||
`safeSFTPUploadName` normalized slash variants and used `path.Base`, but did not reject the special basename `..`. `path.Join(remoteDir, "..")` resolves to the parent directory, so a Wails caller could escape the selected upload directory.
|
||||
|
||||
#### Evidence
|
||||
|
||||
The previous rejection covered empty, `.`, `/`, and NUL, but not `..`. The upload methods then used `path.Join(remoteDir, safeName)`.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A malicious renderer call invokes chunked upload with `remoteDir="/home/user/upload"` and `fileName=".."`. The destination path resolves to `/home/user`, outside the selected directory.
|
||||
|
||||
#### Impact
|
||||
|
||||
Unexpected remote writes/truncation attempts outside the user's selected SFTP directory, depending on server permissions and target type.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Reject `..` after basename normalization.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented `safeName == ".."` rejection.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added `TestSafeSFTPUploadNameRejectsParentDirectory`.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-22: Path Traversal
|
||||
- OWASP ASVS 12.3: File path control
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
The browser `File.name` API normally does not produce `..`, but Wails API methods are still a trust boundary and should validate independently.
|
||||
|
||||
### Finding ID: SEC-20260616-1702-003
|
||||
|
||||
#### Title
|
||||
|
||||
SSH config import lacked total file and Host-block bounds
|
||||
|
||||
#### Severity
|
||||
|
||||
Low
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `internal/sshconfig/sshconfig.go`
|
||||
- `internal/sshconfig/sshconfig_test.go`
|
||||
- `ImportSSHConfig`
|
||||
|
||||
#### Description
|
||||
|
||||
The OpenSSH config parser scanned files line-by-line, but it did not cap total file size or the number of accumulated Host blocks. A very large selected config could allocate a large slice of parsed blocks and profiles.
|
||||
|
||||
#### Evidence
|
||||
|
||||
`ParseFile` opened the file and appended Host blocks to an in-memory slice until EOF.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A user imports a hostile or accidentally huge SSH config containing thousands of Host blocks. The app spends unnecessary CPU and memory parsing and converting entries.
|
||||
|
||||
#### Impact
|
||||
|
||||
Local denial of service or UI unresponsiveness during import.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Reject oversized config files, set a scanner line cap, and reject excessive Host-block counts.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented `maxConfigFileBytes`, `maxConfigLineBytes`, and `maxHostBlocks`.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added oversized-file and excessive-Host-block tests.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-400: Uncontrolled Resource Consumption
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
The selected caps are conservative for normal OpenSSH config files. Extremely large enterprise configs may need batch import support later.
|
||||
|
||||
### Finding ID: SEC-20260616-1702-004
|
||||
|
||||
#### Title
|
||||
|
||||
SSH key generation allowed expensive caller-controlled options without timeout
|
||||
|
||||
#### Severity
|
||||
|
||||
Low
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `internal/api/api.go`
|
||||
- `internal/api/api_test.go`
|
||||
- `GenerateSSHKey`
|
||||
|
||||
#### Description
|
||||
|
||||
The frontend exposes fixed key-type and bit-size choices, but the backend method accepted caller-supplied values directly and ran `ssh-keygen` without a context timeout. A malformed renderer call could request unsupported types or excessive RSA bit sizes, tying up the subprocess.
|
||||
|
||||
#### Evidence
|
||||
|
||||
`GenerateSSHKey` passed `keyType` to `ssh-keygen -t` and only checked `bits > 0` for RSA before adding `-b`.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A malicious renderer call requests a very large RSA key size. `ssh-keygen` consumes CPU for an extended period or fails slowly.
|
||||
|
||||
#### Impact
|
||||
|
||||
Local CPU denial of service and poor recovery if the subprocess hangs.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Validate allowed key types and RSA sizes server-side, and execute `ssh-keygen` with a timeout.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented `validateSSHKeyGenerationOptions` and `exec.CommandContext` with a 30 second timeout.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added validation tests for defaults, RSA defaults, oversized RSA sizes, and unsupported key types.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-400: Uncontrolled Resource Consumption
|
||||
- CWE-20: Improper Input Validation
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
The timeout is a safety net, not a substitute for platform-level process controls. Real key generation should still be manually tested on slower hardware.
|
||||
|
||||
### Finding ID: SEC-20260616-1702-005
|
||||
|
||||
#### Title
|
||||
|
||||
GitHub repo/ref path interpolation and uncapped archive stream
|
||||
|
||||
#### Severity
|
||||
|
||||
Medium
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `internal/githubclient/githubclient.go`
|
||||
- `internal/githubclient/githubclient_test.go`
|
||||
- `FetchLatestCommit`
|
||||
- `DownloadRepoArchive`
|
||||
|
||||
#### Description
|
||||
|
||||
Repository full names and refs were interpolated into REST API paths without escaping. The archive download also streamed response bodies to disk without an explicit maximum. A malformed renderer call, unusual branch name, or compromised GitHub Enterprise endpoint could create surprising request paths or consume disk.
|
||||
|
||||
#### Evidence
|
||||
|
||||
The client built paths with `fmt.Sprintf("%s/repos/%s/commits/%s", ...)` and copied archives with `io.Copy(file, resp.Body)`.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A renderer calls archive download with a malformed repo full name containing extra path segments, or a malicious GitHub Enterprise endpoint returns an unbounded archive response.
|
||||
|
||||
#### Impact
|
||||
|
||||
Potential confused API requests using the user's GitHub token and local disk exhaustion from unbounded archive streams.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Require `owner/repo` format, URL-escape each API path segment, and cap archive streams.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented `splitRepoFullName`, `endpointURL`, `copyLimitedArchive`, and a 2 GiB archive cap.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added tests for escaped refs, malformed repo names, archive limit rejection, and at-limit copies.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-20: Improper Input Validation
|
||||
- CWE-22: Path Traversal style path confusion
|
||||
- CWE-400: Uncontrolled Resource Consumption
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
The 2 GiB archive cap may reject unusually large repositories. A future preferences setting could make this user-configurable.
|
||||
|
||||
### Finding ID: SEC-20260616-1702-006
|
||||
|
||||
#### Title
|
||||
|
||||
SSH key manager rendered key names/errors through dynamic `innerHTML`
|
||||
|
||||
#### Severity
|
||||
|
||||
Medium
|
||||
|
||||
#### Confidence
|
||||
|
||||
High
|
||||
|
||||
#### Affected Files / Components
|
||||
|
||||
- `frontend/src/js/sshkeys.js`
|
||||
- `frontend/scripts/test-regressions.js`
|
||||
- SSH key manager modal
|
||||
|
||||
#### Description
|
||||
|
||||
The SSH key manager interpolated backend error text and confirmation title/message/button text into `innerHTML`. Key names are derived from local `~/.ssh/*.pub` filenames, so a malicious local filename could inject HTML into the delete confirmation modal.
|
||||
|
||||
#### Evidence
|
||||
|
||||
The previous code used `list.innerHTML = `<div ...>${err}</div>`` and built confirmation modal HTML with `${title}`, `${message}`, and `${confirmLabel}`.
|
||||
|
||||
#### Attack Scenario
|
||||
|
||||
A local attacker creates an SSH public key file with an HTML-like filename. When the user opens the key manager and deletes it, the filename is interpolated into modal HTML.
|
||||
|
||||
#### Impact
|
||||
|
||||
DOM XSS in the Wails renderer, with possible access to app UI actions exposed to the renderer.
|
||||
|
||||
#### Recommendation
|
||||
|
||||
Render dynamic strings with `textContent` or DOM node construction.
|
||||
|
||||
#### Safer Example
|
||||
|
||||
Implemented text-node rendering for key load errors and confirmation modal dynamic text.
|
||||
|
||||
#### Suggested Tests
|
||||
|
||||
Added frontend regression checks to prevent the vulnerable interpolation pattern from returning.
|
||||
|
||||
#### References
|
||||
|
||||
- CWE-79: Cross-Site Scripting
|
||||
- OWASP ASVS 5.3: Output encoding
|
||||
|
||||
#### Assumptions / Limitations
|
||||
|
||||
Other static-template `innerHTML` use remains in the frontend and should continue to be reviewed when it accepts dynamic values.
|
||||
|
||||
## 8. Blackhat-Style Abuse Paths
|
||||
|
||||
Path 1: Token leak to VNC abuse
|
||||
|
||||
- Prerequisite: an active VNC proxy URL leaks to a non-app webpage or injected script.
|
||||
- Old path: any Origin could connect and send arbitrary WebSocket frames to the VNC TCP bridge.
|
||||
- Breakpoint added: Wails/loopback Origin allowlist plus message cap.
|
||||
|
||||
Path 2: Renderer-to-remote path escape
|
||||
|
||||
- Prerequisite: malicious renderer code or direct Wails call.
|
||||
- Old path: call SFTP upload with filename `..`, causing `path.Join(remoteDir, "..")`.
|
||||
- Breakpoint added: `..` is rejected after basename normalization.
|
||||
|
||||
Path 3: Local filename to renderer script injection
|
||||
|
||||
- Prerequisite: crafted key filename in `~/.ssh`.
|
||||
- Old path: key name appears in confirmation modal HTML.
|
||||
- Breakpoint added: key names and errors use `textContent`.
|
||||
|
||||
Path 4: Malicious GitHub Enterprise response to disk pressure
|
||||
|
||||
- Prerequisite: user connects to compromised or malicious API base URL allowed by profile validation.
|
||||
- Old path: archive stream was copied until EOF.
|
||||
- Breakpoint added: Content-Length precheck and streaming cap.
|
||||
|
||||
## 9. Denial-of-Service Review
|
||||
|
||||
Fixed resource-control issues:
|
||||
|
||||
- VNC inbound WebSocket message cap.
|
||||
- SSH config file size, line size, and Host-block caps.
|
||||
- SSH key generation input validation and subprocess timeout.
|
||||
- GitHub archive stream cap.
|
||||
|
||||
Previously fixed and rechecked from recent audit context:
|
||||
|
||||
- GitHub/update JSON response caps.
|
||||
- Leviathan bounded reads and chunked save/export paths.
|
||||
- SFTP inline/chunk upload caps.
|
||||
- Secret vault and SSH key file read caps.
|
||||
|
||||
Residual DoS considerations:
|
||||
|
||||
- SFTP directory listings depend on remote server behavior and can still return large lists.
|
||||
- GitHub repository enrichment intentionally caps total repositories but still performs concurrent commit lookups.
|
||||
- Very large legitimate GitHub archives above 2 GiB now fail fast.
|
||||
|
||||
## 10. Dependency and Supply-Chain Review
|
||||
|
||||
Results:
|
||||
|
||||
- `npm --prefix frontend audit --omit=dev`: 0 vulnerabilities.
|
||||
- `govulncheck ./...`: no vulnerabilities found.
|
||||
|
||||
Reviewed manifests:
|
||||
|
||||
- `go.mod`
|
||||
- `go.sum`
|
||||
- `frontend/package.json`
|
||||
- `frontend/package-lock.json`
|
||||
- `.github/workflows/release-builds.yml`
|
||||
|
||||
No high-confidence dependency findings were found in this pass.
|
||||
|
||||
## 11. Secrets and Sensitive Data Review
|
||||
|
||||
Checked:
|
||||
|
||||
- No obvious private keys, GitHub tokens, cloud keys, or hardcoded credentials were found in source outside documentation/examples.
|
||||
- Non-secret profile export redaction was already covered by tests.
|
||||
- Secret access logging records secret type, not value.
|
||||
- GitHub Authorization headers are set only in HTTP requests and not logged by this code.
|
||||
|
||||
Residual:
|
||||
|
||||
- Plain exports without secrets are safer, but encrypted export remains the recommended path for portable backups.
|
||||
- Local audit logs should continue to avoid host/user secrets in future features.
|
||||
|
||||
## 12. Authentication and Authorisation Review
|
||||
|
||||
This is a local desktop application, so there are no server-side user roles or tenant boundaries. Relevant controls reviewed:
|
||||
|
||||
- SSH host-key callback requirement for VNC SSH tunnels.
|
||||
- Known-host storage and verification paths.
|
||||
- Secret retrieval via keychain/vault and prompt callbacks.
|
||||
- GitHub token validation before repo fetch.
|
||||
|
||||
No missing multi-user authorization checks apply to the current architecture.
|
||||
|
||||
## 13. Input Validation and Output Encoding Review
|
||||
|
||||
Fixed:
|
||||
|
||||
- SFTP upload basename `..`.
|
||||
- SSH key generation key type and RSA bit sizes.
|
||||
- GitHub repo full-name format and path segment escaping.
|
||||
- SSH key manager dynamic output encoding.
|
||||
|
||||
Previously present controls:
|
||||
|
||||
- Profile validation rejects invalid hosts, ports, secret modes, GitHub HTTP non-loopback base URLs, and malformed protocol configs.
|
||||
- Import profiles are size-capped and validated before persistence.
|
||||
|
||||
## 14. Frontend HTML/JavaScript Robustness Review
|
||||
|
||||
Fixed:
|
||||
|
||||
- SSH key manager load errors now render via `textContent`.
|
||||
- SSH key deletion confirmation modal dynamic strings now render via DOM nodes/text.
|
||||
- Regression script now checks these patterns.
|
||||
|
||||
Checked:
|
||||
|
||||
- Wails service bridge ordering remains covered by regression checks.
|
||||
- SFTP drag/drop upload still uses chunked methods.
|
||||
- Direct VNC warning flow remains covered by regression checks.
|
||||
|
||||
Residual:
|
||||
|
||||
- Frontend still contains many static `innerHTML` templates. Future reviews should focus on any template that accepts local filesystem, remote host, profile, update, or GitHub data.
|
||||
|
||||
## 15. Infrastructure and Deployment Review
|
||||
|
||||
Reviewed:
|
||||
|
||||
- GitHub Actions release workflow.
|
||||
- Wails build config.
|
||||
- Frontend build scripts.
|
||||
|
||||
No new high-confidence release workflow finding was fixed. The workflow uses pinned major versions for common actions and default GitHub token permissions scoped to release attachment needs.
|
||||
|
||||
Residual:
|
||||
|
||||
- Consider adding checksums/SBOM generation for release artifacts.
|
||||
- Consider a CI job for `go test ./...`, frontend regression tests, `npm audit --omit=dev`, and `govulncheck`.
|
||||
|
||||
## 16. Logging, Monitoring, and Error Handling Review
|
||||
|
||||
Fixed:
|
||||
|
||||
- SSH key manager no longer injects raw error strings into HTML.
|
||||
- GitHub malformed repo names now fail before request construction.
|
||||
- SSH keygen timeout returns a specific timeout error.
|
||||
|
||||
Checked:
|
||||
|
||||
- Error messages added in this pass do not include tokens, passwords, or key material.
|
||||
- Existing audit logger records profile/session actions and secret access metadata.
|
||||
|
||||
## 17. Test Coverage and Security Regression Gaps
|
||||
|
||||
Added:
|
||||
|
||||
- VNC Origin allowlist tests.
|
||||
- SFTP parent-directory upload name tests.
|
||||
- SSH key generation option validation tests.
|
||||
- SSH config oversized file and Host-block cap tests.
|
||||
- GitHub URL escaping, malformed full-name, and archive cap tests.
|
||||
- Frontend static regression checks for SSH key manager safe rendering.
|
||||
|
||||
Remaining gaps:
|
||||
|
||||
- No packaged Wails/noVNC integration test for Origin behavior.
|
||||
- No E2E browser test for SSH key modal rendering with hostile filenames.
|
||||
- No integration test for GitHub archive cap against an HTTP test server.
|
||||
|
||||
## 18. Prioritised Remediation Plan
|
||||
|
||||
Immediate:
|
||||
|
||||
- Manually test VNC connections in a packaged Wails app to verify the Origin allowlist.
|
||||
- Keep the new security tests in CI.
|
||||
|
||||
Short-term:
|
||||
|
||||
- Add an E2E test for SSH key manager hostile filenames.
|
||||
- Add an HTTP integration test for GitHub archive caps and escaped refs.
|
||||
- Surface user-friendly errors for new caps in the UI.
|
||||
|
||||
Medium-term:
|
||||
|
||||
- Add CI security checks for `govulncheck`, `npm audit --omit=dev`, and `git diff --check`.
|
||||
- Add release artifact checksums and an SBOM.
|
||||
|
||||
Long-term:
|
||||
|
||||
- Continue replacing dynamic frontend `innerHTML` where data provenance is mixed.
|
||||
- Add configurable large-download limits for GitHub archives and SFTP operations.
|
||||
|
||||
## 19. False Positives / Needs Manual Verification
|
||||
|
||||
- VNC Origin policy should be validated in macOS, Windows, and Linux packaged Wails builds.
|
||||
- The 2 GiB GitHub archive cap should be validated against expected user repository sizes.
|
||||
- The SSH keygen 30 second timeout should be checked on slow hardware, especially for RSA 4096.
|
||||
|
||||
## 20. Final Notes
|
||||
|
||||
This pass focused on concrete, testable hardening rather than broad speculative rewrites. The remaining risk is mostly runtime validation and UX around newly explicit limits. The repo still has an unrelated sidebar CSS spacing change in the working tree that was not part of this security audit.
|
||||
@@ -324,6 +324,21 @@ assertContains(
|
||||
"window.go?.api?.Service",
|
||||
"Wails service bridge must use the normal named Wails API",
|
||||
);
|
||||
assertContains(
|
||||
"frontend/src/js/sshkeys.js",
|
||||
"textContent: \"Failed to load keys: \" + String(err)",
|
||||
"SSH key manager errors must be rendered as text rather than injected HTML",
|
||||
);
|
||||
assertContains(
|
||||
"frontend/src/js/sshkeys.js",
|
||||
"textContent: message",
|
||||
"SSH key delete confirmation messages must be rendered as text",
|
||||
);
|
||||
assertNotContains(
|
||||
"frontend/src/js/sshkeys.js",
|
||||
"Failed to load keys: ${err}",
|
||||
"SSH key manager must not interpolate backend errors into innerHTML",
|
||||
);
|
||||
assertContains(
|
||||
"frontend/package.json",
|
||||
'"@xterm/xterm":',
|
||||
|
||||
+41
-14
@@ -92,7 +92,12 @@
|
||||
list.appendChild(this._renderKeyRow(key));
|
||||
}
|
||||
} catch (err) {
|
||||
list.innerHTML = `<div class="sshkey-error">Failed to load keys: ${err}</div>`;
|
||||
list.innerHTML = "";
|
||||
list.appendChild(
|
||||
createElement("div", "sshkey-error", {
|
||||
textContent: "Failed to load keys: " + String(err),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,19 +268,41 @@
|
||||
return new Promise((resolve) => {
|
||||
const backdrop = createElement("div", "modal-backdrop");
|
||||
const modal = createElement("div", "modal modal-sm");
|
||||
modal.innerHTML = `
|
||||
<div class="modal-header">
|
||||
<h3 class="modal-title">${title}</h3>
|
||||
<button class="btn btn-icon btn-xs modal-close">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p style="font-size:var(--text-sm);color:var(--text-secondary)">${message}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-sm confirm-cancel">Cancel</button>
|
||||
<button class="btn btn-sm btn-danger confirm-ok">${confirmLabel}</button>
|
||||
</div>
|
||||
`;
|
||||
const header = createElement("div", "modal-header");
|
||||
header.appendChild(
|
||||
createElement("h3", "modal-title", { textContent: title }),
|
||||
);
|
||||
header.appendChild(
|
||||
createElement("button", "btn btn-icon btn-xs modal-close", {
|
||||
textContent: "x",
|
||||
type: "button",
|
||||
"aria-label": "Close",
|
||||
}),
|
||||
);
|
||||
|
||||
const body = createElement("div", "modal-body");
|
||||
const messageEl = createElement("p", "", { textContent: message });
|
||||
messageEl.style.fontSize = "var(--text-sm)";
|
||||
messageEl.style.color = "var(--text-secondary)";
|
||||
body.appendChild(messageEl);
|
||||
|
||||
const footer = createElement("div", "modal-footer");
|
||||
footer.appendChild(
|
||||
createElement("button", "btn btn-sm confirm-cancel", {
|
||||
textContent: "Cancel",
|
||||
type: "button",
|
||||
}),
|
||||
);
|
||||
footer.appendChild(
|
||||
createElement("button", "btn btn-sm btn-danger confirm-ok", {
|
||||
textContent: confirmLabel,
|
||||
type: "button",
|
||||
}),
|
||||
);
|
||||
|
||||
modal.appendChild(header);
|
||||
modal.appendChild(body);
|
||||
modal.appendChild(footer);
|
||||
backdrop.appendChild(modal);
|
||||
document.body.appendChild(backdrop);
|
||||
requestAnimationFrame(() => {
|
||||
|
||||
+35
-6
@@ -49,6 +49,7 @@ const (
|
||||
maxSFTPUploadChunkBytes = 1024 * 1024
|
||||
maxStreamingSFTPUploadSize = int64(2 * 1024 * 1024 * 1024)
|
||||
maxSSHPublicKeyBytes = 64 * 1024
|
||||
sshKeygenTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// Service is the main API surface exposed to the frontend via Wails bindings.
|
||||
@@ -1809,6 +1810,10 @@ func (s *Service) GenerateSSHKey(name string, keyType string, bits int, passphra
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyType, bits, err = validateSSHKeyGenerationOptions(keyType, bits)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sshDir := filepath.Dir(keyPath)
|
||||
|
||||
// Ensure .ssh directory exists
|
||||
@@ -1821,10 +1826,6 @@ func (s *Service) GenerateSSHKey(name string, keyType string, bits int, passphra
|
||||
return fmt.Errorf("key %q already exists", name)
|
||||
}
|
||||
|
||||
if keyType == "" {
|
||||
keyType = "ed25519"
|
||||
}
|
||||
|
||||
// Build ssh-keygen arguments
|
||||
args := []string{"-t", keyType, "-f", keyPath, "-C", name + "@nexus-terminal"}
|
||||
if passphrase != "" {
|
||||
@@ -1837,10 +1838,15 @@ func (s *Service) GenerateSSHKey(name string, keyType string, bits int, passphra
|
||||
}
|
||||
|
||||
// #nosec G204 — arguments are sanitised above
|
||||
cmd := exec.Command("ssh-keygen", args...)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), sshKeygenTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "ssh-keygen", args...)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return fmt.Errorf("ssh-keygen timed out after %s", sshKeygenTimeout)
|
||||
}
|
||||
return fmt.Errorf("ssh-keygen failed: %s", stderr.String())
|
||||
}
|
||||
|
||||
@@ -1929,12 +1935,35 @@ func safeSFTPUploadName(fileName string) (string, error) {
|
||||
}
|
||||
name = strings.ReplaceAll(name, "\\", "/")
|
||||
safeName := path.Base(name)
|
||||
if safeName == "" || safeName == "." || safeName == "/" || strings.ContainsRune(safeName, 0) {
|
||||
if safeName == "" || safeName == "." || safeName == ".." || safeName == "/" || strings.ContainsRune(safeName, 0) {
|
||||
return "", fmt.Errorf("invalid file name")
|
||||
}
|
||||
return safeName, nil
|
||||
}
|
||||
|
||||
func validateSSHKeyGenerationOptions(keyType string, bits int) (string, int, error) {
|
||||
keyType = strings.ToLower(strings.TrimSpace(keyType))
|
||||
if keyType == "" {
|
||||
keyType = "ed25519"
|
||||
}
|
||||
switch keyType {
|
||||
case "ed25519", "ecdsa":
|
||||
return keyType, bits, nil
|
||||
case "rsa":
|
||||
if bits == 0 {
|
||||
bits = 4096
|
||||
}
|
||||
switch bits {
|
||||
case 2048, 3072, 4096:
|
||||
return keyType, bits, nil
|
||||
default:
|
||||
return "", 0, fmt.Errorf("unsupported RSA key size %d (use 2048, 3072, or 4096)", bits)
|
||||
}
|
||||
default:
|
||||
return "", 0, fmt.Errorf("unsupported SSH key type %q", keyType)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) lookupSFTPUpload(uploadID string) (*sftpUpload, error) {
|
||||
s.uploadMu.Lock()
|
||||
defer s.uploadMu.Unlock()
|
||||
|
||||
@@ -138,6 +138,44 @@ func TestSafeSFTPUploadNamePreservesHTMLCharacters(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeSFTPUploadNameRejectsParentDirectory(t *testing.T) {
|
||||
for _, name := range []string{"..", "folder/..", `folder\..`} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := safeSFTPUploadName(name); err == nil {
|
||||
t.Fatal("expected parent directory upload name to be rejected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSSHKeyGenerationOptions(t *testing.T) {
|
||||
keyType, bits, err := validateSSHKeyGenerationOptions("", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("default options error = %v", err)
|
||||
}
|
||||
if keyType != "ed25519" {
|
||||
t.Fatalf("default key type = %q, want ed25519", keyType)
|
||||
}
|
||||
if bits != 0 {
|
||||
t.Fatalf("default bits = %d, want 0", bits)
|
||||
}
|
||||
|
||||
keyType, bits, err = validateSSHKeyGenerationOptions("rsa", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("rsa default options error = %v", err)
|
||||
}
|
||||
if keyType != "rsa" || bits != 4096 {
|
||||
t.Fatalf("rsa defaults = %q/%d, want rsa/4096", keyType, bits)
|
||||
}
|
||||
|
||||
if _, _, err := validateSSHKeyGenerationOptions("rsa", 999999); err == nil {
|
||||
t.Fatal("expected oversized RSA key size to be rejected")
|
||||
}
|
||||
if _, _, err := validateSSHKeyGenerationOptions("dsa", 0); err == nil {
|
||||
t.Fatal("expected unsupported key type to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportProfilesNormalizesSparseRAWProfile(t *testing.T) {
|
||||
svc := newTestService(t)
|
||||
data := `[
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
const (
|
||||
maxGitHubJSONBodyBytes = 4 << 20
|
||||
maxGitHubErrorBodyBytes = 64 << 10
|
||||
maxGitHubArchiveBytes = int64(2 << 30)
|
||||
)
|
||||
|
||||
// Client wraps the GitHub REST API for repository listing.
|
||||
@@ -190,9 +192,16 @@ func (c *Client) fetchRepos(ctx context.Context, progress func(done int, total i
|
||||
|
||||
// FetchLatestCommit returns the committer name and commit time for a repo/ref.
|
||||
func (c *Client) FetchLatestCommit(ctx context.Context, fullName string, ref string) (string, string, error) {
|
||||
url := fmt.Sprintf("%s/repos/%s/commits/%s", c.baseURL, fullName, ref)
|
||||
if ref == "" {
|
||||
url = fmt.Sprintf("%s/repos/%s/commits/HEAD", c.baseURL, fullName)
|
||||
ref = "HEAD"
|
||||
}
|
||||
owner, repo, err := splitRepoFullName(fullName)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
url, err := c.endpointURL("repos", owner, repo, "commits", ref)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
@@ -252,12 +261,17 @@ func (c *Client) FetchLatestCommit(ctx context.Context, fullName string, ref str
|
||||
|
||||
// DownloadRepoArchive downloads a repository zip archive to the given path.
|
||||
func (c *Client) DownloadRepoArchive(ctx context.Context, fullName string, ref string, destPath string) error {
|
||||
if fullName == "" {
|
||||
return fmt.Errorf("repository name cannot be empty")
|
||||
owner, repo, err := splitRepoFullName(fullName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
url := fmt.Sprintf("%s/repos/%s/zipball", c.baseURL, fullName)
|
||||
segments := []string{"repos", owner, repo, "zipball"}
|
||||
if ref != "" {
|
||||
url = url + "/" + ref
|
||||
segments = append(segments, ref)
|
||||
}
|
||||
url, err := c.endpointURL(segments...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
@@ -280,6 +294,9 @@ func (c *Client) DownloadRepoArchive(ctx context.Context, fullName string, ref s
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("GitHub API returned HTTP %d: %s", resp.StatusCode, readGitHubErrorBody(resp.Body))
|
||||
}
|
||||
if resp.ContentLength > maxGitHubArchiveBytes {
|
||||
return fmt.Errorf("archive is too large: %d bytes exceeds %d bytes", resp.ContentLength, maxGitHubArchiveBytes)
|
||||
}
|
||||
|
||||
file, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
@@ -287,7 +304,7 @@ func (c *Client) DownloadRepoArchive(ctx context.Context, fullName string, ref s
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if _, err := io.Copy(file, resp.Body); err != nil {
|
||||
if _, err := copyLimitedArchive(file, resp.Body, maxGitHubArchiveBytes); err != nil {
|
||||
return fmt.Errorf("writing archive: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -345,3 +362,47 @@ func readGitHubErrorBody(r io.Reader) string {
|
||||
}
|
||||
return strings.TrimSpace(string(body))
|
||||
}
|
||||
|
||||
func splitRepoFullName(fullName string) (string, string, error) {
|
||||
parts := strings.Split(strings.TrimSpace(fullName), "/")
|
||||
if len(parts) != 2 {
|
||||
return "", "", fmt.Errorf("repository name must be in owner/repo format")
|
||||
}
|
||||
owner := strings.TrimSpace(parts[0])
|
||||
repo := strings.TrimSpace(parts[1])
|
||||
if owner == "" || repo == "" {
|
||||
return "", "", fmt.Errorf("repository name must be in owner/repo format")
|
||||
}
|
||||
return owner, repo, nil
|
||||
}
|
||||
|
||||
func (c *Client) endpointURL(segments ...string) (string, error) {
|
||||
u, err := url.Parse(c.baseURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid GitHub base URL: %w", err)
|
||||
}
|
||||
plainPath := strings.TrimRight(u.Path, "/")
|
||||
escapedPath := strings.TrimRight(u.EscapedPath(), "/")
|
||||
for _, segment := range segments {
|
||||
if segment == "" {
|
||||
return "", fmt.Errorf("empty GitHub API path segment")
|
||||
}
|
||||
plainPath += "/" + segment
|
||||
escapedPath += "/" + url.PathEscape(segment)
|
||||
}
|
||||
u.Path = plainPath
|
||||
u.RawPath = escapedPath
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func copyLimitedArchive(dst io.Writer, src io.Reader, maxBytes int64) (int64, error) {
|
||||
limited := &io.LimitedReader{R: src, N: maxBytes + 1}
|
||||
n, err := io.Copy(dst, limited)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
if n > maxBytes {
|
||||
return n, fmt.Errorf("archive exceeds %d bytes", maxBytes)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package githubclient
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -24,3 +26,50 @@ func TestReadLimitedGitHubBodyAllowsResponseAtLimit(t *testing.T) {
|
||||
t.Fatalf("body = %q, want abc", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEndpointURLEscapesRepoPathSegments(t *testing.T) {
|
||||
client := New("https://ghe.example.com/api/v3", "")
|
||||
|
||||
got, err := client.endpointURL("repos", "owner", "repo", "commits", "feature/a b")
|
||||
if err != nil {
|
||||
t.Fatalf("endpointURL() error = %v", err)
|
||||
}
|
||||
want := "https://ghe.example.com/api/v3/repos/owner/repo/commits/feature%2Fa%20b"
|
||||
if got != want {
|
||||
t.Fatalf("endpointURL() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitRepoFullNameRejectsExtraSegments(t *testing.T) {
|
||||
if _, _, err := splitRepoFullName("owner/repo/../../user"); err == nil {
|
||||
t.Fatal("expected malformed repository name to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyLimitedArchiveRejectsOversizedStream(t *testing.T) {
|
||||
var dst bytes.Buffer
|
||||
n, err := copyLimitedArchive(&dst, strings.NewReader("abcd"), 3)
|
||||
if err == nil {
|
||||
t.Fatal("expected oversized archive stream to be rejected")
|
||||
}
|
||||
if n != 4 {
|
||||
t.Fatalf("copied = %d, want 4", n)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "archive exceeds") {
|
||||
t.Fatalf("error = %q, want archive exceeds", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyLimitedArchiveAllowsStreamAtLimit(t *testing.T) {
|
||||
var dst bytes.Buffer
|
||||
n, err := copyLimitedArchive(&dst, strings.NewReader("abc"), 3)
|
||||
if err != nil {
|
||||
t.Fatalf("copyLimitedArchive() error = %v", err)
|
||||
}
|
||||
if n != 3 {
|
||||
t.Fatalf("copied = %d, want 3", n)
|
||||
}
|
||||
if got, err := io.ReadAll(&dst); err != nil || string(got) != "abc" {
|
||||
t.Fatalf("dst = %q, err = %v; want abc", string(got), err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,16 +22,22 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
maxConfigFileBytes = 5 * 1024 * 1024
|
||||
maxConfigLineBytes = 256 * 1024
|
||||
maxHostBlocks = 5000
|
||||
)
|
||||
|
||||
// HostBlock represents a parsed SSH config Host section.
|
||||
type HostBlock struct {
|
||||
Aliases []string
|
||||
HostName string
|
||||
Port int
|
||||
User string
|
||||
IdentityFile string
|
||||
ProxyJump string
|
||||
ForwardAgent bool
|
||||
Compression bool
|
||||
Aliases []string
|
||||
HostName string
|
||||
Port int
|
||||
User string
|
||||
IdentityFile string
|
||||
ProxyJump string
|
||||
ForwardAgent bool
|
||||
Compression bool
|
||||
}
|
||||
|
||||
// ParseFile reads and parses an OpenSSH config file.
|
||||
@@ -41,11 +47,33 @@ func ParseFile(path string) ([]HostBlock, error) {
|
||||
return nil, fmt.Errorf("sshconfig: failed to open %s: %w", path, err)
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sshconfig: failed to stat %s: %w", path, err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil, fmt.Errorf("sshconfig: %s is a directory", path)
|
||||
}
|
||||
if info.Size() > maxConfigFileBytes {
|
||||
return nil, fmt.Errorf("sshconfig: config file is too large: %d bytes exceeds %d bytes", info.Size(), maxConfigFileBytes)
|
||||
}
|
||||
|
||||
var blocks []HostBlock
|
||||
var current *HostBlock
|
||||
commitCurrent := func() error {
|
||||
if current == nil {
|
||||
return nil
|
||||
}
|
||||
if len(blocks) >= maxHostBlocks {
|
||||
return fmt.Errorf("sshconfig: too many Host blocks (max %d)", maxHostBlocks)
|
||||
}
|
||||
blocks = append(blocks, *current)
|
||||
current = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), maxConfigLineBytes)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
|
||||
@@ -61,8 +89,8 @@ func ParseFile(path string) ([]HostBlock, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
// Commit previous block.
|
||||
if current != nil {
|
||||
blocks = append(blocks, *current)
|
||||
if err := commitCurrent(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aliases := strings.Fields(value)
|
||||
// Skip wildcard-only hosts (e.g. "Host *").
|
||||
@@ -83,8 +111,8 @@ func ParseFile(path string) ([]HostBlock, error) {
|
||||
|
||||
case "match":
|
||||
// Commit previous block and skip Match blocks.
|
||||
if current != nil {
|
||||
blocks = append(blocks, *current)
|
||||
if err := commitCurrent(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current = nil
|
||||
|
||||
@@ -122,8 +150,8 @@ func ParseFile(path string) ([]HostBlock, error) {
|
||||
}
|
||||
|
||||
// Commit final block.
|
||||
if current != nil {
|
||||
blocks = append(blocks, *current)
|
||||
if err := commitCurrent(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
@@ -161,13 +189,13 @@ func ToProfiles(blocks []HostBlock, folder string) []models.Profile {
|
||||
username := b.User
|
||||
|
||||
sshConf := &models.SSHConfig{
|
||||
AuthMethods: []string{"publickey", "password"},
|
||||
SecretMode: models.SecretModeAskEveryTime,
|
||||
HostKeyPolicy: models.HostKeyAsk,
|
||||
TerminalType: "xterm-256color",
|
||||
AgentAuth: b.ForwardAgent,
|
||||
AuthMethods: []string{"publickey", "password"},
|
||||
SecretMode: models.SecretModeAskEveryTime,
|
||||
HostKeyPolicy: models.HostKeyAsk,
|
||||
TerminalType: "xterm-256color",
|
||||
AgentAuth: b.ForwardAgent,
|
||||
AgentForwarding: b.ForwardAgent,
|
||||
Compression: b.Compression,
|
||||
Compression: b.Compression,
|
||||
}
|
||||
|
||||
if b.IdentityFile != "" {
|
||||
|
||||
@@ -3,6 +3,8 @@ package sshconfig
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -89,6 +91,50 @@ func TestParseFile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFileRejectsOversizedFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Truncate(maxConfigFileBytes + 1); err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = ParseFile(path)
|
||||
if err == nil {
|
||||
t.Fatal("expected oversized config file to be rejected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "too large") {
|
||||
t.Fatalf("error = %q, want too large", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFileRejectsTooManyHostBlocks(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config")
|
||||
var b strings.Builder
|
||||
for i := 0; i < maxHostBlocks+1; i++ {
|
||||
b.WriteString("Host host")
|
||||
b.WriteString(strconv.Itoa(i))
|
||||
b.WriteString("\n HostName example.com\n")
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(b.String()), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := ParseFile(path)
|
||||
if err == nil {
|
||||
t.Fatal("expected excessive Host blocks to be rejected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "too many Host blocks") {
|
||||
t.Fatalf("error = %q, want too many Host blocks", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestToProfiles(t *testing.T) {
|
||||
blocks := []HostBlock{
|
||||
{
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -53,11 +55,13 @@ type Config struct {
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
CheckOrigin: allowProxyOrigin,
|
||||
ReadBufferSize: 65536,
|
||||
WriteBufferSize: 65536,
|
||||
}
|
||||
|
||||
const maxWebSocketMessageBytes = 8 << 20
|
||||
|
||||
// NewClient creates a new VNC proxy client.
|
||||
func NewClient(cfg Config) *Client {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -186,6 +190,7 @@ func (c *Client) startProxy(vncConn net.Conn) (string, error) {
|
||||
return
|
||||
}
|
||||
defer ws.Close()
|
||||
ws.SetReadLimit(maxWebSocketMessageBytes)
|
||||
|
||||
// Bridge WebSocket ↔ VNC TCP in both directions
|
||||
done := make(chan struct{}, 2)
|
||||
@@ -252,6 +257,34 @@ func (c *Client) startProxy(vncConn net.Conn) (string, error) {
|
||||
return wsURL, nil
|
||||
}
|
||||
|
||||
func allowProxyOrigin(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(u.Scheme) {
|
||||
case "wails":
|
||||
return true
|
||||
case "http", "https":
|
||||
return isLoopbackHost(u.Hostname())
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isLoopbackHost(host string) bool {
|
||||
h := strings.ToLower(strings.TrimSpace(host))
|
||||
if h == "localhost" {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(h)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
func newProxyToken() (string, error) {
|
||||
token := make([]byte, 16)
|
||||
if _, err := rand.Read(token); err != nil {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package vncclient
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewProxyTokenIsRandomHex(t *testing.T) {
|
||||
first, err := newProxyToken()
|
||||
@@ -24,3 +27,35 @@ func TestNewProxyTokenIsRandomHex(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowProxyOrigin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
origin string
|
||||
want bool
|
||||
}{
|
||||
{name: "missing origin", origin: "", want: true},
|
||||
{name: "wails origin", origin: "wails://wails", want: true},
|
||||
{name: "localhost http", origin: "http://localhost:34115", want: true},
|
||||
{name: "loopback ipv4", origin: "http://127.0.0.1:34115", want: true},
|
||||
{name: "loopback ipv6", origin: "http://[::1]:34115", want: true},
|
||||
{name: "remote http", origin: "http://example.com", want: false},
|
||||
{name: "lookalike host", origin: "http://127.0.0.1.example.com", want: false},
|
||||
{name: "bad origin", origin: "://bad", want: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1/ws", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tt.origin != "" {
|
||||
req.Header.Set("Origin", tt.origin)
|
||||
}
|
||||
if got := allowProxyOrigin(req); got != tt.want {
|
||||
t.Fatalf("allowProxyOrigin(%q) = %v, want %v", tt.origin, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user