mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-01 12:34:06 +01:00
Yaak Proxy: record why HTTPS is encrypted, refused handshakes, and reconnect on request (#835)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
69b7c9921c
commit
f02dce21e7
33 files changed
+2696
-214
No files matched your search
Generated
+2
@@ -11948,12 +11948,14 @@ dependencies = [
|
||||
"r2d2_sqlite",
|
||||
"reqwest",
|
||||
"rusqlite",
|
||||
"rustls",
|
||||
"sea-query",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"system-configuration",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tonic",
|
||||
"tonic-reflection",
|
||||
"ts-rs",
|
||||
|
||||
@@ -56,13 +56,12 @@ export function FirstRun() {
|
||||
? "done"
|
||||
: systemSwitch.failed
|
||||
? "fail"
|
||||
: trusted
|
||||
? "next"
|
||||
: "todo";
|
||||
: "next";
|
||||
const decrypt = decryptStep(decryptList, trusted);
|
||||
const everything = decrypt.choice === "everything";
|
||||
const setEverything = (on: boolean) => saveDecryptList.mutate(everythingEdit(on));
|
||||
const ready = trusted && (systemOn || !systemSupported);
|
||||
// The certificate is optional here: nothing needs it until something is decrypted.
|
||||
const ready = systemOn || !systemSupported;
|
||||
const encrypting = !running && !otherOwner ? encryptingPercent(proxyState) : null;
|
||||
const trafficState: StepState =
|
||||
encrypting != null ? "wait" : !running && !otherOwner ? "fail" : ready ? "wait" : "todo";
|
||||
|
||||
@@ -190,10 +190,9 @@ export function ProxyLayout() {
|
||||
function FlowsOrFirstRun({ flowLayout }: { flowLayout: SplitLayoutLayout }) {
|
||||
const locked = useAtomValue(lockedAtom);
|
||||
const noFlows = useAtomValue(noFlowsAtom) || locked != null;
|
||||
const { caStatus, systemProxy } = useProxySetup();
|
||||
const { systemProxy } = useProxySetup();
|
||||
const systemProxyEverOn = useAtomValue(systemProxyEverOnAtom);
|
||||
const incomplete = setupIncomplete({
|
||||
trusted: caStatus.data?.trusted ?? null,
|
||||
systemProxySupported: systemProxy.data?.supported ?? null,
|
||||
systemProxyEverOn,
|
||||
});
|
||||
|
||||
@@ -52,6 +52,12 @@ const base: Flow = {
|
||||
grpcMessage: null,
|
||||
graphqlOperation: null,
|
||||
tunnelled: false,
|
||||
tunnelReason: null,
|
||||
tunnelExcludedBy: null,
|
||||
tunnelExcludedBuiltIn: false,
|
||||
tunnelRejectedBy: null,
|
||||
reconnectRequested: false,
|
||||
tlsRejected: null,
|
||||
agentRead: false,
|
||||
clientAddr: "127.0.0.1:54321",
|
||||
elapsedConnectMs: 18,
|
||||
@@ -209,6 +215,7 @@ export const fixtures: FlowFixture[] = [
|
||||
requestSize: 3_412,
|
||||
responseSize: 48_210,
|
||||
tunnelled: true,
|
||||
tunnelReason: "not_listed",
|
||||
},
|
||||
requestBody: body(""),
|
||||
responseBody: body(""),
|
||||
|
||||
@@ -51,6 +51,12 @@ const flowBase: Flow = {
|
||||
grpcMessage: null,
|
||||
graphqlOperation: null,
|
||||
tunnelled: false,
|
||||
tunnelReason: null,
|
||||
tunnelExcludedBy: null,
|
||||
tunnelExcludedBuiltIn: false,
|
||||
tunnelRejectedBy: null,
|
||||
reconnectRequested: false,
|
||||
tlsRejected: null,
|
||||
agentRead: false,
|
||||
clientAddr: null,
|
||||
elapsedConnectMs: null,
|
||||
|
||||
@@ -2,11 +2,7 @@ import { describe, expect, test } from "vite-plus/test";
|
||||
import { decryptStep, setupIncomplete } from "./firstRun";
|
||||
|
||||
describe("setupIncomplete", () => {
|
||||
const done = { trusted: true, systemProxySupported: true, systemProxyEverOn: true };
|
||||
|
||||
test("is incomplete while the certificate is untrusted", () => {
|
||||
expect(setupIncomplete({ ...done, trusted: false })).toBe(true);
|
||||
});
|
||||
const done = { systemProxySupported: true, systemProxyEverOn: true };
|
||||
|
||||
test("is incomplete until the system proxy has been on once", () => {
|
||||
expect(setupIncomplete({ ...done, systemProxyEverOn: false })).toBe(true);
|
||||
@@ -17,12 +13,12 @@ describe("setupIncomplete", () => {
|
||||
expect(
|
||||
setupIncomplete({ ...done, systemProxySupported: false, systemProxyEverOn: false }),
|
||||
).toBe(false);
|
||||
expect(setupIncomplete({ ...done, systemProxySupported: false, trusted: false })).toBe(true);
|
||||
});
|
||||
|
||||
test("waits for both to be read, so the card does not flash", () => {
|
||||
expect(setupIncomplete({ ...done, trusted: null })).toBe(false);
|
||||
expect(setupIncomplete({ ...done, systemProxySupported: null, trusted: false })).toBe(false);
|
||||
test("waits for the system proxy to be read, so the card does not flash", () => {
|
||||
expect(setupIncomplete({ ...done, systemProxySupported: null, systemProxyEverOn: false })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ import { decryptsEverything } from "./decrypt";
|
||||
|
||||
/** What decides whether setup is done, as the app last read it */
|
||||
export interface SetupState {
|
||||
/** The certificate is trusted, or null until read */
|
||||
trusted: boolean | null;
|
||||
/** The system proxy can be set on this platform, or null until read */
|
||||
systemProxySupported: boolean | null;
|
||||
/** The system proxy has been on at some point since this install */
|
||||
@@ -12,14 +10,14 @@ export interface SetupState {
|
||||
}
|
||||
|
||||
/**
|
||||
* The first-run card shows while setup is incomplete: the certificate untrusted, or the system
|
||||
* proxy never on since this install, where there is one. Not while either is still being read,
|
||||
* so the card does not flash. Once setup is done an empty list is the "no flows yet" state,
|
||||
* after a Clear too.
|
||||
* The first-run card shows while setup is incomplete: the system proxy never on since this
|
||||
* install, where there is one. The certificate is not part of it: nothing needs it until
|
||||
* something is decrypted, which asks for it then. Not while the system proxy is still being
|
||||
* read, so the card does not flash. Once setup is done an empty list is the "no flows yet"
|
||||
* state, after a Clear too.
|
||||
*/
|
||||
export function setupIncomplete(s: SetupState): boolean {
|
||||
if (s.trusted == null || s.systemProxySupported == null) return false;
|
||||
if (!s.trusted) return true;
|
||||
if (s.systemProxySupported == null) return false;
|
||||
return s.systemProxySupported && !s.systemProxyEverOn;
|
||||
}
|
||||
|
||||
|
||||
@@ -141,16 +141,20 @@ export function useFlowActions(): (flow: Flow) => DropdownItem[] {
|
||||
}
|
||||
};
|
||||
const noResponse = (flow.error != null || flow.cancelled) && flow.status == null;
|
||||
// A failed TLS handshake, recorded without a request, has nothing to replay.
|
||||
const noRequest = flow.method === "";
|
||||
return [
|
||||
{
|
||||
label: flow.savedRequestId == null ? "Save as Yaak Request" : "Save to Yaak Again",
|
||||
icon: "bookmark",
|
||||
disabled: noRequest,
|
||||
onSelect: () => openSave(flow),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Copy as cURL",
|
||||
icon: "square_terminal",
|
||||
disabled: noRequest,
|
||||
onSelect: async () => {
|
||||
let body: string | null = null;
|
||||
if (flow.requestSize > 0) {
|
||||
|
||||
@@ -60,6 +60,12 @@ const flow: Flow = {
|
||||
grpcMessage: null,
|
||||
graphqlOperation: null,
|
||||
tunnelled: false,
|
||||
tunnelReason: null,
|
||||
tunnelExcludedBy: null,
|
||||
tunnelExcludedBuiltIn: false,
|
||||
tunnelRejectedBy: null,
|
||||
reconnectRequested: false,
|
||||
tlsRejected: null,
|
||||
agentRead: false,
|
||||
clientAddr: null,
|
||||
elapsedConnectMs: null,
|
||||
|
||||
@@ -87,7 +87,9 @@ protoc-bin-vendored = "3"
|
||||
tonic = { version = "0.14.6", default-features = false }
|
||||
tonic-reflection = "0.14.6"
|
||||
reqwest = { workspace = true }
|
||||
rustls = { workspace = true, features = ["ring"] }
|
||||
tempfile = "3"
|
||||
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] }
|
||||
tokio-rustls = "0.26"
|
||||
yaak-crypto = { workspace = true, features = ["test-support"] }
|
||||
yaak-proxy-helper = { workspace = true, features = ["test-support"] }
|
||||
+36
@@ -147,6 +147,37 @@ graphqlOperation: string | null,
|
||||
* the bytes each way, and no headers or bodies. Open until `elapsedMs` or `error` is set.
|
||||
*/
|
||||
tunnelled: boolean,
|
||||
/**
|
||||
* Why a tunnelled flow was not decrypted. None for other flows, and for tunnels recorded
|
||||
* before the reason was.
|
||||
*/
|
||||
tunnelReason: TunnelReason | null,
|
||||
/**
|
||||
* For a tunnel the decrypt list excluded, the exclusion that kept it out, as stored:
|
||||
* `!host:*.apple.com`.
|
||||
*/
|
||||
tunnelExcludedBy: string | null,
|
||||
/**
|
||||
* That exclusion is one of the built-in ones.
|
||||
*/
|
||||
tunnelExcludedBuiltIn: boolean,
|
||||
/**
|
||||
* For a tunnel passed through after a client rejected the proxy's certificate, the id of
|
||||
* the flow of that refused handshake, when it was recorded.
|
||||
*/
|
||||
tunnelRejectedBy: string | null,
|
||||
/**
|
||||
* The proxy closed this tunnel on request, so its client would reconnect.
|
||||
*/
|
||||
reconnectRequested: boolean,
|
||||
/**
|
||||
* A client's refused TLS handshake, recorded as its host and port began to be passed
|
||||
* through: how it refused, its alert (`unknown_ca`, `bad_certificate`,
|
||||
* `certificate_unknown`, ...) or `hang_up`. Such a flow has no method, its URL is
|
||||
* `https://<authority>`, and its error says it rejected the certificate. A handshake that
|
||||
* failed otherwise is recorded the same way with this None and the failure as its error.
|
||||
*/
|
||||
tlsRejected: string | null,
|
||||
/**
|
||||
* An agent read the flow through the control API: its detail, a body or its messages.
|
||||
* Never written by an upsert, which keeps what is stored.
|
||||
@@ -291,3 +322,8 @@ key: string, matches: boolean, };
|
||||
* The streaming protocol a flow carries.
|
||||
*/
|
||||
export type StreamKind = "websocket" | "sse" | "grpc" | "grpc_web";
|
||||
|
||||
/**
|
||||
* Why a tunnel was passed through undecrypted.
|
||||
*/
|
||||
export type TunnelReason = "not_listed" | "excluded" | "rejected";
|
||||
+147
-6
@@ -1,5 +1,5 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { FilterHistoryEntry, Flow, FlowBody, FlowMessage, GrpcSchema, ModelPayload, SavedQuery } from "./gen_models";
|
||||
import type { FilterHistoryEntry, Flow, FlowBody, FlowMessage, GrpcSchema, ModelPayload, SavedQuery, TunnelReason } from "./gen_models";
|
||||
|
||||
export type ActionInvocation = { "scope": "global", action: GlobalAction, };
|
||||
|
||||
@@ -35,6 +35,23 @@ export type CaStatusRequest = Record<string, never>;
|
||||
|
||||
export type CaTrustRequest = Record<string, never>;
|
||||
|
||||
/**
|
||||
* What came of asking to trust the CA, with its status after.
|
||||
*/
|
||||
export type CaTrustResult = {
|
||||
/**
|
||||
* The person cancelled the password prompt, so nothing changed. Not an error.
|
||||
*/
|
||||
cancelled: boolean,
|
||||
/**
|
||||
* macOS trusts this app's CA, so HTTPS flows can be decrypted.
|
||||
*/
|
||||
trusted: boolean,
|
||||
/**
|
||||
* A certificate named "Yaak Proxy CA" is in a keychain: this one, or an older one.
|
||||
*/
|
||||
installed: boolean, certPath: string, };
|
||||
|
||||
export type ClearFilterHistoryRequest = Record<string, never>;
|
||||
|
||||
export type ClearFlowsRequest = Record<string, never>;
|
||||
@@ -60,7 +77,7 @@ path: string,
|
||||
*/
|
||||
cwd: string | null, };
|
||||
|
||||
export type CountSavedQueriesRequest = { hideSystem?: boolean, };
|
||||
export type CountSavedQueriesRequest = { hideSystem?: boolean, hideEncrypted?: boolean, };
|
||||
|
||||
export type CreateSavedQueryRequest = { name: string, query: string, };
|
||||
|
||||
@@ -115,7 +132,22 @@ entry: string,
|
||||
/**
|
||||
* Shipped with the app: an exclusion of Apple's services or a pinned app's hosts.
|
||||
*/
|
||||
builtIn: boolean, };
|
||||
builtIn: boolean,
|
||||
/**
|
||||
* Why a built-in exclusion ships. None for the user's own entries.
|
||||
*/
|
||||
kind?: ExclusionKind, };
|
||||
|
||||
/**
|
||||
* The decrypt list as saved, and what it means for connections already open.
|
||||
*/
|
||||
export type DecryptListSaved = {
|
||||
/**
|
||||
* Open connections the list now decrypts that stay encrypted until their clients
|
||||
* reconnect: `reconnect_tunnels` closes them so they do. Closed by nothing else. Zero from
|
||||
* an owner too old to count them.
|
||||
*/
|
||||
stillEncrypted: number, entries: Array<DecryptListEntry>, };
|
||||
|
||||
export type DeleteFilterHistoryRequest = { filter: string, };
|
||||
|
||||
@@ -131,6 +163,11 @@ export type DroppedHeader = { name: string, value: string, reason: DropReason, }
|
||||
*/
|
||||
export type EditDecryptListRequest = { add: Array<string>, remove: Array<string>, };
|
||||
|
||||
/**
|
||||
* Why a built-in exclusion ships.
|
||||
*/
|
||||
export type ExclusionKind = "apple" | "pinned";
|
||||
|
||||
export type ExportHarRequest = {
|
||||
/**
|
||||
* The file to write.
|
||||
@@ -171,6 +208,11 @@ query?: string,
|
||||
* `@is:system` itself.
|
||||
*/
|
||||
hideSystem?: boolean,
|
||||
/**
|
||||
* Leaves out HTTPS connections passed through undecrypted, as hiding Encrypted does,
|
||||
* unless the query says `@is:encrypted` itself.
|
||||
*/
|
||||
hideEncrypted?: boolean,
|
||||
/**
|
||||
* At most this many flows, the newest.
|
||||
*/
|
||||
@@ -216,6 +258,22 @@ export type FolderSummary = { id: string, name: string,
|
||||
*/
|
||||
folderId: string | null, };
|
||||
|
||||
/**
|
||||
* An address to intercept again: `host`, `host:port` or `[::1]:8443`, as a flow's URL has
|
||||
* it, the port 443 when left out.
|
||||
*/
|
||||
export type ForgetPassthroughRequest = { address: string, };
|
||||
|
||||
export type ForgetPassthroughResponse = {
|
||||
/**
|
||||
* It was passed through.
|
||||
*/
|
||||
forgotten: boolean,
|
||||
/**
|
||||
* The addresses still passed through.
|
||||
*/
|
||||
addresses: Array<string>, };
|
||||
|
||||
export type FormatBodyRequest = { text: string, };
|
||||
|
||||
export type GetDecryptListRequest = Record<string, never>;
|
||||
@@ -391,6 +449,8 @@ messages: Array<FlowMessage>,
|
||||
*/
|
||||
total: number, };
|
||||
|
||||
export type ListPassthroughRequest = Record<string, never>;
|
||||
|
||||
export type ListSavedQueriesRequest = Record<string, never>;
|
||||
|
||||
export type ListSeenRequest = Record<string, never>;
|
||||
@@ -419,6 +479,28 @@ export type OpenTerminalRequest = {
|
||||
*/
|
||||
vars: Array<[string, string]>, };
|
||||
|
||||
/**
|
||||
* An open tunnel, as the app is told of it.
|
||||
*/
|
||||
export type OpenTunnel = {
|
||||
/**
|
||||
* Its id for closing it, unique to this run of the engine, so one listed before the
|
||||
* engine restarted closes nothing after.
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* The host it leads to, without an IPv6 address's brackets.
|
||||
*/
|
||||
host: string, port: number,
|
||||
/**
|
||||
* The app that opened it, when known.
|
||||
*/
|
||||
appName: string | null, appBundleId: string | null,
|
||||
/**
|
||||
* Its flow, when it was recorded.
|
||||
*/
|
||||
flowId: string | null, reason: TunnelReason, };
|
||||
|
||||
export type OtherOwner = { owner: Owner, pid: number, startedAt: string,
|
||||
/**
|
||||
* The engine's port while it runs.
|
||||
@@ -430,6 +512,25 @@ proxyPort: number | null, };
|
||||
*/
|
||||
export type Owner = "app" | "cli";
|
||||
|
||||
/**
|
||||
* The addresses passed through after clients rejected the CA changed: one was added or
|
||||
* forgotten.
|
||||
*/
|
||||
export type PassthroughChangedPayload = {
|
||||
/**
|
||||
* Each `host:port`, an IPv6 host in brackets, sorted.
|
||||
*/
|
||||
addresses: Array<string>, };
|
||||
|
||||
/**
|
||||
* The addresses passed through after clients rejected the CA.
|
||||
*/
|
||||
export type PassthroughResponse = {
|
||||
/**
|
||||
* Each `host:port`, an IPv6 host in brackets, sorted.
|
||||
*/
|
||||
addresses: Array<string>, };
|
||||
|
||||
export type PreviewSaveRequest = { flowId: string, };
|
||||
|
||||
/**
|
||||
@@ -476,6 +577,31 @@ export type QueryValuesRequest = {
|
||||
*/
|
||||
path: string, };
|
||||
|
||||
/**
|
||||
* Tunnels to close: those in `ids`, or, without them, every one `list_reconnectable_tunnels`
|
||||
* returns for the same `entry` and `flowId`.
|
||||
*/
|
||||
export type ReconnectTunnelsRequest = {
|
||||
/**
|
||||
* `OpenTunnel` ids. Ones from an earlier run of the engine close nothing.
|
||||
*/
|
||||
ids?: Array<string>,
|
||||
/**
|
||||
* An entry as stored or typed, `host:www.google.com`, `app:Dia`, `*`: only tunnels it
|
||||
* names. An exclusion, `!host:*.chase.com`, names those it would keep out.
|
||||
*/
|
||||
entry?: string,
|
||||
/**
|
||||
* Only the tunnel this flow records.
|
||||
*/
|
||||
flowId?: string, };
|
||||
|
||||
export type ReconnectTunnelsResponse = {
|
||||
/**
|
||||
* Tunnels closed: those still open of the ones asked for.
|
||||
*/
|
||||
closed: number, };
|
||||
|
||||
/**
|
||||
* A filter applied from the search box, or from the history itself, put at its top.
|
||||
*/
|
||||
@@ -494,9 +620,9 @@ export type RenameSavedQueryRequest = { id: string, name: string, };
|
||||
|
||||
export type ResetCapturedDataRequest = Record<string, never>;
|
||||
|
||||
export type RpcEventSchema = { decrypt_list_changed: DecryptListChangedPayload, filter_history_changed: FilterHistoryChangedPayload, flows_cleared: FlowsClearedPayload, flows_removed: FlowsRemovedPayload, message_write: MessagePayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, saved_queries_changed: SavedQueriesChangedPayload, };
|
||||
export type RpcEventSchema = { decrypt_list_changed: DecryptListChangedPayload, filter_history_changed: FilterHistoryChangedPayload, flows_cleared: FlowsClearedPayload, flows_removed: FlowsRemovedPayload, message_write: MessagePayload, model_write: ModelPayload, passthrough_changed: PassthroughChangedPayload, proxy_state_changed: ProxyStatePayload, saved_queries_changed: SavedQueriesChangedPayload, };
|
||||
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], get_decrypt_list: [GetDecryptListRequest, DecryptList], get_message_payload: [GetMessagePayloadRequest, GetMessagePayloadResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], query_schema: [QuerySchemaRequest, QuerySchemaResponse], validate_query: [ValidateQueryRequest, Array<QueryDiagnostic>], watch_query: [WatchQueryRequest, boolean], list_saved_queries: [ListSavedQueriesRequest, Array<SavedQuery>], create_saved_query: [CreateSavedQueryRequest, SavedQuery], rename_saved_query: [RenameSavedQueryRequest, SavedQuery], delete_saved_query: [DeleteSavedQueryRequest, boolean], list_filter_history: [ListFilterHistoryRequest, Array<FilterHistoryEntry>], record_filter: [RecordFilterRequest, boolean], delete_filter_history: [DeleteFilterHistoryRequest, boolean], clear_filter_history: [ClearFilterHistoryRequest, number], get_last_filter: [GetLastFilterRequest, string], set_last_filter: [SetLastFilterRequest, boolean], get_window_places: [GetWindowPlacesRequest, string | null], set_window_places: [SetWindowPlacesRequest, boolean], list_grpc_schemas: [ListGrpcSchemasRequest, Array<GrpcSchema>], list_messages: [ListMessagesRequest, ListMessagesResponse], remove_grpc_schema: [RemoveGrpcSchemaRequest, boolean], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], set_capture_body_limit: [SetCaptureBodyLimitRequest, number], set_traffic: [SetTrafficRequest, TrafficRetention], set_keep_traffic: [SetKeepTrafficRequest, number | null], add_grpc_schema: [AddGrpcSchemaRequest, GrpcSchema], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], decode_grpc_message: [DecodeGrpcMessageRequest, DecodedGrpcMessage], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], edit_decrypt_list: [EditDecryptListRequest, DecryptList], list_seen: [ListSeenRequest, SeenTargets], set_decrypt_list: [SetDecryptListRequest, DecryptList], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], reflect_grpc_host: [ReflectGrpcHostRequest, GrpcSchema], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], set_port: [SetPortRequest, number], get_storage_size: [GetStorageSizeRequest, GetStorageSizeResponse], reset_captured_data: [ResetCapturedDataRequest, boolean], open_terminal: [OpenTerminalRequest, boolean], query_values: [QueryValuesRequest, Array<string>], match_flows: [MatchFlowsRequest, Array<string>], get_flows: [GetFlowsRequest, Array<Flow>], count_saved_queries: [CountSavedQueriesRequest, Array<SavedQueryCount>], };
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], get_decrypt_list: [GetDecryptListRequest, DecryptList], get_message_payload: [GetMessagePayloadRequest, GetMessagePayloadResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], query_schema: [QuerySchemaRequest, QuerySchemaResponse], validate_query: [ValidateQueryRequest, Array<QueryDiagnostic>], watch_query: [WatchQueryRequest, boolean], list_saved_queries: [ListSavedQueriesRequest, Array<SavedQuery>], create_saved_query: [CreateSavedQueryRequest, SavedQuery], rename_saved_query: [RenameSavedQueryRequest, SavedQuery], delete_saved_query: [DeleteSavedQueryRequest, boolean], list_filter_history: [ListFilterHistoryRequest, Array<FilterHistoryEntry>], record_filter: [RecordFilterRequest, boolean], delete_filter_history: [DeleteFilterHistoryRequest, boolean], clear_filter_history: [ClearFilterHistoryRequest, number], get_last_filter: [GetLastFilterRequest, string], set_last_filter: [SetLastFilterRequest, boolean], get_window_places: [GetWindowPlacesRequest, string | null], set_window_places: [SetWindowPlacesRequest, boolean], list_grpc_schemas: [ListGrpcSchemasRequest, Array<GrpcSchema>], list_messages: [ListMessagesRequest, ListMessagesResponse], remove_grpc_schema: [RemoveGrpcSchemaRequest, boolean], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], set_capture_body_limit: [SetCaptureBodyLimitRequest, number], set_traffic: [SetTrafficRequest, TrafficRetention], set_keep_traffic: [SetKeepTrafficRequest, number | null], add_grpc_schema: [AddGrpcSchemaRequest, GrpcSchema], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaTrustResult], forget_passthrough: [ForgetPassthroughRequest, ForgetPassthroughResponse], list_passthrough: [ListPassthroughRequest, PassthroughResponse], list_reconnectable_tunnels: [TunnelScope, Array<OpenTunnel>], reconnect_tunnels: [ReconnectTunnelsRequest, ReconnectTunnelsResponse], clear_flows: [ClearFlowsRequest, number], decode_grpc_message: [DecodeGrpcMessageRequest, DecodedGrpcMessage], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], edit_decrypt_list: [EditDecryptListRequest, DecryptListSaved], list_seen: [ListSeenRequest, SeenTargets], set_decrypt_list: [SetDecryptListRequest, DecryptListSaved], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], reflect_grpc_host: [ReflectGrpcHostRequest, GrpcSchema], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], set_port: [SetPortRequest, number], get_storage_size: [GetStorageSizeRequest, GetStorageSizeResponse], reset_captured_data: [ResetCapturedDataRequest, boolean], open_terminal: [OpenTerminalRequest, boolean], query_values: [QueryValuesRequest, Array<string>], match_flows: [MatchFlowsRequest, Array<string>], get_flows: [GetFlowsRequest, Array<Flow>], count_saved_queries: [CountSavedQueriesRequest, Array<SavedQueryCount>], };
|
||||
|
||||
export type SaveFlowBodyRequest = { flowId: string, which: FlowBody,
|
||||
/**
|
||||
@@ -672,12 +798,27 @@ export type TakeOverRequest = Record<string, never>;
|
||||
*/
|
||||
export type TrafficRetention = "clearOnLaunch" | "keep";
|
||||
|
||||
/**
|
||||
* Which open tunnels to consider: all of them, those one decrypt-list entry names, or the one
|
||||
* a flow records.
|
||||
*/
|
||||
export type TunnelScope = {
|
||||
/**
|
||||
* An entry as stored or typed, `host:www.google.com`, `app:Dia`, `*`: only tunnels it
|
||||
* names. An exclusion, `!host:*.chase.com`, names those it would keep out.
|
||||
*/
|
||||
entry?: string,
|
||||
/**
|
||||
* Only the tunnel this flow records.
|
||||
*/
|
||||
flowId?: string, };
|
||||
|
||||
export type ValidateQueryRequest = { query: string, };
|
||||
|
||||
/**
|
||||
* The search the app shows, which flows written from now on are matched against, their events
|
||||
* naming `key`. No query stops it.
|
||||
*/
|
||||
export type WatchQueryRequest = { key: string, query?: string, hideSystem?: boolean, };
|
||||
export type WatchQueryRequest = { key: string, query?: string, hideSystem?: boolean, hideEncrypted?: boolean, };
|
||||
|
||||
export type WorkspaceSummary = { id: string, name: string, folders: Array<FolderSummary>, };
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Why an HTTPS connection was passed through undecrypted: `not_listed`, `excluded` (with the
|
||||
-- exclusion that kept it out, and whether that one is built in) or `rejected` (with the flow of
|
||||
-- the refused handshake that started passing its address through, when that was recorded).
|
||||
ALTER TABLE flows ADD COLUMN tunnel_reason TEXT;
|
||||
ALTER TABLE flows ADD COLUMN tunnel_excluded_by TEXT;
|
||||
ALTER TABLE flows ADD COLUMN tunnel_excluded_built_in BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE flows ADD COLUMN tunnel_rejected_by TEXT;
|
||||
|
||||
-- A tunnel the proxy closed on request so its client reconnects.
|
||||
ALTER TABLE flows ADD COLUMN reconnect_requested BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
-- A client's refused TLS handshake with the proxy, recorded once as its address is passed
|
||||
-- through: the client's alert (`unknown_ca`, `bad_certificate`, ...) or `hang_up`.
|
||||
ALTER TABLE flows ADD COLUMN tls_rejected TEXT;
|
||||
@@ -13,6 +13,25 @@ pub struct CaStatus {
|
||||
pub cert_path: String,
|
||||
}
|
||||
|
||||
/// What came of asking to trust the CA, with its status after.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct CaTrustResult {
|
||||
#[serde(flatten)]
|
||||
pub status: CaStatus,
|
||||
/// The person cancelled the password prompt, so nothing changed. Not an error.
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
/// What came of [`trust`] when it did not fail.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Trusted {
|
||||
Yes,
|
||||
/// The person cancelled the password prompt.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
const CA_NAME: &str = "Yaak Proxy CA";
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -30,9 +49,9 @@ pub async fn status(cert_path: &Path) -> Result<CaStatus, String> {
|
||||
}
|
||||
|
||||
/// Adds the CA to the login keychain as a trusted root. macOS asks for the user's password;
|
||||
/// the app never elevates.
|
||||
/// the app never elevates. Cancelling that prompt is not a failure.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn trust(cert_path: &Path) -> Result<(), String> {
|
||||
pub async fn trust(cert_path: &Path) -> Result<Trusted, String> {
|
||||
let home = std::env::var("HOME").map_err(|_| "HOME is not set".to_string())?;
|
||||
let keychain = Path::new(&home).join("Library/Keychains/login.keychain-db");
|
||||
let output = security(&[
|
||||
@@ -45,12 +64,25 @@ pub async fn trust(cert_path: &Path) -> Result<(), String> {
|
||||
])
|
||||
.await?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
return Ok(Trusted::Yes);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if is_cancelled(&stderr) {
|
||||
return Ok(Trusted::Cancelled);
|
||||
}
|
||||
Err(if stderr.is_empty() { format!("security exited with {}", output.status) } else { stderr })
|
||||
}
|
||||
|
||||
/// `security`'s error for a cancelled authorization prompt: "The authorization was canceled by
|
||||
/// the user." (`errAuthorizationCanceled`, -128).
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn is_cancelled(stderr: &str) -> bool {
|
||||
let stderr = stderr.to_lowercase();
|
||||
stderr.contains("canceled by the user")
|
||||
|| stderr.contains("cancelled by the user")
|
||||
|| stderr.contains("errauthorizationcanceled")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn security(args: &[&str]) -> Result<std::process::Output, String> {
|
||||
tokio::process::Command::new(SECURITY)
|
||||
@@ -70,6 +102,20 @@ pub async fn status(cert_path: &Path) -> Result<CaStatus, String> {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub async fn trust(_cert_path: &Path) -> Result<(), String> {
|
||||
pub async fn trust(_cert_path: &Path) -> Result<Trusted, String> {
|
||||
Err("Trusting the certificate from the app is only supported on macOS".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_prompt_is_told_apart() {
|
||||
let cancelled =
|
||||
"SecTrustSettingsSetTrustSettings: The authorization was canceled by the user.";
|
||||
assert!(is_cancelled(cancelled));
|
||||
assert!(!is_cancelled("SecCertificateCreateFromData: Unknown format in import."));
|
||||
assert!(!is_cancelled(""));
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! and `blobs.sqlite` read-only so captured traffic stays reachable.
|
||||
|
||||
use crate::bodies::{self, DecodedBody};
|
||||
use crate::ca::CaStatus;
|
||||
use crate::ca::CaTrustResult;
|
||||
use crate::control::{
|
||||
self, ControlInfo, ControlStatus, DecryptRequest, ErrorBody, NOTE_HEADER, RecordingRequest,
|
||||
StartRequest, SystemProxyRequest, TRUNCATED_HEADER,
|
||||
@@ -16,6 +16,7 @@ use crate::macos::SystemProxyStatus;
|
||||
use crate::models::{Flow, FlowBody};
|
||||
use crate::save::{SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
|
||||
use crate::settings::{DecryptList, ProxySettings};
|
||||
use crate::tunnels::{OpenTunnel, TunnelScope};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::Path;
|
||||
@@ -129,10 +130,49 @@ impl ControlClient {
|
||||
resp.text().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn trust_ca(&self) -> Result<CaStatus, String> {
|
||||
pub async fn trust_ca(&self) -> Result<CaTrustResult, String> {
|
||||
self.post("/ca/trust", &serde_json::json!({})).await
|
||||
}
|
||||
|
||||
/// The addresses the owner's engine passes through after clients rejected the CA.
|
||||
pub async fn passthrough(&self) -> Result<crate::PassthroughResponse, String> {
|
||||
self.get("/passthrough").await
|
||||
}
|
||||
|
||||
/// Has the owner's engine intercept one passed-through address again.
|
||||
pub async fn forget_passthrough(
|
||||
&self,
|
||||
req: &crate::ForgetPassthroughRequest,
|
||||
) -> Result<crate::ForgetPassthroughResponse, String> {
|
||||
self.post("/passthrough/forget", req).await
|
||||
}
|
||||
|
||||
/// The owner's open tunnels its decrypt list would decrypt if their clients reconnected.
|
||||
pub async fn reconnectable_tunnels(
|
||||
&self,
|
||||
scope: &TunnelScope,
|
||||
) -> Result<Vec<OpenTunnel>, String> {
|
||||
let query = {
|
||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||
if let Some(entry) = &scope.entry {
|
||||
query.append_pair("entry", entry);
|
||||
}
|
||||
if let Some(flow_id) = &scope.flow_id {
|
||||
query.append_pair("flowId", flow_id);
|
||||
}
|
||||
query.finish()
|
||||
};
|
||||
self.get(&format!("/tunnels/reconnectable?{query}")).await
|
||||
}
|
||||
|
||||
/// Closes tunnels in the owner's engine so their clients reconnect.
|
||||
pub async fn reconnect_tunnels(
|
||||
&self,
|
||||
req: &crate::ReconnectTunnelsRequest,
|
||||
) -> Result<crate::ReconnectTunnelsResponse, String> {
|
||||
self.post("/tunnels/reconnect", req).await
|
||||
}
|
||||
|
||||
/// Resumes or pauses storing flows in the owner's engine.
|
||||
pub async fn set_recording(&self, enabled: bool) -> Result<ControlStatus, String> {
|
||||
self.post("/recording", &RecordingRequest { enabled }).await
|
||||
@@ -154,7 +194,7 @@ impl ControlClient {
|
||||
pub async fn edit_decrypt_list(
|
||||
&self,
|
||||
edit: &crate::EditDecryptListRequest,
|
||||
) -> Result<DecryptList, String> {
|
||||
) -> Result<crate::DecryptListSaved, String> {
|
||||
let body = serde_json::to_vec(edit).map_err(|e| e.to_string())?;
|
||||
let req = self
|
||||
.http
|
||||
@@ -166,7 +206,10 @@ impl ControlClient {
|
||||
}
|
||||
|
||||
/// Replaces the decrypt list in the owner, which saves it and applies it to its engine.
|
||||
pub async fn set_decrypt_list(&self, entries: &[String]) -> Result<DecryptList, String> {
|
||||
pub async fn set_decrypt_list(
|
||||
&self,
|
||||
entries: &[String],
|
||||
) -> Result<crate::DecryptListSaved, String> {
|
||||
let body = serde_json::to_vec(&DecryptRequest { entries: entries.to_vec() })
|
||||
.map_err(|e| e.to_string())?;
|
||||
let req = self
|
||||
|
||||
@@ -11,8 +11,10 @@ use crate::macos::SystemProxyStatus;
|
||||
use crate::messages::{self, FlowMessage, MessageKind};
|
||||
use crate::models::{FlowBody, find_header};
|
||||
use crate::save::SaveFlowRequest;
|
||||
use crate::tunnels::TunnelScope;
|
||||
use crate::{
|
||||
AddGrpcSchemaRequest, EditDecryptListRequest, ListMessagesResponse, ProxyCtx, ProxyState,
|
||||
AddGrpcSchemaRequest, EditDecryptListRequest, ForgetPassthroughRequest, ListMessagesResponse,
|
||||
PassthroughResponse, ProxyCtx, ProxyState, ReconnectTunnelsRequest, ReconnectTunnelsResponse,
|
||||
ReflectGrpcHostRequest, bodies,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
@@ -626,15 +628,24 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
|
||||
};
|
||||
Ok(response(StatusCode::OK, "application/x-pem-file", ca.pem().to_string()))
|
||||
}
|
||||
(&Method::POST, ["ca", "trust"]) => {
|
||||
// Off the runtime's few workers: it may wait for the keychain or a conversion.
|
||||
let ca = {
|
||||
let ctx = ctx.clone();
|
||||
blocking(move || ctx.load_ca()).await?
|
||||
};
|
||||
ca::trust(ca.cert_path()).await.map_err(bad_request)?;
|
||||
ctx.forget_passthrough();
|
||||
json(&ca::status(ca.cert_path()).await?)
|
||||
(&Method::POST, ["ca", "trust"]) => json(&ctx.trust_ca().await.map_err(bad_request)?),
|
||||
(&Method::GET, ["passthrough"]) => {
|
||||
json(&PassthroughResponse { addresses: ctx.passthrough() })
|
||||
}
|
||||
(&Method::POST, ["passthrough", "forget"]) => {
|
||||
let body: ForgetPassthroughRequest = read_json(req).await?;
|
||||
json(&ctx.forget_passthrough_request(&body).map_err(bad_request)?)
|
||||
}
|
||||
(&Method::GET, ["tunnels", "reconnectable"]) => {
|
||||
let scope = tunnel_scope(&query);
|
||||
let ctx = ctx.clone();
|
||||
json(&blocking(move || ctx.reconnectable_tunnels(&scope)).await.map_err(bad_request)?)
|
||||
}
|
||||
(&Method::POST, ["tunnels", "reconnect"]) => {
|
||||
let body: ReconnectTunnelsRequest = read_json(req).await?;
|
||||
let ctx = ctx.clone();
|
||||
let closed = blocking(move || ctx.reconnect_tunnels(body.ids.as_deref(), &body.scope));
|
||||
json(&ReconnectTunnelsResponse { closed: closed.await.map_err(bad_request)? })
|
||||
}
|
||||
(&Method::GET, ["system-proxy"]) => {
|
||||
let ctx = ctx.clone();
|
||||
@@ -723,6 +734,20 @@ fn message_page(query: &str) -> Result<(Option<i64>, Option<usize>), ApiError> {
|
||||
Ok((after, limit))
|
||||
}
|
||||
|
||||
/// `entry` and `flowId` from a query string.
|
||||
fn tunnel_scope(query: &str) -> TunnelScope {
|
||||
let mut scope = TunnelScope::default();
|
||||
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
|
||||
let value = Some(value.into_owned()).filter(|v| !v.is_empty());
|
||||
match key.as_ref() {
|
||||
"entry" => scope.entry = value,
|
||||
"flowId" => scope.flow_id = value,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
scope
|
||||
}
|
||||
|
||||
fn body_limit(query: &str) -> Result<usize, ApiError> {
|
||||
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
|
||||
if key == "bodyLimit" {
|
||||
|
||||
@@ -618,7 +618,7 @@ mod tests {
|
||||
&applied[6..],
|
||||
[
|
||||
"00000007", "00000008", "00000009", "00000010", "00000011", "00000012", "00000013",
|
||||
"00000014"
|
||||
"00000014", "00000015"
|
||||
]
|
||||
);
|
||||
let mark_columns = columns(&conn, "flow_clear_mark");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::bodies;
|
||||
use crate::db::{ProxyQueryManager, Stores};
|
||||
use crate::models::{Flow, FlowBody};
|
||||
use crate::query::{FlowColumns, FlowQuery};
|
||||
use crate::query::{FlowColumns, FlowQuery, Hidden};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use rusqlite::types::Value;
|
||||
@@ -23,6 +23,10 @@ pub struct FlowFilter {
|
||||
/// `@is:system` itself.
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_system: bool,
|
||||
/// Leaves out HTTPS connections passed through undecrypted, as hiding Encrypted does,
|
||||
/// unless the query says `@is:encrypted` itself.
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_encrypted: bool,
|
||||
/// At most this many flows, the newest.
|
||||
#[ts(optional, type = "number")]
|
||||
pub limit: Option<usize>,
|
||||
@@ -338,7 +342,8 @@ impl FlowFilter {
|
||||
Self { query: Some(query.into()), ..Self::default() }
|
||||
}
|
||||
|
||||
/// The filter from a query string's `query`, `hide_system`, `limit`, `after` and `before`.
|
||||
/// The filter from a query string's `query`, `hide_system`, `hide_encrypted`, `limit`,
|
||||
/// `after` and `before`.
|
||||
pub fn from_query(query: &str) -> Result<Self, String> {
|
||||
let mut filter = Self::default();
|
||||
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
|
||||
@@ -351,6 +356,12 @@ impl FlowFilter {
|
||||
.transpose()?
|
||||
.unwrap_or_default()
|
||||
}
|
||||
"hide_encrypted" => {
|
||||
filter.hide_encrypted = value
|
||||
.map(|v| v.parse().map_err(|_| format!("Invalid hide_encrypted {v:?}")))
|
||||
.transpose()?
|
||||
.unwrap_or_default()
|
||||
}
|
||||
"after" => filter.after = value,
|
||||
"before" => filter.before = value,
|
||||
"limit" => {
|
||||
@@ -368,9 +379,11 @@ impl FlowFilter {
|
||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||
let limit = self.limit.map(|l| l.to_string());
|
||||
let hide_system = self.hide_system.then(|| "true".to_string());
|
||||
let hide_encrypted = self.hide_encrypted.then(|| "true".to_string());
|
||||
for (key, value) in [
|
||||
("query", &self.query),
|
||||
("hide_system", &hide_system),
|
||||
("hide_encrypted", &hide_encrypted),
|
||||
("limit", &limit),
|
||||
("after", &self.after),
|
||||
("before", &self.before),
|
||||
@@ -384,7 +397,12 @@ impl FlowFilter {
|
||||
|
||||
/// The search, prepared to run now.
|
||||
pub fn flow_query(&self) -> FlowQuery {
|
||||
FlowQuery::new(self.query.as_deref().unwrap_or_default(), self.hide_system)
|
||||
FlowQuery::new(self.query.as_deref().unwrap_or_default(), self.hidden())
|
||||
}
|
||||
|
||||
/// What the filter leaves out unless its query names it.
|
||||
pub fn hidden(&self) -> Hidden {
|
||||
Hidden { system: self.hide_system, encrypted: self.hide_encrypted }
|
||||
}
|
||||
|
||||
/// Narrows more than `after`, `before` and `limit` do, so it covers fewer than all flows.
|
||||
@@ -1867,6 +1885,67 @@ mod tests {
|
||||
assert_eq!(hidden("@host:*.github.com OR @is:SYSTEM"), vec!["fl_daemon", "fl_node"]);
|
||||
}
|
||||
|
||||
/// Hiding encrypted connections leaves them out of the list and its count, the totals the
|
||||
/// sidebar reads, and saved searches' counts, unless the search names them.
|
||||
#[test]
|
||||
fn hides_encrypted_connections() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db =
|
||||
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
|
||||
let flow = |id: &str, url: &str, tunnelled: bool, path: Option<&str>| Flow {
|
||||
id: id.into(),
|
||||
url: url.into(),
|
||||
method: if tunnelled { "CONNECT" } else { "GET" }.into(),
|
||||
tunnelled,
|
||||
client_path: path.map(String::from),
|
||||
..Default::default()
|
||||
};
|
||||
for f in [
|
||||
flow("fl_get", "https://api.example.com/v1", false, None),
|
||||
flow("fl_tunnel", "https://bank.example.com", true, None),
|
||||
flow("fl_daemon_tunnel", "https://p01.icloud.com", true, Some("/usr/libexec/trustd")),
|
||||
] {
|
||||
db.with_tx(|tx| tx.upsert(&f, &yaak_database::UpdateSource::Background)).unwrap();
|
||||
}
|
||||
let filter = |query: &str, hide_system: bool| FlowFilter {
|
||||
hide_encrypted: true,
|
||||
hide_system,
|
||||
..FlowFilter::search(query)
|
||||
};
|
||||
let ids = |filter: FlowFilter| -> Vec<String> {
|
||||
let mut ids: Vec<String> =
|
||||
list(&db, &filter).unwrap().into_iter().map(|f| f.id).collect();
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
assert_eq!(ids(filter("", false)), vec!["fl_get"]);
|
||||
assert_eq!(ids(filter("example", false)), vec!["fl_get"]);
|
||||
assert_eq!(ids(filter("@is:encrypted", false)), vec!["fl_daemon_tunnel", "fl_tunnel"]);
|
||||
assert_eq!(ids(filter("@is:encrypted", true)), vec!["fl_tunnel"]);
|
||||
assert_eq!(ids(filter("@is:tunnelled", false)).len(), 2);
|
||||
|
||||
// The totals: everything stored, and what shows with encrypted connections hidden.
|
||||
let page = sorted_page(&db, &FlowFilter { limit: Some(0), ..filter("", false) }).unwrap();
|
||||
assert_eq!((page.total, page.matching), (3, Some(1)));
|
||||
let page = sorted_page(&db, &FlowFilter::default()).unwrap();
|
||||
assert_eq!((page.total, page.matching), (3, None));
|
||||
assert!(FlowFilter { hide_encrypted: true, ..Default::default() }.narrows());
|
||||
assert_eq!(
|
||||
count_each(&db, &[filter("", false), filter("@is:encrypted", true)]).unwrap(),
|
||||
[1, 1]
|
||||
);
|
||||
|
||||
// Saved searches count as the list would show them.
|
||||
let all = crate::saved_queries::create(&db, "All HTTPS", "@scheme:https").unwrap();
|
||||
let count = |hidden: Hidden| {
|
||||
let counts = crate::saved_queries::counts(&db, hidden).unwrap();
|
||||
counts.into_iter().find(|c| c.id == all.id).unwrap().count
|
||||
};
|
||||
assert_eq!(count(Hidden::default()), 3);
|
||||
assert_eq!(count(Hidden { system: false, encrypted: true }), 1);
|
||||
assert_eq!(count(Hidden { system: true, encrypted: false }), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tells_system_daemons_apart() {
|
||||
assert!(is_system(None, Some("/usr/libexec/nsurlsessiond")));
|
||||
@@ -1897,6 +1976,13 @@ mod tests {
|
||||
};
|
||||
assert_eq!(filter.to_query(), "query=post+%40status%3A4xx&hide_system=true&limit=20");
|
||||
assert_eq!(FlowFilter::from_query(&filter.to_query()).unwrap(), filter);
|
||||
let filter = FlowFilter { hide_encrypted: true, ..filter };
|
||||
assert_eq!(
|
||||
filter.to_query(),
|
||||
"query=post+%40status%3A4xx&hide_system=true&hide_encrypted=true&limit=20"
|
||||
);
|
||||
assert_eq!(FlowFilter::from_query(&filter.to_query()).unwrap(), filter);
|
||||
assert!(FlowFilter::from_query("hide_encrypted=maybe").is_err());
|
||||
assert_eq!(FlowFilter::from_query("").unwrap(), FlowFilter::default());
|
||||
assert!(FlowFilter::from_query("limit=lots").is_err());
|
||||
assert!(FlowFilter::from_query("hide_system=maybe").is_err());
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod save;
|
||||
pub mod saved_queries;
|
||||
pub mod settings;
|
||||
pub mod terminal;
|
||||
pub mod tunnels;
|
||||
|
||||
use crate::actions::{ActionInvocation, ActionMetadata, GlobalAction};
|
||||
use crate::attribution::Attribution;
|
||||
@@ -32,7 +33,9 @@ use crate::grpc::{DecodedGrpcMessage, GrpcSchema, GrpcState};
|
||||
use crate::helper::HelperState;
|
||||
use crate::macos::{SystemProxyBackend, SystemProxyStatus};
|
||||
use crate::messages::FlowMessage;
|
||||
use crate::models::{Flow, FlowBody, ModelPayload, ProxyHeader, StreamKind, find_header};
|
||||
use crate::models::{
|
||||
Flow, FlowBody, ModelPayload, ProxyHeader, StreamKind, TunnelReason, find_header,
|
||||
};
|
||||
use crate::save::{ClientDb, SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
|
||||
use crate::settings::{DecryptList, HttpVersion, ProxySettings, TrafficRetention};
|
||||
use base64::Engine;
|
||||
@@ -130,6 +133,8 @@ pub struct ProxyCtx {
|
||||
pub grpc: GrpcState,
|
||||
/// The search the app shows, which written flows' events are matched against.
|
||||
live_search: Arc<query::LiveSearch>,
|
||||
/// The HTTPS connections the running engine passes through undecrypted now.
|
||||
tunnels: Arc<tunnels::OpenTunnels>,
|
||||
}
|
||||
|
||||
impl ProxyCtx {
|
||||
@@ -178,6 +183,7 @@ impl ProxyCtx {
|
||||
events,
|
||||
grpc: GrpcState::default(),
|
||||
live_search: Default::default(),
|
||||
tunnels: Default::default(),
|
||||
};
|
||||
// Unreadable settings keep the traffic: nothing is deleted on a guess. Nor is traffic
|
||||
// another process is capturing as this launches, which this one may take over later.
|
||||
@@ -513,6 +519,7 @@ impl ProxyCtx {
|
||||
let mut proxy_handle = yaak_proxy::start_proxy(config)?;
|
||||
let attribution = Attribution::new(proxy_handle.port);
|
||||
let _ = attribution_slot.set(attribution.clone());
|
||||
let tunnel_run = self.tunnels.begin_run(Some(attribution.clone()));
|
||||
|
||||
if let Some(event_rx) = proxy_handle.take_event_rx() {
|
||||
let sink = FlowSink {
|
||||
@@ -524,6 +531,10 @@ impl ProxyCtx {
|
||||
recording: self.recording.clone(),
|
||||
finished: Default::default(),
|
||||
clock: BatchClock::Real,
|
||||
tunnels: self.tunnels.clone(),
|
||||
tunnel_run,
|
||||
handle: Arc::downgrade(&self.handle),
|
||||
rejections: Default::default(),
|
||||
};
|
||||
std::thread::spawn(move || run_event_loop(event_rx, sink));
|
||||
}
|
||||
@@ -615,6 +626,9 @@ impl ProxyCtx {
|
||||
let mut handle = self.handle.lock().map_err(|_| "lock poisoned".to_string())?;
|
||||
// Under the handle's lock, so a start waiting for the databases sees it.
|
||||
self.stops.fetch_add(1, Ordering::SeqCst);
|
||||
// Its tunnels go with it, in the same turn of the lock, so nothing reads them as open
|
||||
// once it is gone.
|
||||
self.tunnels.stop_run();
|
||||
// Dropping the handle stops the listener and joins its thread.
|
||||
let port = handle.take().map(|h| h.port);
|
||||
drop(handle);
|
||||
@@ -1098,7 +1112,7 @@ impl ProxyCtx {
|
||||
|
||||
/// Replaces the decrypt list, saved in `settings.json` and applied to the running engine's
|
||||
/// next connections. Connections already open stay as they were.
|
||||
pub fn set_decrypt_list(&self, entries: &[String]) -> Result<DecryptList, String> {
|
||||
pub fn set_decrypt_list(&self, entries: &[String]) -> Result<DecryptListSaved, String> {
|
||||
self.change_decrypt_list(|settings| settings.set_decrypt_list(entries))
|
||||
}
|
||||
|
||||
@@ -1108,38 +1122,167 @@ impl ProxyCtx {
|
||||
&self,
|
||||
add: &[String],
|
||||
remove: &[String],
|
||||
) -> Result<DecryptList, String> {
|
||||
) -> Result<DecryptListSaved, String> {
|
||||
self.change_decrypt_list(|settings| settings.edit_decrypt_list(add, remove))
|
||||
}
|
||||
|
||||
/// Changes the list in `settings.json`, one change at a time, applies it to the running
|
||||
/// engine, and tells the app.
|
||||
/// engine, and tells the app. Connections already open are left as they are; the reply
|
||||
/// counts those the new list would decrypt if they reconnected.
|
||||
fn change_decrypt_list(
|
||||
&self,
|
||||
change: impl FnOnce(&mut ProxySettings) -> Result<(), String>,
|
||||
) -> Result<DecryptList, String> {
|
||||
) -> Result<DecryptListSaved, String> {
|
||||
let _turn = self.decrypt_edits.lock().map_err(|_| "lock poisoned".to_string())?;
|
||||
let mut settings = self.settings()?;
|
||||
change(&mut settings)?;
|
||||
settings.save(&self.settings_path())?;
|
||||
if let Ok(handle) = self.handle.lock()
|
||||
&& let Some(handle) = handle.as_ref()
|
||||
{
|
||||
handle.set_decrypt_policy(settings.decrypt_policy());
|
||||
}
|
||||
let policy = settings.decrypt_policy();
|
||||
// Applied and counted against the one engine running, whose tunnels these are.
|
||||
let still_encrypted = self.with_engine(|engine| {
|
||||
let Some(engine) = engine else {
|
||||
return Ok::<_, String>(0);
|
||||
};
|
||||
engine.set_decrypt_policy(policy.clone());
|
||||
let all = tunnels::TunnelScope::default();
|
||||
Ok(self.reconnectable_in(engine, &policy, &all)?.len())
|
||||
})?;
|
||||
let list = settings.decrypt_list();
|
||||
self.events.emit("decrypt_list_changed", &DecryptListChangedPayload { list: list.clone() });
|
||||
Ok(list)
|
||||
Ok(DecryptListSaved { list, still_encrypted })
|
||||
}
|
||||
|
||||
/// `f` with the engine running now, if any, under its lock. Starting and stopping the engine
|
||||
/// swap it and the open-tunnel registry's run under this same lock, so what `f` reads of
|
||||
/// the engine's tunnels and pass-through set and what it does to them belong to one run.
|
||||
fn with_engine<T>(&self, f: impl FnOnce(Option<&ProxyHandle>) -> T) -> T {
|
||||
let handle = self.handle.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
f(handle.as_ref())
|
||||
}
|
||||
|
||||
/// The open tunnels of `engine` within `scope` that `policy` would decrypt if their clients
|
||||
/// reconnected. For a caller holding the engine's lock.
|
||||
fn reconnectable_in(
|
||||
&self,
|
||||
engine: &ProxyHandle,
|
||||
policy: &yaak_proxy::DecryptPolicy,
|
||||
scope: &tunnels::TunnelScope,
|
||||
) -> Result<Vec<tunnels::OpenTunnel>, String> {
|
||||
tunnels::reconnectable(&self.tunnels.list(), policy, &engine.passthrough(), scope)
|
||||
}
|
||||
|
||||
/// Intercepts again the hosts passed through after clients rejected the CA, as they no
|
||||
/// longer will once it is trusted.
|
||||
pub fn forget_passthrough(&self) {
|
||||
if let Ok(handle) = self.handle.lock()
|
||||
&& let Some(handle) = handle.as_ref()
|
||||
{
|
||||
handle.forget_passthrough();
|
||||
let addresses = self.with_engine(|engine| {
|
||||
let engine = engine?;
|
||||
engine.forget_passthrough();
|
||||
Some(engine.passthrough())
|
||||
});
|
||||
let addresses = addresses.unwrap_or_default();
|
||||
self.events.emit("passthrough_changed", &PassthroughChangedPayload { addresses });
|
||||
}
|
||||
|
||||
/// Intercepts again one address (`host:port`) passed through after a client rejected the
|
||||
/// CA. Returns whether it was passed through, and what still is, read from the same engine.
|
||||
pub fn forget_passthrough_address(&self, address: &str) -> (bool, Vec<String>) {
|
||||
let (forgotten, addresses) = self.with_engine(|engine| match engine {
|
||||
Some(e) => (e.forget_passthrough_address(address), e.passthrough()),
|
||||
None => (false, Vec::new()),
|
||||
});
|
||||
if forgotten {
|
||||
let payload = PassthroughChangedPayload { addresses: addresses.clone() };
|
||||
self.events.emit("passthrough_changed", &payload);
|
||||
}
|
||||
(forgotten, addresses)
|
||||
}
|
||||
|
||||
/// The addresses (`host:port`) the running engine passes through after clients rejected
|
||||
/// the CA. Empty while it is stopped.
|
||||
pub fn passthrough(&self) -> Vec<String> {
|
||||
self.with_engine(|engine| engine.map(ProxyHandle::passthrough).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// [`Self::forget_passthrough_address`] for an address as the app or the control API names
|
||||
/// it, with what is still passed through.
|
||||
pub fn forget_passthrough_request(
|
||||
&self,
|
||||
req: &ForgetPassthroughRequest,
|
||||
) -> Result<ForgetPassthroughResponse, String> {
|
||||
let address = passthrough_address(&req.address)
|
||||
.ok_or_else(|| format!("Invalid address {:?}", req.address))?;
|
||||
let (forgotten, addresses) = self.forget_passthrough_address(&address);
|
||||
Ok(ForgetPassthroughResponse { forgotten, addresses })
|
||||
}
|
||||
|
||||
/// Trusts the CA, made first when the engine has never run so there is one to trust. Once
|
||||
/// trusted, the addresses passed through after clients rejected it are intercepted again.
|
||||
pub async fn trust_ca(&self) -> Result<ca::CaTrustResult, String> {
|
||||
// Off the async threads: it may wait for the keychain or a conversion.
|
||||
let ca = {
|
||||
let ctx = self.clone();
|
||||
blocking(move || ctx.load_ca()).await.map_err(|e| e.message)?
|
||||
};
|
||||
let trusted = ca::trust(ca.cert_path()).await?;
|
||||
if trusted == ca::Trusted::Yes {
|
||||
self.forget_passthrough();
|
||||
}
|
||||
let status = ca::status(ca.cert_path()).await?;
|
||||
Ok(ca::CaTrustResult { status, cancelled: trusted == ca::Trusted::Cancelled })
|
||||
}
|
||||
|
||||
/// The process that owns the engine, while it is another one: commands about the running
|
||||
/// engine go there.
|
||||
fn engine_elsewhere(&self) -> Option<ControlInfo> {
|
||||
if self.port().is_some() {
|
||||
return None;
|
||||
}
|
||||
self.other_owner()
|
||||
}
|
||||
|
||||
/// The HTTPS connections open now that the decrypt list would decrypt if their clients
|
||||
/// reconnected, within `scope`. Not those passed through after a client rejected the CA.
|
||||
pub fn reconnectable_tunnels(
|
||||
&self,
|
||||
scope: &tunnels::TunnelScope,
|
||||
) -> Result<Vec<tunnels::OpenTunnel>, String> {
|
||||
let policy = self.settings()?.decrypt_policy();
|
||||
self.with_engine(|engine| match engine {
|
||||
Some(engine) => self.reconnectable_in(engine, &policy, scope),
|
||||
None => Ok(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Closes tunnels so their clients reconnect, decrypted as the list now says: those in
|
||||
/// `ids` this run of the engine gave out, or, without ids, those
|
||||
/// [`Self::reconnectable_tunnels`] finds in `scope`. Each ends with its flow marked
|
||||
/// `reconnectRequested`. Returns how many were open. Looked up and closed under the engine's
|
||||
/// lock, so a restart can't come between and have another run's tunnels closed.
|
||||
pub fn reconnect_tunnels(
|
||||
&self,
|
||||
ids: Option<&[String]>,
|
||||
scope: &tunnels::TunnelScope,
|
||||
) -> Result<usize, String> {
|
||||
let policy = match ids {
|
||||
Some(_) => None,
|
||||
None => Some(self.settings()?.decrypt_policy()),
|
||||
};
|
||||
self.with_engine(|engine| {
|
||||
let Some(engine) = engine else {
|
||||
return Ok(0);
|
||||
};
|
||||
let ids = match (ids, &policy) {
|
||||
(Some(ids), _) => self.tunnels.engine_ids(ids),
|
||||
(None, Some(policy)) => {
|
||||
let found = self.reconnectable_in(engine, policy, scope)?;
|
||||
found.iter().map(|t| t.engine_id).collect()
|
||||
}
|
||||
(None, None) => Vec::new(),
|
||||
};
|
||||
#[cfg(test)]
|
||||
tests::pause_between_lookup_and_close();
|
||||
Ok(engine.close_tunnels(&ids))
|
||||
})
|
||||
}
|
||||
|
||||
/// Flows are being stored.
|
||||
@@ -1630,6 +1773,51 @@ pub struct DecryptListChangedPayload {
|
||||
pub list: DecryptList,
|
||||
}
|
||||
|
||||
/// `host`, `host:port`, `[::1]` or `[::1]:8443` as the engine keys its pass-through set:
|
||||
/// `host:port`, an IPv6 host in brackets. None when it is none of these.
|
||||
fn passthrough_address(address: &str) -> Option<String> {
|
||||
let address = address.trim();
|
||||
let (host, port) = if let Some(rest) = address.strip_prefix('[') {
|
||||
let (host, after) = rest.split_once(']')?;
|
||||
let port = match after {
|
||||
"" => 443,
|
||||
p => p.strip_prefix(':')?.parse().ok()?,
|
||||
};
|
||||
(format!("[{host}]"), port)
|
||||
} else {
|
||||
match address.split_once(':') {
|
||||
Some((host, port)) if !port.contains(':') => (host.to_string(), port.parse().ok()?),
|
||||
Some(_) => (format!("[{address}]"), 443),
|
||||
None => (address.to_string(), 443),
|
||||
}
|
||||
};
|
||||
(!host.is_empty() && host != "[]").then(|| format!("{host}:{port}"))
|
||||
}
|
||||
|
||||
/// The decrypt list as saved, and what it means for connections already open.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct DecryptListSaved {
|
||||
#[serde(flatten)]
|
||||
pub list: DecryptList,
|
||||
/// Open connections the list now decrypts that stay encrypted until their clients
|
||||
/// reconnect: `reconnect_tunnels` closes them so they do. Closed by nothing else. Zero from
|
||||
/// an owner too old to count them.
|
||||
#[serde(default)]
|
||||
#[ts(type = "number")]
|
||||
pub still_encrypted: usize,
|
||||
}
|
||||
|
||||
/// The addresses passed through after clients rejected the CA changed: one was added or
|
||||
/// forgotten.
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct PassthroughChangedPayload {
|
||||
/// Each `host:port`, an IPv6 host in brackets, sorted.
|
||||
pub addresses: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ProxyStatePayload {
|
||||
@@ -1702,6 +1890,9 @@ pub struct WatchQueryRequest {
|
||||
#[serde(default)]
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_system: bool,
|
||||
#[serde(default)]
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_encrypted: bool,
|
||||
}
|
||||
|
||||
/// Which of some flows a search covers, for flows whose events were matched against another.
|
||||
@@ -1744,6 +1935,9 @@ pub struct CountSavedQueriesRequest {
|
||||
#[serde(default)]
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_system: bool,
|
||||
#[serde(default)]
|
||||
#[ts(optional, as = "Option<bool>")]
|
||||
pub hide_encrypted: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
@@ -2189,6 +2383,56 @@ pub struct CaStatusRequest {}
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct CaTrustRequest {}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ListPassthroughRequest {}
|
||||
|
||||
/// The addresses passed through after clients rejected the CA.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct PassthroughResponse {
|
||||
/// Each `host:port`, an IPv6 host in brackets, sorted.
|
||||
pub addresses: Vec<String>,
|
||||
}
|
||||
|
||||
/// An address to intercept again: `host`, `host:port` or `[::1]:8443`, as a flow's URL has
|
||||
/// it, the port 443 when left out.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ForgetPassthroughRequest {
|
||||
pub address: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ForgetPassthroughResponse {
|
||||
/// It was passed through.
|
||||
pub forgotten: bool,
|
||||
/// The addresses still passed through.
|
||||
pub addresses: Vec<String>,
|
||||
}
|
||||
|
||||
/// Tunnels to close: those in `ids`, or, without them, every one `list_reconnectable_tunnels`
|
||||
/// returns for the same `entry` and `flowId`.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ReconnectTunnelsRequest {
|
||||
/// `OpenTunnel` ids. Ones from an earlier run of the engine close nothing.
|
||||
#[ts(optional)]
|
||||
pub ids: Option<Vec<String>>,
|
||||
#[serde(flatten)]
|
||||
pub scope: tunnels::TunnelScope,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ReconnectTunnelsResponse {
|
||||
/// Tunnels closed: those still open of the ones asked for.
|
||||
#[ts(type = "number")]
|
||||
pub closed: usize,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SystemProxyStatusRequest {}
|
||||
@@ -2472,7 +2716,7 @@ fn get_decrypt_list(ctx: &ProxyCtx, _req: GetDecryptListRequest) -> Result<Decry
|
||||
async fn set_decrypt_list(
|
||||
ctx: ProxyCtx,
|
||||
req: SetDecryptListRequest,
|
||||
) -> Result<DecryptList, RpcError> {
|
||||
) -> Result<DecryptListSaved, RpcError> {
|
||||
if ctx.port().is_none()
|
||||
&& let Some(owner) = ctx.other_owner()
|
||||
{
|
||||
@@ -2485,7 +2729,7 @@ async fn set_decrypt_list(
|
||||
async fn edit_decrypt_list(
|
||||
ctx: ProxyCtx,
|
||||
req: EditDecryptListRequest,
|
||||
) -> Result<DecryptList, RpcError> {
|
||||
) -> Result<DecryptListSaved, RpcError> {
|
||||
if ctx.port().is_none()
|
||||
&& let Some(owner) = ctx.other_owner()
|
||||
{
|
||||
@@ -2524,6 +2768,9 @@ async fn list_workspaces(
|
||||
|
||||
async fn preview_save(ctx: ProxyCtx, req: PreviewSaveRequest) -> Result<SavePreview, RpcError> {
|
||||
let flow = find_flow(&ctx, &req.flow_id)?;
|
||||
if flow.is_handshake_only() {
|
||||
return Err(rpc_error(NOT_A_REQUEST));
|
||||
}
|
||||
let limit = settings(&ctx)?.capture_body_limit;
|
||||
let body = bodies::read_body(&ctx.db()?, &ctx.blobs()?, &flow, FlowBody::Request, limit)
|
||||
.await
|
||||
@@ -2683,16 +2930,59 @@ async fn ca_status(ctx: ProxyCtx, _req: CaStatusRequest) -> Result<CaStatus, Rpc
|
||||
ca::status(&ctx.ca_dir().join("ca.pem")).await.map_err(rpc_error)
|
||||
}
|
||||
|
||||
async fn ca_trust(ctx: ProxyCtx, _req: CaTrustRequest) -> Result<CaStatus, RpcError> {
|
||||
// Creates the CA when the engine has never run, so there is something to trust. Off the
|
||||
// async threads: it may wait for the keychain or a conversion.
|
||||
let ca = {
|
||||
let ctx = ctx.clone();
|
||||
blocking(move || ctx.load_ca()).await?
|
||||
};
|
||||
ca::trust(ca.cert_path()).await.map_err(rpc_error)?;
|
||||
ctx.forget_passthrough();
|
||||
ca::status(ca.cert_path()).await.map_err(rpc_error)
|
||||
/// Asks macOS to trust the CA, whenever the app needs it, not only during setup. A cancelled
|
||||
/// password prompt is a result, `cancelled`, not an error.
|
||||
async fn ca_trust(ctx: ProxyCtx, _req: CaTrustRequest) -> Result<ca::CaTrustResult, RpcError> {
|
||||
ctx.trust_ca().await.map_err(rpc_error)
|
||||
}
|
||||
|
||||
/// The addresses passed through after clients rejected the CA, in the engine that runs, here
|
||||
/// or in the process that owns it.
|
||||
async fn list_passthrough(
|
||||
ctx: ProxyCtx,
|
||||
_req: ListPassthroughRequest,
|
||||
) -> Result<PassthroughResponse, RpcError> {
|
||||
if let Some(owner) = ctx.engine_elsewhere() {
|
||||
return ControlClient::new(owner).passthrough().await.map_err(rpc_error);
|
||||
}
|
||||
Ok(PassthroughResponse { addresses: ctx.passthrough() })
|
||||
}
|
||||
|
||||
/// Intercepts one passed-through address again from its next connection on.
|
||||
async fn forget_passthrough(
|
||||
ctx: ProxyCtx,
|
||||
req: ForgetPassthroughRequest,
|
||||
) -> Result<ForgetPassthroughResponse, RpcError> {
|
||||
if let Some(owner) = ctx.engine_elsewhere() {
|
||||
return ControlClient::new(owner).forget_passthrough(&req).await.map_err(rpc_error);
|
||||
}
|
||||
ctx.forget_passthrough_request(&req).map_err(rpc_error)
|
||||
}
|
||||
|
||||
/// The open tunnels the decrypt list would decrypt if their clients reconnected.
|
||||
async fn list_reconnectable_tunnels(
|
||||
ctx: ProxyCtx,
|
||||
req: tunnels::TunnelScope,
|
||||
) -> Result<Vec<tunnels::OpenTunnel>, RpcError> {
|
||||
if let Some(owner) = ctx.engine_elsewhere() {
|
||||
return ControlClient::new(owner).reconnectable_tunnels(&req).await.map_err(rpc_error);
|
||||
}
|
||||
blocking(move || ctx.reconnectable_tunnels(&req)).await
|
||||
}
|
||||
|
||||
/// Closes tunnels so their clients reconnect, decrypted as the list now says.
|
||||
async fn reconnect_tunnels(
|
||||
ctx: ProxyCtx,
|
||||
req: ReconnectTunnelsRequest,
|
||||
) -> Result<ReconnectTunnelsResponse, RpcError> {
|
||||
if let Some(owner) = ctx.engine_elsewhere() {
|
||||
return ControlClient::new(owner).reconnect_tunnels(&req).await.map_err(rpc_error);
|
||||
}
|
||||
blocking(move || {
|
||||
let closed = ctx.reconnect_tunnels(req.ids.as_deref(), &req.scope)?;
|
||||
Ok::<_, String>(ReconnectTunnelsResponse { closed })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn system_proxy_status(
|
||||
@@ -2780,8 +3070,9 @@ async fn query_values(ctx: ProxyCtx, req: QueryValuesRequest) -> Result<Vec<Stri
|
||||
}
|
||||
|
||||
fn watch_query(ctx: &ProxyCtx, req: WatchQueryRequest) -> Result<bool, RpcError> {
|
||||
let watched = req.query.filter(|q| !q.trim().is_empty() || req.hide_system);
|
||||
ctx.live_search.watch(watched.map(|q| (req.key, q, req.hide_system)));
|
||||
let hidden = query::Hidden { system: req.hide_system, encrypted: req.hide_encrypted };
|
||||
let watched = req.query.filter(|q| !q.trim().is_empty() || hidden != Default::default());
|
||||
ctx.live_search.watch(watched.map(|q| (req.key, q, hidden)));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -2886,7 +3177,8 @@ async fn count_saved_queries(
|
||||
ctx: ProxyCtx,
|
||||
req: CountSavedQueriesRequest,
|
||||
) -> Result<Vec<saved_queries::SavedQueryCount>, RpcError> {
|
||||
blocking(move || saved_queries::counts(&ctx.db()?, req.hide_system)).await
|
||||
let hidden = query::Hidden { system: req.hide_system, encrypted: req.hide_encrypted };
|
||||
blocking(move || saved_queries::counts(&ctx.db()?, hidden)).await
|
||||
}
|
||||
|
||||
// -- Event loop --
|
||||
@@ -2936,6 +3228,13 @@ const STOPPED_MID_STREAM: &str = "Yaak Proxy stopped before the stream ended";
|
||||
/// Why a tunnel still open when the engine stopped ended.
|
||||
const STOPPED_MID_TUNNEL: &str = "Yaak Proxy stopped before the connection closed";
|
||||
|
||||
/// Why a failed handshake's flow can't be saved as a request.
|
||||
pub(crate) const NOT_A_REQUEST: &str =
|
||||
"Not a request: the client's TLS handshake failed before it sent one";
|
||||
|
||||
/// The error of a flow recording a client's refusal of the proxy's certificate.
|
||||
const REJECTED_CERTIFICATE: &str = "Rejected the proxy's certificate";
|
||||
|
||||
/// A flow between its `RequestStart` and its end, with its bodies being written as they
|
||||
/// stream.
|
||||
struct InFlight {
|
||||
@@ -3043,6 +3342,15 @@ struct FlowSink {
|
||||
finished: std::cell::RefCell<FinishedFlows>,
|
||||
/// What a batch's wait is timed by.
|
||||
clock: BatchClock,
|
||||
/// The open tunnels, kept for this engine's run whether or not flows are recorded.
|
||||
tunnels: Arc<tunnels::OpenTunnels>,
|
||||
tunnel_run: u64,
|
||||
/// The engine, for its pass-through set as it changes. Weak, so the loop never keeps alive
|
||||
/// the engine whose events it waits for.
|
||||
handle: Weak<Mutex<Option<ProxyHandle>>>,
|
||||
/// The flow recorded for each refused handshake, by the engine's id for it, for the tunnels
|
||||
/// passed through after it to name.
|
||||
rejections: std::cell::RefCell<HashMap<u64, String>>,
|
||||
}
|
||||
|
||||
/// What the event loop times a batch's wait by: the time, or in tests a time that stands still,
|
||||
@@ -3168,6 +3476,7 @@ fn run_event_loop(rx: std::sync::mpsc::Receiver<ProxyEvent>, sink: FlowSink) {
|
||||
}
|
||||
}
|
||||
sink.write_finished();
|
||||
sink.tunnels.end_run(sink.tunnel_run);
|
||||
// Its hold on the databases goes before the gate opens again.
|
||||
drop(sink);
|
||||
}
|
||||
@@ -3279,19 +3588,61 @@ impl FlowSink {
|
||||
},
|
||||
);
|
||||
}
|
||||
ProxyEvent::TunnelStart { id, started_at, authority, connection, client_addr } => {
|
||||
if !recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
ProxyEvent::TunnelStart {
|
||||
id,
|
||||
started_at,
|
||||
authority,
|
||||
host,
|
||||
port,
|
||||
connection,
|
||||
client_addr,
|
||||
reason,
|
||||
} => {
|
||||
attribution.begin(connection, client_addr);
|
||||
let recorded = recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true);
|
||||
let flow_id = recorded.then(Flow::generate_id);
|
||||
let (tunnel_reason, excluded_by, excluded_built_in, rejected_by) = match reason {
|
||||
yaak_proxy::TunnelReason::NotListed => {
|
||||
(TunnelReason::NotListed, None, false, None)
|
||||
}
|
||||
yaak_proxy::TunnelReason::Excluded { entry, built_in } => {
|
||||
(TunnelReason::Excluded, Some(entry), built_in, None)
|
||||
}
|
||||
yaak_proxy::TunnelReason::Rejected { rejected_by } => {
|
||||
let flow = self.rejections.borrow().get(&rejected_by).cloned();
|
||||
(TunnelReason::Rejected, None, false, flow)
|
||||
}
|
||||
};
|
||||
// Kept paused too, so it can be closed for a reconnect.
|
||||
let mut open = tunnels::OpenTunnel {
|
||||
id: String::new(),
|
||||
engine_id: id,
|
||||
host,
|
||||
port,
|
||||
app_name: None,
|
||||
app_bundle_id: None,
|
||||
flow_id: flow_id.clone(),
|
||||
reason: tunnel_reason,
|
||||
};
|
||||
if let Some(app) = attribution.get(connection, Duration::ZERO) {
|
||||
tunnels::set_app(&mut open, app);
|
||||
}
|
||||
self.tunnels.open(self.tunnel_run, open, connection);
|
||||
let Some(flow_id) = flow_id else {
|
||||
return;
|
||||
};
|
||||
let flow = Flow {
|
||||
id: Flow::generate_id(),
|
||||
id: flow_id,
|
||||
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
|
||||
method: "CONNECT".to_string(),
|
||||
url: format!("https://{authority}"),
|
||||
client_http_version: "HTTP/1.1".to_string(),
|
||||
client_addr: Some(client_addr.to_string()),
|
||||
tunnelled: true,
|
||||
tunnel_reason: Some(tunnel_reason),
|
||||
tunnel_excluded_by: excluded_by,
|
||||
tunnel_excluded_built_in: excluded_built_in,
|
||||
tunnel_rejected_by: rejected_by,
|
||||
..Default::default()
|
||||
};
|
||||
let mut f = InFlight {
|
||||
@@ -3310,15 +3661,77 @@ impl FlowSink {
|
||||
self.write_stream_flow(&mut f);
|
||||
in_flight.insert(id, f);
|
||||
}
|
||||
ProxyEvent::TunnelEnd { id, sent, received, elapsed_ms, error } => {
|
||||
ProxyEvent::TunnelEnd {
|
||||
id,
|
||||
sent,
|
||||
received,
|
||||
elapsed_ms,
|
||||
error,
|
||||
reconnect_requested,
|
||||
} => {
|
||||
self.tunnels.close(self.tunnel_run, id);
|
||||
if let Some(mut f) = in_flight.remove(&id) {
|
||||
f.flow.request_size = sent as i64;
|
||||
f.flow.response_size = received as i64;
|
||||
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
|
||||
f.flow.error = error;
|
||||
f.flow.reconnect_requested = reconnect_requested;
|
||||
self.finish_flow(f);
|
||||
}
|
||||
}
|
||||
ProxyEvent::HandshakeFailed {
|
||||
id,
|
||||
started_at,
|
||||
authority,
|
||||
connection,
|
||||
client_addr,
|
||||
rejection,
|
||||
error,
|
||||
elapsed_ms,
|
||||
} => {
|
||||
// Whether or not it is recorded, the pass-through set has changed.
|
||||
let addresses = self
|
||||
.handle
|
||||
.upgrade()
|
||||
.and_then(|handle| {
|
||||
let handle = handle.lock().ok()?;
|
||||
handle.as_ref().map(ProxyHandle::passthrough)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.events.emit("passthrough_changed", &PassthroughChangedPayload { addresses });
|
||||
if !recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
attribution.begin(connection, client_addr);
|
||||
let error = match &rejection {
|
||||
Some(_) => REJECTED_CERTIFICATE.to_string(),
|
||||
None => format!("TLS handshake failed: {error}"),
|
||||
};
|
||||
let flow = Flow {
|
||||
id: Flow::generate_id(),
|
||||
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
|
||||
url: format!("https://{authority}"),
|
||||
client_http_version: "HTTP/1.1".to_string(),
|
||||
client_addr: Some(client_addr.to_string()),
|
||||
elapsed_ms: Some(clamp_ms(elapsed_ms)),
|
||||
tls_rejected: rejection,
|
||||
error: Some(error),
|
||||
..Default::default()
|
||||
};
|
||||
self.rejections.borrow_mut().insert(id, flow.id.clone());
|
||||
self.finish_flow(InFlight {
|
||||
flow,
|
||||
connection,
|
||||
request_body: None,
|
||||
response_body: None,
|
||||
persisted: false,
|
||||
cleared: false,
|
||||
next_seq: 0,
|
||||
dirty: false,
|
||||
last_write: None,
|
||||
graphql_scan: None,
|
||||
});
|
||||
}
|
||||
ProxyEvent::StreamStart { id, kind } => {
|
||||
if let Some(f) = in_flight.get_mut(&id) {
|
||||
let kind = StreamKind::from(kind);
|
||||
@@ -3787,7 +4200,11 @@ define_rpc! {
|
||||
add_grpc_schema(AddGrpcSchemaRequest) -> GrpcSchema,
|
||||
app_icon(AppIconRequest) -> Option<String>,
|
||||
ca_status(CaStatusRequest) -> CaStatus,
|
||||
ca_trust(CaTrustRequest) -> CaStatus,
|
||||
ca_trust(CaTrustRequest) -> ca::CaTrustResult,
|
||||
forget_passthrough(ForgetPassthroughRequest) -> ForgetPassthroughResponse,
|
||||
list_passthrough(ListPassthroughRequest) -> PassthroughResponse,
|
||||
list_reconnectable_tunnels(tunnels::TunnelScope) -> Vec<tunnels::OpenTunnel>,
|
||||
reconnect_tunnels(ReconnectTunnelsRequest) -> ReconnectTunnelsResponse,
|
||||
clear_flows(ClearFlowsRequest) -> usize,
|
||||
decode_grpc_message(DecodeGrpcMessageRequest) -> DecodedGrpcMessage,
|
||||
export_har(ExportHarRequest) -> usize,
|
||||
@@ -3796,9 +4213,9 @@ define_rpc! {
|
||||
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
|
||||
helper_register(HelperRegisterRequest) -> SystemProxyStatus,
|
||||
helper_unregister(HelperUnregisterRequest) -> SystemProxyStatus,
|
||||
edit_decrypt_list(EditDecryptListRequest) -> DecryptList,
|
||||
edit_decrypt_list(EditDecryptListRequest) -> DecryptListSaved,
|
||||
list_seen(ListSeenRequest) -> flows::SeenTargets,
|
||||
set_decrypt_list(SetDecryptListRequest) -> DecryptList,
|
||||
set_decrypt_list(SetDecryptListRequest) -> DecryptListSaved,
|
||||
list_workspaces(ListWorkspacesRequest) -> ListWorkspacesResponse,
|
||||
preview_save(PreviewSaveRequest) -> SavePreview,
|
||||
reflect_grpc_host(ReflectGrpcHostRequest) -> GrpcSchema,
|
||||
@@ -3823,6 +4240,7 @@ define_rpc! {
|
||||
flows_removed(FlowsRemovedPayload),
|
||||
message_write(MessagePayload),
|
||||
model_write(ModelPayload),
|
||||
passthrough_changed(PassthroughChangedPayload),
|
||||
proxy_state_changed(ProxyStatePayload),
|
||||
saved_queries_changed(SavedQueriesChangedPayload),
|
||||
}
|
||||
@@ -3832,6 +4250,151 @@ define_rpc! {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// While set, [`ProxyCtx::reconnect_tunnels`] says when it has looked up what to close and
|
||||
/// waits, up to a time, to be let go, so a test can restart the engine in between.
|
||||
static BETWEEN_LOOKUP_AND_CLOSE: Mutex<
|
||||
Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>,
|
||||
> = Mutex::new(None);
|
||||
|
||||
pub(super) fn pause_between_lookup_and_close() {
|
||||
let pause = BETWEEN_LOOKUP_AND_CLOSE.lock().unwrap().take();
|
||||
if let Some((reached, go)) = pause {
|
||||
let _ = reached.send(());
|
||||
let _ = go.recv_timeout(Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// A CONNECT tunnel through the engine on `port` to `target`, its bytes crossing both ways.
|
||||
async fn open_tunnel(port: u16, target: &str) -> tokio::net::TcpStream {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut tcp = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let connect = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n");
|
||||
tcp.write_all(connect.as_bytes()).await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
assert!(head.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&head));
|
||||
assert!(still_open(&mut tcp).await, "the tunnel did not relay");
|
||||
tcp
|
||||
}
|
||||
|
||||
/// Whether `tcp` still relays: a ping comes back, rather than the connection ending.
|
||||
async fn still_open(tcp: &mut tokio::net::TcpStream) -> bool {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut echoed = [0u8; 4];
|
||||
tcp.write_all(b"ping").await.is_ok() && tcp.read_exact(&mut echoed).await.is_ok()
|
||||
}
|
||||
|
||||
async fn spawn_echo() -> u16 {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut tcp, _) = listener.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut read, mut write) = tcp.split();
|
||||
let _ = tokio::io::copy(&mut read, &mut write).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
async fn wait_for_open_tunnels(ctx: &ProxyCtx, n: usize) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while ctx.tunnels.list().len() != n {
|
||||
assert!(std::time::Instant::now() < deadline, "{:?}", ctx.tunnels.list());
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// An engine restart between finding what to close and closing it can't close a tunnel of
|
||||
/// the new run, though the new run numbers its tunnels from 1 again: Greptile's "Reconnect
|
||||
/// closes the wrong tunnel" on #835.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_restart_between_lookup_and_close_closes_nothing_of_the_new_run() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings =
|
||||
ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, _rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
ctx.start().unwrap();
|
||||
let echo = spawn_echo().await;
|
||||
// The address the echo listens on, not `localhost`, which Windows tries as `::1` first
|
||||
// and takes seconds to give up on.
|
||||
let target = format!("127.0.0.1:{echo}");
|
||||
let host = "host:127.0.0.1".to_string();
|
||||
|
||||
// Run 1: one tunnel, listed as reconnectable once the list names its host.
|
||||
let mut old = open_tunnel(ctx.port().unwrap(), &target).await;
|
||||
ctx.edit_decrypt_list(std::slice::from_ref(&host), &[]).unwrap();
|
||||
wait_for_open_tunnels(&ctx, 1).await;
|
||||
let listed = ctx.reconnectable_tunnels(&tunnels::TunnelScope::default()).unwrap();
|
||||
let ids: Vec<String> = listed.iter().map(|t| t.id.clone()).collect();
|
||||
assert_eq!((ids.len(), listed[0].engine_id), (1, 1));
|
||||
|
||||
// Reconnect pauses once it has looked up what to close.
|
||||
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
|
||||
let (go_tx, go_rx) = std::sync::mpsc::channel();
|
||||
*BETWEEN_LOOKUP_AND_CLOSE.lock().unwrap() = Some((reached_tx, go_rx));
|
||||
let reconnecting = {
|
||||
let ctx = ctx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ctx.reconnect_tunnels(Some(&ids), &tunnels::TunnelScope::default())
|
||||
})
|
||||
};
|
||||
tokio::task::spawn_blocking(move || reached_rx.recv().unwrap()).await.unwrap();
|
||||
|
||||
// Then the engine restarts, and the new run's first tunnel is number 1 too. While the
|
||||
// reconnect holds the engine's lock, a restart would wait for it, so it is let go
|
||||
// first; were the lock not held, the restart and the new tunnel land in between.
|
||||
let holds_engine = ctx.handle.try_lock().is_err();
|
||||
if holds_engine {
|
||||
go_tx.send(()).unwrap();
|
||||
}
|
||||
let restarting = ctx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
restarting.stop().unwrap();
|
||||
restarting.edit_decrypt_list(&[], std::slice::from_ref(&host)).unwrap();
|
||||
restarting.start().unwrap();
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let mut new = open_tunnel(ctx.port().unwrap(), &target).await;
|
||||
wait_for_open_tunnels(&ctx, 1).await;
|
||||
assert_eq!(ctx.tunnels.list()[0].engine_id, 1, "the new run's first tunnel");
|
||||
if !holds_engine {
|
||||
go_tx.send(()).unwrap();
|
||||
}
|
||||
|
||||
let closed = reconnecting.await.unwrap().unwrap();
|
||||
assert!(still_open(&mut new).await, "the new run's tunnel was closed");
|
||||
assert!(!still_open(&mut old).await, "the old run's tunnel outlived its engine");
|
||||
assert!(holds_engine, "looked up without the engine's lock held");
|
||||
assert_eq!(closed, 1, "the old run's tunnel, closed in its own run");
|
||||
}
|
||||
|
||||
/// An owner from before the count answers a forwarded save without it.
|
||||
#[test]
|
||||
fn a_saved_list_from_an_older_owner_reads_without_its_count() {
|
||||
let saved: DecryptListSaved = serde_json::from_str(r#"{"entries": []}"#).unwrap();
|
||||
assert_eq!((saved.list.entries.len(), saved.still_encrypted), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passthrough_addresses_as_the_engine_keys_them() {
|
||||
assert_eq!(passthrough_address("a.com").as_deref(), Some("a.com:443"));
|
||||
assert_eq!(passthrough_address(" a.com:8443 ").as_deref(), Some("a.com:8443"));
|
||||
assert_eq!(passthrough_address("[::1]").as_deref(), Some("[::1]:443"));
|
||||
assert_eq!(passthrough_address("[::1]:8443").as_deref(), Some("[::1]:8443"));
|
||||
assert_eq!(passthrough_address("::1").as_deref(), Some("[::1]:443"));
|
||||
assert_eq!(passthrough_address(""), None);
|
||||
assert_eq!(passthrough_address("a.com:http"), None);
|
||||
assert_eq!(passthrough_address("[]"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_the_password_prompt_parked_keep_it_over_the_helper() {
|
||||
use yaak_proxy_helper::networksetup::{ProxySetting, ServiceProxy, Snapshot};
|
||||
@@ -3899,6 +4462,10 @@ mod tests {
|
||||
recording: ctx.recording.clone(),
|
||||
finished: Default::default(),
|
||||
clock: BatchClock::Real,
|
||||
tunnels: ctx.tunnels.clone(),
|
||||
tunnel_run: ctx.tunnels.begin_run(None),
|
||||
handle: Arc::downgrade(&ctx.handle),
|
||||
rejections: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -110,11 +110,58 @@ pub struct Flow {
|
||||
/// client rejected the proxy's certificate: method `CONNECT`, its URL the host, its sizes
|
||||
/// the bytes each way, and no headers or bodies. Open until `elapsedMs` or `error` is set.
|
||||
pub tunnelled: bool,
|
||||
/// Why a tunnelled flow was not decrypted. None for other flows, and for tunnels recorded
|
||||
/// before the reason was.
|
||||
pub tunnel_reason: Option<TunnelReason>,
|
||||
/// For a tunnel the decrypt list excluded, the exclusion that kept it out, as stored:
|
||||
/// `!host:*.apple.com`.
|
||||
pub tunnel_excluded_by: Option<String>,
|
||||
/// That exclusion is one of the built-in ones.
|
||||
pub tunnel_excluded_built_in: bool,
|
||||
/// For a tunnel passed through after a client rejected the proxy's certificate, the id of
|
||||
/// the flow of that refused handshake, when it was recorded.
|
||||
pub tunnel_rejected_by: Option<String>,
|
||||
/// The proxy closed this tunnel on request, so its client would reconnect.
|
||||
pub reconnect_requested: bool,
|
||||
/// A client's refused TLS handshake, recorded as its host and port began to be passed
|
||||
/// through: how it refused, its alert (`unknown_ca`, `bad_certificate`,
|
||||
/// `certificate_unknown`, ...) or `hang_up`. Such a flow has no method, its URL is
|
||||
/// `https://<authority>`, and its error says it rejected the certificate. A handshake that
|
||||
/// failed otherwise is recorded the same way with this None and the failure as its error.
|
||||
pub tls_rejected: Option<String>,
|
||||
/// An agent read the flow through the control API: its detail, a body or its messages.
|
||||
/// Never written by an upsert, which keeps what is stored.
|
||||
pub agent_read: bool,
|
||||
}
|
||||
|
||||
/// Why a tunnel was passed through undecrypted.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "gen_models.ts")]
|
||||
pub enum TunnelReason {
|
||||
/// No entry of the decrypt list named it.
|
||||
NotListed,
|
||||
/// An entry named it, and an exclusion kept it out: `tunnelExcludedBy`.
|
||||
Excluded,
|
||||
/// The list decrypts it, but a client rejected the proxy's certificate for its host and
|
||||
/// port, which are passed through until the proxy restarts or forgets them.
|
||||
Rejected,
|
||||
}
|
||||
|
||||
impl TunnelReason {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::NotListed => "not_listed",
|
||||
Self::Excluded => "excluded",
|
||||
Self::Rejected => "rejected",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Self::NotListed, Self::Excluded, Self::Rejected].into_iter().find(|r| r.as_str() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// The streaming protocol a flow carries.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -182,6 +229,11 @@ impl Flow {
|
||||
}
|
||||
}
|
||||
|
||||
/// A client's failed TLS handshake, recorded without a request: nothing to save or replay.
|
||||
pub fn is_handshake_only(&self) -> bool {
|
||||
self.method.is_empty()
|
||||
}
|
||||
|
||||
pub fn truncated(&self, body: FlowBody) -> bool {
|
||||
match body {
|
||||
FlowBody::Request => self.request_truncated,
|
||||
@@ -278,6 +330,12 @@ impl UpsertModelInfo for Flow {
|
||||
(GrpcMessage, self.grpc_message.into()),
|
||||
(GraphqlOperation, self.graphql_operation.into()),
|
||||
(Tunnelled, self.tunnelled.into()),
|
||||
(FlowIden::TunnelReason, self.tunnel_reason.map(|r| r.as_str()).into()),
|
||||
(TunnelExcludedBy, self.tunnel_excluded_by.into()),
|
||||
(TunnelExcludedBuiltIn, self.tunnel_excluded_built_in.into()),
|
||||
(TunnelRejectedBy, self.tunnel_rejected_by.into()),
|
||||
(ReconnectRequested, self.reconnect_requested.into()),
|
||||
(TlsRejected, self.tls_rejected.into()),
|
||||
(ElapsedConnectMs, self.elapsed_connect_ms.into()),
|
||||
(ElapsedTlsMs, self.elapsed_tls_ms.into()),
|
||||
(ElapsedRequestMs, self.elapsed_request_ms.into()),
|
||||
@@ -322,6 +380,12 @@ impl UpsertModelInfo for Flow {
|
||||
FlowIden::GrpcMessage,
|
||||
FlowIden::GraphqlOperation,
|
||||
FlowIden::Tunnelled,
|
||||
FlowIden::TunnelReason,
|
||||
FlowIden::TunnelExcludedBy,
|
||||
FlowIden::TunnelExcludedBuiltIn,
|
||||
FlowIden::TunnelRejectedBy,
|
||||
FlowIden::ReconnectRequested,
|
||||
FlowIden::TlsRejected,
|
||||
FlowIden::ElapsedConnectMs,
|
||||
FlowIden::ElapsedTlsMs,
|
||||
FlowIden::ElapsedRequestMs,
|
||||
@@ -381,6 +445,14 @@ impl UpsertModelInfo for Flow {
|
||||
grpc_message: added_column(r, "grpc_message")?,
|
||||
graphql_operation: added_column(r, "graphql_operation")?,
|
||||
tunnelled: added_column(r, "tunnelled")?.unwrap_or_default(),
|
||||
tunnel_reason: added_column::<String>(r, "tunnel_reason")?
|
||||
.and_then(|r| TunnelReason::parse(&r)),
|
||||
tunnel_excluded_by: added_column(r, "tunnel_excluded_by")?,
|
||||
tunnel_excluded_built_in: added_column(r, "tunnel_excluded_built_in")?
|
||||
.unwrap_or_default(),
|
||||
tunnel_rejected_by: added_column(r, "tunnel_rejected_by")?,
|
||||
reconnect_requested: added_column(r, "reconnect_requested")?.unwrap_or_default(),
|
||||
tls_rejected: added_column(r, "tls_rejected")?,
|
||||
agent_read: added_column(r, "agent_read")?.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ pub const FLAGS: &[&str] = &[
|
||||
"error",
|
||||
"pending",
|
||||
"system",
|
||||
"tunnelled",
|
||||
"encrypted",
|
||||
"rejected",
|
||||
"saved",
|
||||
"read",
|
||||
"loop",
|
||||
@@ -40,6 +41,10 @@ pub const FLAGS: &[&str] = &[
|
||||
"graphql",
|
||||
];
|
||||
|
||||
/// Other names `@is:` takes for a flag, kept for queries written with them: `tunnelled` is
|
||||
/// `encrypted`'s name from before.
|
||||
const FLAG_ALIASES: &[(&str, &str)] = &[("tunnelled", "encrypted")];
|
||||
|
||||
/// Flags `@is:` will take once flows have what they need. Valid, matching nothing.
|
||||
const FLAGS_NOT_YET: &[&str] = &["marked"];
|
||||
|
||||
@@ -84,7 +89,12 @@ pub fn schema() -> &'static Schema {
|
||||
field("status", number(), "Response status", "@status:4xx @status:>=400"),
|
||||
field("type", text(), "Content type", "@type:json"),
|
||||
field("app", text(), "App or program", "@app:Slack"),
|
||||
field("is", text(), "error, pending, system, …", "@is:error -@is:system"),
|
||||
field(
|
||||
"is",
|
||||
text(),
|
||||
"error, pending, system, encrypted, rejected, …",
|
||||
"@is:error -@is:system @is:encrypted",
|
||||
),
|
||||
map("header", "A header on either side", "@header.content-type:json"),
|
||||
map("req.header", "A request header", "@req.header.accept:*"),
|
||||
map("res.header", "A response header", "@res.header.x-cache:hit"),
|
||||
@@ -130,30 +140,53 @@ const TIME_UNITS: &[(&str, f64)] = &[
|
||||
|
||||
// -- Preparing --
|
||||
|
||||
/// A query prepared for running: its shorthands written out, System left out when hidden.
|
||||
/// What a query leaves out unless it names it: System's flows, encrypted connections.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Hidden {
|
||||
pub system: bool,
|
||||
pub encrypted: bool,
|
||||
}
|
||||
|
||||
/// System alone hidden, or nothing.
|
||||
impl From<bool> for Hidden {
|
||||
fn from(system: bool) -> Self {
|
||||
Self { system, encrypted: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A query prepared for running: its shorthands written out, hidden flows left out.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FlowQuery {
|
||||
root: Option<Node>,
|
||||
}
|
||||
|
||||
impl FlowQuery {
|
||||
/// `text` as of now. With `hide_system`, macOS's own daemons are left out, unless the text
|
||||
/// says `@is:system` itself.
|
||||
pub fn new(text: &str, hide_system: bool) -> Self {
|
||||
Self::at(text, hide_system, Utc::now())
|
||||
/// `text` as of now. With `hidden.system`, macOS's own daemons are left out, unless the text
|
||||
/// says `@is:system` itself; with `hidden.encrypted`, connections tunnelled undecrypted,
|
||||
/// unless it says `@is:encrypted` (or `@is:tunnelled`).
|
||||
pub fn new(text: &str, hidden: impl Into<Hidden>) -> Self {
|
||||
Self::at(text, hidden, Utc::now())
|
||||
}
|
||||
|
||||
/// [`Self::new`], with `now` for the times `@time` counts back from.
|
||||
pub fn at(text: &str, hide_system: bool, now: DateTime<Utc>) -> Self {
|
||||
pub fn at(text: &str, hidden: impl Into<Hidden>, now: DateTime<Utc>) -> Self {
|
||||
let hidden = hidden.into();
|
||||
let parsed = yaak_query::parse(text);
|
||||
let mentions_system = parsed.as_ref().is_some_and(mentions_system);
|
||||
let mentions = |flags: &[&str]| parsed.as_ref().is_some_and(|r| mentions_flag(r, flags));
|
||||
let hide: Vec<&str> = [
|
||||
(hidden.system && !mentions(&["system"])).then_some("system"),
|
||||
(hidden.encrypted && !mentions(&["encrypted", "tunnelled"])).then_some("encrypted"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
let mut root = parsed.map(|root| prepare(&root, now, &mut Vec::new()));
|
||||
if hide_system && !mentions_system {
|
||||
for flag in hide {
|
||||
let span = Span::default();
|
||||
let not_system = Node::Not { node: Box::new(is_flag("system", span)), span };
|
||||
let not_flag = Node::Not { node: Box::new(is_flag(flag, span)), span };
|
||||
root = Some(match root {
|
||||
None => not_system,
|
||||
Some(root) => Node::And { children: vec![root, not_system], span },
|
||||
None => not_flag,
|
||||
Some(root) => Node::And { children: vec![root, not_flag], span },
|
||||
});
|
||||
}
|
||||
Self { root }
|
||||
@@ -197,15 +230,15 @@ fn is_flag(flag: &str, span: Span) -> Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The query names `@is:system`, either way, so hiding System leaves it be.
|
||||
fn mentions_system(root: &Node) -> bool {
|
||||
/// The query names `@is:` one of `flags`, either way, so hiding it leaves it be.
|
||||
fn mentions_flag(root: &Node, flags: &[&str]) -> bool {
|
||||
let mut found = false;
|
||||
root.walk(&mut |node| {
|
||||
if let Node::Field { path, value, .. } = node
|
||||
&& path.len() == 1
|
||||
&& path[0].eq_ignore_ascii_case("is")
|
||||
&& let FieldValue::Text { text, .. } | FieldValue::Wildcard { pattern: text } = value
|
||||
&& text.eq_ignore_ascii_case("system")
|
||||
&& flags.iter().any(|f| text.eq_ignore_ascii_case(f))
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
@@ -295,7 +328,10 @@ fn prepare(node: &Node, now: DateTime<Utc>, issues: &mut Vec<Issue>) -> Node {
|
||||
with(FieldValue::Wildcard { pattern: text.clone() })
|
||||
}
|
||||
("is", FieldValue::Text { text, .. }) if !text.is_empty() => {
|
||||
let flag = text.to_lowercase();
|
||||
let mut flag = text.to_lowercase();
|
||||
if let Some((_, to)) = FLAG_ALIASES.iter().find(|(alias, _)| *alias == flag) {
|
||||
flag = to.to_string();
|
||||
}
|
||||
if FLAGS.contains(&flag.as_str()) {
|
||||
with(FieldValue::Wildcard { pattern: flag })
|
||||
} else if FLAGS_NOT_YET.contains(&flag.as_str()) {
|
||||
@@ -441,22 +477,22 @@ pub struct LiveSearch(RwLock<Option<Watched>>);
|
||||
struct Watched {
|
||||
key: String,
|
||||
text: String,
|
||||
hide_system: bool,
|
||||
hidden: Hidden,
|
||||
}
|
||||
|
||||
impl LiveSearch {
|
||||
/// Matches flows against `text` from now on, their events naming `key`; None stops.
|
||||
pub fn watch(&self, watched: Option<(String, String, bool)>) {
|
||||
let watched = watched.map(|(key, text, hide_system)| Watched { key, text, hide_system });
|
||||
pub fn watch(&self, watched: Option<(String, String, Hidden)>) {
|
||||
let watched = watched.map(|(key, text, hidden)| Watched { key, text, hidden });
|
||||
*self.0.write().unwrap_or_else(PoisonError::into_inner) = watched;
|
||||
}
|
||||
|
||||
/// `flow` matched against the search shown, if any.
|
||||
pub fn check(&self, flow: &Flow) -> Option<SearchMatch> {
|
||||
let watched = self.0.read().unwrap_or_else(PoisonError::into_inner);
|
||||
let Watched { key, text, hide_system } = watched.as_ref()?;
|
||||
let Watched { key, text, hidden } = watched.as_ref()?;
|
||||
// Prepared again for each flow, so `@time:<5m` counts back from now.
|
||||
let matches = FlowQuery::new(text, *hide_system).matches(flow);
|
||||
let matches = FlowQuery::new(text, *hidden).matches(flow);
|
||||
Some(SearchMatch { key: key.clone(), matches })
|
||||
}
|
||||
|
||||
@@ -812,7 +848,8 @@ fn flags(flow: &Flow) -> Vec<&'static str> {
|
||||
&& flow.elapsed_ms.is_none()
|
||||
}
|
||||
"system" => is_system(flow.client_bundle_id.as_deref(), flow.client_path.as_deref()),
|
||||
"tunnelled" => flow.tunnelled,
|
||||
"encrypted" => flow.tunnelled,
|
||||
"rejected" => flow.tls_rejected.is_some(),
|
||||
"saved" => flow.saved_request_id.is_some(),
|
||||
"read" => flow.agent_read,
|
||||
"loop" => flow.status == Some(508),
|
||||
@@ -970,7 +1007,11 @@ impl FlowColumns {
|
||||
return name.to_string();
|
||||
}
|
||||
match name {
|
||||
"cancelled" | "tunnelled" | "agent_read" => "0".into(),
|
||||
"cancelled"
|
||||
| "tunnelled"
|
||||
| "agent_read"
|
||||
| "reconnect_requested"
|
||||
| "tunnel_excluded_built_in" => "0".into(),
|
||||
_ => "NULL".into(),
|
||||
}
|
||||
}
|
||||
@@ -1145,7 +1186,8 @@ impl Sql<'_> {
|
||||
c("cancelled")
|
||||
),
|
||||
"system" => format!("is_system({}, {})", c("client_bundle_id"), c("client_path")),
|
||||
"tunnelled" => c("tunnelled"),
|
||||
"encrypted" => c("tunnelled"),
|
||||
"rejected" => format!("{} IS NOT NULL", c("tls_rejected")),
|
||||
"saved" => format!("{} IS NOT NULL", c("saved_request_id")),
|
||||
"read" => c("agent_read"),
|
||||
"loop" => "status = 508".into(),
|
||||
|
||||
@@ -381,6 +381,53 @@ fn headers_on_either_side_or_one() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `@is:encrypted` finds tunnelled connections, as `@is:tunnelled` did and still does, and
|
||||
/// `@is:rejected` refused handshakes; hiding encrypted connections leaves them out unless the
|
||||
/// query names them.
|
||||
#[test]
|
||||
fn encrypted_and_rejected() {
|
||||
let rejected = Flow {
|
||||
id: "fl_rejected".into(),
|
||||
url: "https://my.1password.com".into(),
|
||||
client_http_version: "HTTP/1.1".into(),
|
||||
tls_rejected: Some("unknown_ca".into()),
|
||||
error: Some("Rejected the proxy's certificate".into()),
|
||||
elapsed_ms: Some(3),
|
||||
started_at: (now() - Duration::minutes(5)).naive_utc(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut flows = fixture();
|
||||
flows.push(rejected);
|
||||
let (_dir, db, flows) = db_of(flows);
|
||||
let find = |query: &str, hidden: Hidden| {
|
||||
let prepared = FlowQuery::at(query, hidden, now());
|
||||
let sql = sql_ids(&db, &prepared);
|
||||
assert_eq!(sql, memory_ids(&flows, &prepared), "the two disagree on {query:?}");
|
||||
sql
|
||||
};
|
||||
let none = Hidden::default();
|
||||
let encrypted = Hidden { system: false, encrypted: true };
|
||||
assert_eq!(find("@is:encrypted", none), ids(&["fl_tunnel"]));
|
||||
assert_eq!(find("@is:tunnelled", none), ids(&["fl_tunnel"]));
|
||||
assert_eq!(find("@is:TUNNELLED", none), ids(&["fl_tunnel"]));
|
||||
assert_eq!(find("@is:rejected", none), ids(&["fl_rejected"]));
|
||||
assert!(find("@is:error", none).contains(&"fl_rejected".to_string()));
|
||||
// Hidden, unless named.
|
||||
let all = find("", none);
|
||||
let shown = find("", encrypted);
|
||||
assert_eq!(shown.len(), all.len() - 1);
|
||||
assert!(!shown.contains(&"fl_tunnel".to_string()));
|
||||
assert_eq!(find("@is:encrypted", encrypted), ids(&["fl_tunnel"]));
|
||||
assert_eq!(find("@is:tunnelled", encrypted), ids(&["fl_tunnel"]));
|
||||
assert_eq!(find("bank", encrypted), Vec::<String>::new());
|
||||
// Both hidden.
|
||||
let both = find("", Hidden { system: true, encrypted: true });
|
||||
assert_eq!(both.len(), all.len() - 2);
|
||||
assert_eq!(diagnostics("@is:encrypted @is:rejected @is:tunnelled"), vec![]);
|
||||
assert!(FLAGS.contains(&"encrypted") && FLAGS.contains(&"rejected"));
|
||||
assert!(!FLAGS.contains(&"tunnelled"), "an alias, not offered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags() {
|
||||
assert_eq!(finds("@is:system"), ids(&["fl_daemon"]));
|
||||
@@ -701,6 +748,10 @@ fn sample(count: usize) -> Vec<Flow> {
|
||||
cancelled: rng.chance(10),
|
||||
saved_request_id: rng.chance(15).then(|| "rq_x".to_string()),
|
||||
tunnelled,
|
||||
tls_rejected: rng
|
||||
.chance(10)
|
||||
.then(|| rng.pick(&["unknown_ca", "hang_up"]).to_string())
|
||||
.filter(|_| !tunnelled),
|
||||
agent_read: rng.chance(20),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -888,6 +939,12 @@ const BATTERY: &[&str] = &[
|
||||
"@nope:x",
|
||||
"-@nope:x",
|
||||
"@status:4xx OR @is:tunnelled",
|
||||
"@is:encrypted",
|
||||
"-@is:encrypted",
|
||||
"@is:rejected",
|
||||
"@is:rejected OR @is:encrypted",
|
||||
"-@is:rejected @is:error",
|
||||
"@is:e*",
|
||||
"(@status:4xx OR @is:error) -@method:post",
|
||||
"-(@status:* OR @is:pending)",
|
||||
"github -@host:github.com",
|
||||
@@ -903,8 +960,9 @@ fn the_database_and_the_evaluator_find_the_same_flows() {
|
||||
let (_dir, db, flows) = db_of(sample(400));
|
||||
let mut checked = 0;
|
||||
for query in BATTERY {
|
||||
for hide_system in [false, true] {
|
||||
let prepared = FlowQuery::at(query, hide_system, now());
|
||||
for (system, encrypted) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let hidden = Hidden { system, encrypted };
|
||||
let prepared = FlowQuery::at(query, hidden, now());
|
||||
let sql = sql_ids(&db, &prepared);
|
||||
let memory = memory_ids(&flows, &prepared);
|
||||
if sql != memory {
|
||||
@@ -915,14 +973,14 @@ fn the_database_and_the_evaluator_find_the_same_flows() {
|
||||
.or(only_memory.first())
|
||||
.map(|id| flows.iter().find(|f| &&f.id == id).cloned());
|
||||
panic!(
|
||||
"{query:?} (hide_system {hide_system}): only in SQL {only_sql:?}, \
|
||||
"{query:?} ({hidden:?}): only in SQL {only_sql:?}, \
|
||||
only in memory {only_memory:?}; e.g. {example:#?}"
|
||||
);
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, BATTERY.len() * 2);
|
||||
assert_eq!(checked, BATTERY.len() * 4);
|
||||
// The battery means something only if the sample spreads its answers.
|
||||
let spread = BATTERY
|
||||
.iter()
|
||||
@@ -938,9 +996,9 @@ fn live_search_matches_as_the_list_does() {
|
||||
let live = LiveSearch::default();
|
||||
let flow = fixture().remove(0);
|
||||
assert_eq!(live.check(&flow), None);
|
||||
live.watch(Some(("k1".into(), "@status:2xx @host:*.github.com".into(), false)));
|
||||
live.watch(Some(("k1".into(), "@status:2xx @host:*.github.com".into(), false.into())));
|
||||
assert_eq!(live.check(&flow), Some(SearchMatch { key: "k1".into(), matches: true }));
|
||||
live.watch(Some(("k2".into(), "@status:4xx".into(), false)));
|
||||
live.watch(Some(("k2".into(), "@status:4xx".into(), false.into())));
|
||||
let payload = live.payload(flow, true);
|
||||
assert_eq!(payload.search, Some(SearchMatch { key: "k2".into(), matches: false }));
|
||||
live.watch(None);
|
||||
|
||||
@@ -111,6 +111,9 @@ impl ClientDb {
|
||||
body: &DecodedBody,
|
||||
target: &SaveFlowRequest,
|
||||
) -> Result<SaveFlowResponse, String> {
|
||||
if flow.is_handshake_only() {
|
||||
return Err(crate::NOT_A_REQUEST.to_string());
|
||||
}
|
||||
let db = self.query_manager.connect();
|
||||
db.get_workspace(&target.workspace_id)
|
||||
.map_err(|_| format!("No workspace {} in Yaak", target.workspace_id))?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::db::ProxyQueryManager;
|
||||
use crate::flows::{self, FlowFilter};
|
||||
use crate::query::Hidden;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
use yaak_database::generate_prefixed_id;
|
||||
@@ -115,13 +116,17 @@ pub fn delete(db: &ProxyQueryManager, id: &str) -> Result<bool, String> {
|
||||
.map_err(|e| failed("delete", e))
|
||||
}
|
||||
|
||||
/// Each saved query's count of flows, with System's left out when `hide_system`, as the list
|
||||
/// would show it, read from one snapshot.
|
||||
pub fn counts(db: &ProxyQueryManager, hide_system: bool) -> Result<Vec<SavedQueryCount>, String> {
|
||||
/// Each saved query's count of flows, with what `hidden` says left out, as the list would show
|
||||
/// it, read from one snapshot.
|
||||
pub fn counts(db: &ProxyQueryManager, hidden: Hidden) -> Result<Vec<SavedQueryCount>, String> {
|
||||
let saved = list(db)?;
|
||||
let filters: Vec<FlowFilter> = saved
|
||||
.iter()
|
||||
.map(|s| FlowFilter { hide_system, ..FlowFilter::search(s.query.clone()) })
|
||||
.map(|s| FlowFilter {
|
||||
hide_system: hidden.system,
|
||||
hide_encrypted: hidden.encrypted,
|
||||
..FlowFilter::search(s.query.clone())
|
||||
})
|
||||
.collect();
|
||||
let counts = flows::count_each(db, &filters)?;
|
||||
Ok(saved
|
||||
@@ -165,7 +170,7 @@ mod tests {
|
||||
["Errors", "Fine"]
|
||||
);
|
||||
|
||||
let counts = counts(&db, false).unwrap();
|
||||
let counts = counts(&db, false.into()).unwrap();
|
||||
assert_eq!(
|
||||
counts,
|
||||
vec![
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use ts_rs::TS;
|
||||
use yaak_proxy::{BUILT_IN_EXCLUSIONS, DEFAULT_CAPTURE_BODY_LIMIT, DecryptEntry, DecryptPolicy};
|
||||
use yaak_proxy::{
|
||||
BUILT_IN_EXCLUSIONS, BuiltInKind, DEFAULT_CAPTURE_BODY_LIMIT, DecryptEntry, DecryptPolicy,
|
||||
};
|
||||
|
||||
/// `settings.json` in the proxy data directory. Missing keys take their defaults.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -69,6 +71,30 @@ pub struct DecryptListEntry {
|
||||
pub entry: String,
|
||||
/// Shipped with the app: an exclusion of Apple's services or a pinned app's hosts.
|
||||
pub built_in: bool,
|
||||
/// Why a built-in exclusion ships. None for the user's own entries.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub kind: Option<ExclusionKind>,
|
||||
}
|
||||
|
||||
/// Why a built-in exclusion ships.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub enum ExclusionKind {
|
||||
/// Apple's own services, which macOS daemons reach with pinned certificates.
|
||||
Apple,
|
||||
/// The hosts of an app that pins its certificates.
|
||||
Pinned,
|
||||
}
|
||||
|
||||
impl From<BuiltInKind> for ExclusionKind {
|
||||
fn from(kind: BuiltInKind) -> Self {
|
||||
match kind {
|
||||
BuiltInKind::Apple => Self::Apple,
|
||||
BuiltInKind::Pinned => Self::Pinned,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What HTTPS is decrypted: the user's entries in order, then the built-in exclusions not
|
||||
@@ -115,12 +141,19 @@ impl ProxySettings {
|
||||
|
||||
/// The user's entries, then the built-in exclusions they kept.
|
||||
pub fn decrypt_list(&self) -> DecryptList {
|
||||
let user =
|
||||
self.decrypt.iter().map(|e| DecryptListEntry { entry: e.clone(), built_in: false });
|
||||
let user = self.decrypt.iter().map(|e| DecryptListEntry {
|
||||
entry: e.clone(),
|
||||
built_in: false,
|
||||
kind: None,
|
||||
});
|
||||
let built_in = BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.filter(|e| !self.decrypt_built_ins_removed.iter().any(|r| r == *e))
|
||||
.map(|e| DecryptListEntry { entry: e.to_string(), built_in: true });
|
||||
.filter(|(e, _)| !self.decrypt_built_ins_removed.iter().any(|r| r == e))
|
||||
.map(|(e, kind)| DecryptListEntry {
|
||||
entry: e.to_string(),
|
||||
built_in: true,
|
||||
kind: Some((*kind).into()),
|
||||
});
|
||||
DecryptList { entries: user.chain(built_in).collect() }
|
||||
}
|
||||
|
||||
@@ -142,8 +175,8 @@ impl ProxySettings {
|
||||
self.decrypt = user;
|
||||
self.decrypt_built_ins_removed = BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.filter(|e| !kept_built_ins.iter().any(|k| k == *e))
|
||||
.map(|e| e.to_string())
|
||||
.filter(|(e, _)| !kept_built_ins.iter().any(|k| k == e))
|
||||
.map(|(e, _)| e.to_string())
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
@@ -346,7 +379,10 @@ mod tests {
|
||||
];
|
||||
// Every built-in exclusion but zoom.us, kept.
|
||||
entries.extend(
|
||||
BUILT_IN_EXCLUSIONS.iter().filter(|e| **e != "!host:*.zoom.us").map(|e| e.to_string()),
|
||||
BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.filter(|(e, _)| *e != "!host:*.zoom.us")
|
||||
.map(|(e, _)| e.to_string()),
|
||||
);
|
||||
settings.set_decrypt_list(&entries).unwrap();
|
||||
assert_eq!(settings.decrypt, ["host:api.example.com", "*", "app:Google Chrome"]);
|
||||
@@ -354,9 +390,13 @@ mod tests {
|
||||
let list = settings.decrypt_list();
|
||||
assert_eq!(
|
||||
list.entries[0],
|
||||
DecryptListEntry { entry: "host:api.example.com".into(), built_in: false }
|
||||
DecryptListEntry { entry: "host:api.example.com".into(), built_in: false, kind: None }
|
||||
);
|
||||
assert!(list.entries[3].built_in);
|
||||
assert_eq!(list.entries[3].entry, "!host:*.apple.com");
|
||||
assert_eq!(list.entries[3].kind, Some(ExclusionKind::Apple));
|
||||
let onepassword = list.entries.iter().find(|e| e.entry == "!host:*.1password.com");
|
||||
assert_eq!(onepassword.unwrap().kind, Some(ExclusionKind::Pinned));
|
||||
assert!(!list.entries.iter().any(|e| e.entry == "!host:*.zoom.us"));
|
||||
|
||||
// Written again, a built-in exclusion is restored.
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! The HTTPS connections the engine is passing through undecrypted right now, kept whether or
|
||||
//! not flows are recorded, since a tunnel opened while paused has no flow. Each is added as its
|
||||
//! `TunnelStart` is handled and removed at its `TunnelEnd`, never on the decrypted path. From
|
||||
//! them and the decrypt list come the tunnels that would be decrypted if their client
|
||||
//! reconnected, which the app may close so it does.
|
||||
|
||||
use crate::attribution::{Attribution, ClientApp};
|
||||
use crate::models::TunnelReason;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
use ts_rs::TS;
|
||||
use yaak_proxy::{DecryptApp, DecryptEntry, DecryptPolicy, DecryptQuery};
|
||||
|
||||
/// An open tunnel, as the app is told of it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct OpenTunnel {
|
||||
/// Its id for closing it, unique to this run of the engine, so one listed before the
|
||||
/// engine restarted closes nothing after.
|
||||
pub id: String,
|
||||
/// The engine's own number for it, which starts again each run.
|
||||
#[serde(skip)]
|
||||
#[ts(skip)]
|
||||
pub engine_id: u64,
|
||||
/// The host it leads to, without an IPv6 address's brackets.
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
/// The app that opened it, when known.
|
||||
pub app_name: Option<String>,
|
||||
pub app_bundle_id: Option<String>,
|
||||
/// Its flow, when it was recorded.
|
||||
pub flow_id: Option<String>,
|
||||
pub reason: TunnelReason,
|
||||
}
|
||||
|
||||
impl OpenTunnel {
|
||||
/// `host:port`, as the engine keys its pass-through set, an IPv6 host in brackets.
|
||||
pub fn address(&self) -> String {
|
||||
if self.host.contains(':') {
|
||||
format!("[{}]:{}", self.host, self.port)
|
||||
} else {
|
||||
format!("{}:{}", self.host, self.port)
|
||||
}
|
||||
}
|
||||
|
||||
fn query(&self) -> DecryptQuery {
|
||||
DecryptQuery {
|
||||
host: self.host.clone(),
|
||||
port: self.port,
|
||||
app: self.app_name.as_ref().map(|name| DecryptApp {
|
||||
name: name.clone(),
|
||||
bundle_id: self.app_bundle_id.clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which open tunnels to consider: all of them, those one decrypt-list entry names, or the one
|
||||
/// a flow records.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct TunnelScope {
|
||||
/// An entry as stored or typed, `host:www.google.com`, `app:Dia`, `*`: only tunnels it
|
||||
/// names. An exclusion, `!host:*.chase.com`, names those it would keep out.
|
||||
#[ts(optional)]
|
||||
pub entry: Option<String>,
|
||||
/// Only the tunnel this flow records.
|
||||
#[ts(optional)]
|
||||
pub flow_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The open tunnels among `tunnels` in `scope` that `policy` would decrypt if their clients
|
||||
/// reconnected. Those whose address `passthrough` holds, after a client rejected the proxy's
|
||||
/// certificate, are left out, as their next connection would be passed through again; once the
|
||||
/// address is forgotten, its tunnels count again.
|
||||
pub fn reconnectable(
|
||||
tunnels: &[OpenTunnel],
|
||||
policy: &DecryptPolicy,
|
||||
passthrough: &[String],
|
||||
scope: &TunnelScope,
|
||||
) -> Result<Vec<OpenTunnel>, String> {
|
||||
let entry = scope.entry.as_deref().map(DecryptEntry::parse).transpose()?;
|
||||
Ok(tunnels
|
||||
.iter()
|
||||
.filter(|t| scope.flow_id.as_ref().is_none_or(|f| t.flow_id.as_ref() == Some(f)))
|
||||
.filter(|t| !passthrough.contains(&t.address()))
|
||||
.filter(|t| {
|
||||
let query = t.query();
|
||||
entry.as_ref().is_none_or(|e| e.covers(&query)) && policy.decrypts(&query)
|
||||
})
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The registry of open tunnels, shared by the context and the engine's event loop. Each start
|
||||
/// of the engine begins a new run, its ids its own, and an event loop of an earlier run changes
|
||||
/// nothing.
|
||||
#[derive(Default)]
|
||||
pub struct OpenTunnels(Mutex<Run>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Run {
|
||||
run: u64,
|
||||
/// Random for each run, so ids from another run or process never match this one's.
|
||||
token: String,
|
||||
/// Finds the app behind a tunnel not known when it opened.
|
||||
attribution: Option<Attribution>,
|
||||
tunnels: HashMap<u64, Open>,
|
||||
}
|
||||
|
||||
struct Open {
|
||||
tunnel: OpenTunnel,
|
||||
/// The client connection it came on, for finding its app.
|
||||
connection: u64,
|
||||
}
|
||||
|
||||
impl OpenTunnels {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Run> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Starts a run for an engine just started, forgetting the last one's tunnels, which ended
|
||||
/// with it. Returns the run, for the event loop's changes.
|
||||
pub fn begin_run(&self, attribution: Option<Attribution>) -> u64 {
|
||||
let mut run = self.lock();
|
||||
run.run += 1;
|
||||
run.token = yaak_database::generate_prefixed_id("tnl");
|
||||
run.attribution = attribution;
|
||||
run.tunnels.clear();
|
||||
run.run
|
||||
}
|
||||
|
||||
/// The engine stopped, and its tunnels with it. Its event loop's late changes, and ids it
|
||||
/// gave out, apply to nothing from now on.
|
||||
pub fn stop_run(&self) {
|
||||
let mut run = self.lock();
|
||||
run.run += 1;
|
||||
run.token.clear();
|
||||
run.attribution = None;
|
||||
run.tunnels.clear();
|
||||
}
|
||||
|
||||
/// The engine of `run` stopped, and its tunnels with it.
|
||||
pub fn end_run(&self, run: u64) {
|
||||
let mut current = self.lock();
|
||||
if current.run == run {
|
||||
current.tunnels.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// A tunnel opened in `run`, on client `connection`, its `id` given here from its
|
||||
/// `engine_id`.
|
||||
pub fn open(&self, run: u64, mut tunnel: OpenTunnel, connection: u64) {
|
||||
let mut current = self.lock();
|
||||
if current.run == run {
|
||||
tunnel.id = format!("{}.{}", current.token, tunnel.engine_id);
|
||||
current.tunnels.insert(tunnel.engine_id, Open { tunnel, connection });
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's numbers for those of `ids` this run gave out. Others are left out.
|
||||
pub fn engine_ids(&self, ids: &[String]) -> Vec<u64> {
|
||||
let current = self.lock();
|
||||
if current.token.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
ids.iter()
|
||||
.filter_map(|id| id.strip_prefix(current.token.as_str())?.strip_prefix('.'))
|
||||
.filter_map(|n| n.parse().ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A tunnel of `run` closed.
|
||||
pub fn close(&self, run: u64, id: u64) {
|
||||
let mut current = self.lock();
|
||||
if current.run == run {
|
||||
current.tunnels.remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The tunnels open now, oldest first, each with its app when it can be found without
|
||||
/// waiting.
|
||||
pub fn list(&self) -> Vec<OpenTunnel> {
|
||||
let mut current = self.lock();
|
||||
let Run { attribution, tunnels, .. } = &mut *current;
|
||||
for open in tunnels.values_mut() {
|
||||
if open.tunnel.app_name.is_none()
|
||||
&& let Some(app) =
|
||||
attribution.as_ref().and_then(|a| a.get(open.connection, Duration::ZERO))
|
||||
{
|
||||
set_app(&mut open.tunnel, app);
|
||||
}
|
||||
}
|
||||
let mut list: Vec<OpenTunnel> = tunnels.values().map(|o| o.tunnel.clone()).collect();
|
||||
list.sort_by_key(|t| t.engine_id);
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the app that opened `tunnel`.
|
||||
pub fn set_app(tunnel: &mut OpenTunnel, app: ClientApp) {
|
||||
tunnel.app_name = Some(app.name);
|
||||
tunnel.app_bundle_id = app.bundle_id;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use yaak_proxy::BUILT_IN_EXCLUSIONS;
|
||||
|
||||
fn tunnel(id: u64, host: &str, app: Option<&str>, reason: TunnelReason) -> OpenTunnel {
|
||||
OpenTunnel {
|
||||
id: String::new(),
|
||||
engine_id: id,
|
||||
host: host.into(),
|
||||
port: 443,
|
||||
app_name: app.map(String::from),
|
||||
app_bundle_id: app.map(|a| format!("com.example.{}", a.to_lowercase())),
|
||||
flow_id: Some(format!("fl_{id}")),
|
||||
reason,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample() -> Vec<OpenTunnel> {
|
||||
use TunnelReason::*;
|
||||
vec![
|
||||
tunnel(1, "www.google.com", Some("Dia"), NotListed),
|
||||
tunnel(2, "api.example.com", Some("Slack"), NotListed),
|
||||
tunnel(3, "gateway.icloud.com", Some("Dia"), Excluded),
|
||||
tunnel(4, "my.1password.com", Some("1Password"), Rejected),
|
||||
tunnel(5, "www.chase.com", None, Excluded),
|
||||
tunnel(6, "maps.google.com", None, NotListed),
|
||||
]
|
||||
}
|
||||
|
||||
fn policy(entries: &[&str]) -> DecryptPolicy {
|
||||
let mut all = entries.to_vec();
|
||||
all.extend(BUILT_IN_EXCLUSIONS.iter().map(|(e, _)| *e));
|
||||
DecryptPolicy::parse(&all).unwrap()
|
||||
}
|
||||
|
||||
fn ids(
|
||||
policy: &DecryptPolicy,
|
||||
passthrough: &[&str],
|
||||
entry: Option<&str>,
|
||||
flow_id: Option<&str>,
|
||||
) -> Vec<u64> {
|
||||
let passthrough: Vec<String> = passthrough.iter().map(|p| p.to_string()).collect();
|
||||
let scope =
|
||||
TunnelScope { entry: entry.map(String::from), flow_id: flow_id.map(String::from) };
|
||||
reconnectable(&sample(), policy, &passthrough, &scope)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| t.engine_id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_entries() {
|
||||
let p = policy(&["host:www.google.com"]);
|
||||
assert_eq!(ids(&p, &[], None, None), [1]);
|
||||
let p = policy(&["host:*.google.com"]);
|
||||
assert_eq!(ids(&p, &[], None, None), [1, 6]);
|
||||
// Narrowed to one entry of several.
|
||||
let p = policy(&["host:*.google.com", "host:api.example.com"]);
|
||||
assert_eq!(ids(&p, &[], Some("host:api.example.com"), None), [2]);
|
||||
assert_eq!(ids(&p, &[], Some("api.example.com"), None), [2], "as typed");
|
||||
assert_eq!(ids(&p, &[], Some("host:*.google.com"), None), [1, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_entries() {
|
||||
// Dia's iCloud tunnel too: an app entry outranks the built-in exclusion.
|
||||
let p = policy(&["app:Dia"]);
|
||||
assert_eq!(ids(&p, &[], None, None), [1, 3]);
|
||||
let p = policy(&["app:com.example.slack"]);
|
||||
assert_eq!(ids(&p, &[], Some("app:com.example.slack"), None), [2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_and_exclusions() {
|
||||
// The built-in exclusions keep iCloud and 1Password out.
|
||||
let p = policy(&["*"]);
|
||||
assert_eq!(ids(&p, &[], None, None), [1, 2, 5, 6]);
|
||||
assert_eq!(ids(&p, &[], Some("*"), None), [1, 2, 5, 6]);
|
||||
// The person's own exclusion.
|
||||
let p = policy(&["*", "!host:*.chase.com"]);
|
||||
assert_eq!(ids(&p, &[], None, None), [1, 2, 6]);
|
||||
// A removed exclusion, asked about by name: what it kept out.
|
||||
let p = policy(&["*"]);
|
||||
assert_eq!(ids(&p, &[], Some("!host:*.chase.com"), None), [5]);
|
||||
assert!(reconnectable(&sample(), &p, &[], &TunnelScope::search_entry("host:a b")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_pass_throughs_are_left_out() {
|
||||
let p = policy(&["*", "host:my.1password.com"]);
|
||||
let rejected = "my.1password.com:443";
|
||||
assert!(!ids(&p, &[rejected], None, None).contains(&4), "passed through still");
|
||||
// Forgotten, its next connection would be decrypted.
|
||||
assert!(ids(&p, &[], None, None).contains(&4));
|
||||
// An address passed through since it opened.
|
||||
assert_eq!(ids(&p, &[rejected, "www.google.com:443"], None, None), [2, 5, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_flow() {
|
||||
let p = policy(&["*"]);
|
||||
assert_eq!(ids(&p, &[], None, Some("fl_2")), [2]);
|
||||
assert!(ids(&p, &[], None, Some("fl_3")).is_empty(), "excluded still");
|
||||
assert!(ids(&p, &[], None, Some("fl_nope")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_listed_reconnects_nothing() {
|
||||
assert!(ids(&policy(&[]), &[], None, None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_keeps_one_run() {
|
||||
let tunnels = OpenTunnels::default();
|
||||
let first = tunnels.begin_run(None);
|
||||
tunnels.open(first, tunnel(1, "a.com", None, TunnelReason::NotListed), 1);
|
||||
tunnels.open(first, tunnel(2, "b.com", None, TunnelReason::NotListed), 2);
|
||||
tunnels.close(first, 1);
|
||||
assert_eq!(tunnels.list().iter().map(|t| t.engine_id).collect::<Vec<_>>(), [2]);
|
||||
let id = tunnels.list()[0].id.clone();
|
||||
assert!(id.starts_with("tnl_") && id.ends_with(".2"), "{id}");
|
||||
assert_eq!(tunnels.engine_ids(&[id.clone(), "tnl_x.2".into(), "2".into()]), [2]);
|
||||
// A new run starts empty, and the old one's late events change nothing.
|
||||
let second = tunnels.begin_run(None);
|
||||
tunnels.open(first, tunnel(3, "c.com", None, TunnelReason::NotListed), 3);
|
||||
tunnels.open(second, tunnel(2, "d.com", None, TunnelReason::NotListed), 4);
|
||||
tunnels.close(first, 2);
|
||||
tunnels.end_run(first);
|
||||
assert_eq!(tunnels.list().iter().map(|t| t.host.as_str()).collect::<Vec<_>>(), ["d.com"]);
|
||||
// An id the first run gave out names nothing now, though its number is reused.
|
||||
assert!(tunnels.engine_ids(&[id]).is_empty());
|
||||
tunnels.end_run(second);
|
||||
assert!(tunnels.list().is_empty());
|
||||
|
||||
// Stopped, a run's late events and ids apply to nothing.
|
||||
let third = tunnels.begin_run(None);
|
||||
tunnels.open(third, tunnel(1, "e.com", None, TunnelReason::NotListed), 5);
|
||||
let id = tunnels.list()[0].id.clone();
|
||||
tunnels.stop_run();
|
||||
assert!(tunnels.list().is_empty());
|
||||
tunnels.open(third, tunnel(2, "f.com", None, TunnelReason::NotListed), 6);
|
||||
assert!(tunnels.list().is_empty());
|
||||
assert!(tunnels.engine_ids(&[id, ".1".into()]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn addresses_as_the_engine_keys_them() {
|
||||
assert_eq!(tunnel(1, "a.com", None, TunnelReason::NotListed).address(), "a.com:443");
|
||||
assert_eq!(tunnel(1, "::1", None, TunnelReason::NotListed).address(), "[::1]:443");
|
||||
}
|
||||
|
||||
impl TunnelScope {
|
||||
fn search_entry(entry: &str) -> Self {
|
||||
Self { entry: Some(entry.into()), flow_id: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,6 +494,103 @@ async fn the_app_takes_over_from_the_cli() {
|
||||
assert!(control::live_owner(dir.path()).is_none());
|
||||
}
|
||||
|
||||
/// Tunnels listed while the CLI owned the engine can't be closed once the app has taken over,
|
||||
/// by id or by flow, though the app's engine numbers its tunnels from 1 again: a request closes
|
||||
/// only tunnels of the engine run it names. An entry names what is open now.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tunnels_listed_before_the_app_took_over_close_nothing_after() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let client_dir = tempfile::tempdir().unwrap();
|
||||
let cli = ctx(dir.path(), client_dir.path()).with_owner(Owner::Cli);
|
||||
let mut server = ControlServer::start(cli.clone()).unwrap();
|
||||
let stop_rx = server.take_stop_rx().unwrap();
|
||||
let daemon = std::thread::spawn(move || {
|
||||
stop_rx.recv().unwrap();
|
||||
drop(server);
|
||||
});
|
||||
cli.start().unwrap();
|
||||
let app = ctx(dir.path(), client_dir.path());
|
||||
|
||||
let echo = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let echo_port = echo.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut tcp, _) = echo.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut read, mut write) = tcp.split();
|
||||
let _ = tokio::io::copy(&mut read, &mut write).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
// The address the echo listens on, not `localhost`, which Windows tries as `::1` first and
|
||||
// takes seconds to give up on.
|
||||
let target = format!("127.0.0.1:{echo_port}");
|
||||
let open = |port: u16| {
|
||||
let target = target.clone();
|
||||
async move {
|
||||
let mut tcp = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let connect = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n");
|
||||
tcp.write_all(connect.as_bytes()).await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
tcp
|
||||
}
|
||||
};
|
||||
let alive = |mut tcp: tokio::net::TcpStream| async move {
|
||||
let mut echoed = [0u8; 4];
|
||||
let ok = tcp.write_all(b"ping").await.is_ok() && tcp.read_exact(&mut echoed).await.is_ok();
|
||||
(ok, tcp)
|
||||
};
|
||||
let listed = |app: &ProxyCtx| {
|
||||
let app = app.clone();
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let tunnels = rpc(&app, "list_reconnectable_tunnels", json!({})).await.unwrap();
|
||||
if tunnels.as_array().unwrap().len() == 1 && !tunnels[0]["flowId"].is_null() {
|
||||
return tunnels[0].clone();
|
||||
}
|
||||
assert!(Instant::now() < deadline, "the tunnel never showed: {tunnels}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The CLI's tunnel, listed through it.
|
||||
let (ok, _old) = alive(open(cli.port().unwrap()).await).await;
|
||||
assert!(ok);
|
||||
rpc(&app, "edit_decrypt_list", json!({"add": ["host:127.0.0.1"]})).await.unwrap();
|
||||
let old = listed(&app).await;
|
||||
|
||||
// The app takes over, and its first tunnel is number 1 again.
|
||||
assert_eq!(rpc(&app, "take_over", json!({})).await.unwrap(), json!(true));
|
||||
daemon.join().unwrap();
|
||||
rpc(&app, "edit_decrypt_list", json!({"remove": ["host:127.0.0.1"]})).await.unwrap();
|
||||
let (ok, new) = alive(open(app.port().unwrap()).await).await;
|
||||
assert!(ok);
|
||||
rpc(&app, "edit_decrypt_list", json!({"add": ["host:127.0.0.1"]})).await.unwrap();
|
||||
let current = listed(&app).await;
|
||||
assert_ne!(current["id"], old["id"]);
|
||||
assert_ne!(current["flowId"], old["flowId"]);
|
||||
|
||||
let by_id = rpc(&app, "reconnect_tunnels", json!({"ids": [old["id"]]})).await.unwrap();
|
||||
assert_eq!(by_id["closed"], 0);
|
||||
let by_flow = rpc(&app, "reconnect_tunnels", json!({"flowId": old["flowId"]})).await.unwrap();
|
||||
assert_eq!(by_flow["closed"], 0);
|
||||
let (ok, mut new) = alive(new).await;
|
||||
assert!(ok, "the app's tunnel was closed by the CLI's ids");
|
||||
|
||||
// An entry is resolved against what is open now.
|
||||
let by_entry = rpc(&app, "reconnect_tunnels", json!({"entry": "host:127.0.0.1"})).await;
|
||||
assert_eq!(by_entry.unwrap()["closed"], 1);
|
||||
let mut rest = Vec::new();
|
||||
let _ = new.read_to_end(&mut rest).await;
|
||||
app.stop().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_save_dialog_reads_workspaces_previews_and_saves() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -809,9 +906,11 @@ async fn the_decrypt_list_is_read_and_replaced_over_the_control_api() {
|
||||
]),
|
||||
"every built-in exclusion left out is removed"
|
||||
);
|
||||
// Saved, it says how many open connections stay encrypted: none, as none are open.
|
||||
assert_eq!(list["stillEncrypted"], 0);
|
||||
let read: Value =
|
||||
http.get(&url).bearer_auth(&info.token).send().await.unwrap().json().await.unwrap();
|
||||
assert_eq!(read, list);
|
||||
assert_eq!(read["entries"], list["entries"]);
|
||||
|
||||
let bad = http
|
||||
.put(&url)
|
||||
@@ -859,6 +958,82 @@ async fn the_decrypt_list_reaches_the_cli_that_owns_the_engine() {
|
||||
}
|
||||
}
|
||||
|
||||
/// While the CLI owns the engine, the app reads its open tunnels and pass-through set and
|
||||
/// reconnects tunnels there, through the control API.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn open_tunnels_are_reconnected_in_the_cli_that_owns_the_engine() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let client_dir = tempfile::tempdir().unwrap();
|
||||
let cli = ctx(dir.path(), client_dir.path()).with_owner(Owner::Cli);
|
||||
let _server = ControlServer::start(cli.clone()).unwrap();
|
||||
cli.start().unwrap();
|
||||
let app = ctx(dir.path(), client_dir.path());
|
||||
|
||||
// An open tunnel, which the empty list leaves encrypted.
|
||||
let echo = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let echo_port = echo.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut tcp, _) = echo.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut read, mut write) = tcp.split();
|
||||
let _ = tokio::io::copy(&mut read, &mut write).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut tcp = tokio::net::TcpStream::connect(("127.0.0.1", cli.port().unwrap())).await.unwrap();
|
||||
let target = format!("localhost:{echo_port}");
|
||||
tcp.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
tcp.write_all(b"ping").await.unwrap();
|
||||
let mut echoed = [0u8; 4];
|
||||
tcp.read_exact(&mut echoed).await.unwrap();
|
||||
|
||||
rpc(&app, "edit_decrypt_list", json!({"add": ["host:localhost"]})).await.unwrap();
|
||||
// Known once the CLI's event loop has seen it open.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let tunnels = loop {
|
||||
let tunnels = rpc(&app, "list_reconnectable_tunnels", json!({})).await.unwrap();
|
||||
if !tunnels.as_array().unwrap().is_empty() {
|
||||
break tunnels;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "the tunnel never showed");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
};
|
||||
let saved = rpc(&app, "edit_decrypt_list", json!({"add": ["host:localhost"]})).await.unwrap();
|
||||
assert_eq!(saved["stillEncrypted"], 1, "counted where the engine runs");
|
||||
assert_eq!(tunnels.as_array().unwrap().len(), 1);
|
||||
assert_eq!(tunnels[0]["host"], "localhost");
|
||||
let scope = json!({"entry": "host:localhost"});
|
||||
let closed = rpc(&app, "reconnect_tunnels", scope).await.unwrap();
|
||||
assert_eq!(closed["closed"], 1);
|
||||
let mut rest = Vec::new();
|
||||
tcp.read_to_end(&mut rest).await.unwrap();
|
||||
|
||||
let set = rpc(&app, "list_passthrough", json!({})).await.unwrap();
|
||||
assert_eq!(set["addresses"], json!([]));
|
||||
let forgot = rpc(&app, "forget_passthrough", json!({"address": target})).await.unwrap();
|
||||
assert_eq!(forgot, json!({"forgotten": false, "addresses": []}));
|
||||
|
||||
// The routes themselves.
|
||||
let info = control::read(dir.path()).unwrap();
|
||||
let http = reqwest::Client::builder().no_proxy().build().unwrap();
|
||||
let get =
|
||||
|path: &str| http.get(format!("{}{path}", info.base_url())).bearer_auth(&info.token).send();
|
||||
let none: Value =
|
||||
get("/tunnels/reconnectable?entry=host%3Alocalhost").await.unwrap().json().await.unwrap();
|
||||
assert_eq!(none, json!([]));
|
||||
assert_eq!(get("/tunnels/reconnectable?entry=host%3Aa+b").await.unwrap().status(), 400);
|
||||
let set: Value = get("/passthrough").await.unwrap().json().await.unwrap();
|
||||
assert_eq!(set, json!({"addresses": []}));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_decrypt_list_is_edited_over_the_control_api() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! HTTPS decryption through the engine: why each connection was tunnelled, a client's refused
|
||||
//! handshake as a flow, the addresses passed through after it, and the open tunnels the decrypt
|
||||
//! list would decrypt if their clients reconnected.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rustls::pki_types::ServerName;
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio_rustls::TlsConnector;
|
||||
use yaak_proxy_lib::models::{Flow, TunnelReason};
|
||||
use yaak_proxy_lib::settings::ProxySettings;
|
||||
use yaak_proxy_lib::{MasterKeySource, ProxyCtx};
|
||||
use yaak_rpc::{RpcEvent, RpcEventEmitter};
|
||||
|
||||
async fn rpc(ctx: &ProxyCtx, cmd: &str, payload: Value) -> Result<Value, String> {
|
||||
yaak_proxy_lib::build_router().dispatch(cmd, payload, ctx).await.map_err(|e| e.message)
|
||||
}
|
||||
|
||||
/// A started engine with `decrypt` as the list, and the events it sends the app.
|
||||
fn started(decrypt: &[&str]) -> (tempfile::TempDir, ProxyCtx, std::sync::mpsc::Receiver<RpcEvent>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
system_proxy_at_launch: false,
|
||||
decrypt: decrypt.iter().map(|e| e.to_string()).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
ctx.start().unwrap();
|
||||
(dir, ctx, event_rx)
|
||||
}
|
||||
|
||||
/// A TCP server that echoes what it reads, then closes once the client does.
|
||||
async fn spawn_echo() -> SocketAddr {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut tcp, _) = listener.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut read, mut write) = tcp.split();
|
||||
let _ = tokio::io::copy(&mut read, &mut write).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
/// Opens a CONNECT tunnel to `target` through the engine of `ctx`.
|
||||
async fn connect_through(ctx: &ProxyCtx, target: &str) -> TcpStream {
|
||||
let mut tcp = TcpStream::connect(("127.0.0.1", ctx.port().unwrap())).await.unwrap();
|
||||
let connect = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n");
|
||||
tcp.write_all(connect.as_bytes()).await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
assert!(head.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&head));
|
||||
tcp
|
||||
}
|
||||
|
||||
/// A tunnel whose bytes have crossed both ways, so the engine has judged it and is relaying.
|
||||
async fn open_tunnel(ctx: &ProxyCtx, target: &str) -> TcpStream {
|
||||
let mut tcp = connect_through(ctx, target).await;
|
||||
tcp.write_all(b"ping").await.unwrap();
|
||||
let mut echoed = [0u8; 4];
|
||||
tcp.read_exact(&mut echoed).await.unwrap();
|
||||
tcp
|
||||
}
|
||||
|
||||
/// TLS through the engine to `target` from a client that trusts no CA at all, so it refuses the
|
||||
/// engine's certificate with an `unknown_ca` alert.
|
||||
async fn refuse_certificate(ctx: &ProxyCtx, target: &str) {
|
||||
let config =
|
||||
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(RootCertStore::empty())
|
||||
.with_no_client_auth();
|
||||
let tcp = connect_through(ctx, target).await;
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
let tls = TlsConnector::from(Arc::new(config)).connect(name, tcp).await;
|
||||
assert!(tls.is_err(), "trusting nothing, the client refuses the engine's certificate");
|
||||
}
|
||||
|
||||
fn flows(ctx: &ProxyCtx) -> Vec<Flow> {
|
||||
ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap())
|
||||
}
|
||||
|
||||
async fn wait_for(ctx: &ProxyCtx, what: &str, check: impl Fn(&Flow) -> bool) -> Flow {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if let Some(flow) = flows(ctx).into_iter().find(|f| check(f)) {
|
||||
return flow;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no flow {what}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until `check` holds of what `list_reconnectable_tunnels` returns for `scope`.
|
||||
async fn wait_for_tunnels(ctx: &ProxyCtx, scope: Value, check: impl Fn(&[Value]) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let tunnels = rpc(ctx, "list_reconnectable_tunnels", scope.clone()).await.unwrap();
|
||||
if check(tunnels.as_array().unwrap()) {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "tunnels for {scope} stayed {tunnels}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn reconnectable(ctx: &ProxyCtx, scope: Value) -> Vec<Value> {
|
||||
let tunnels = rpc(ctx, "list_reconnectable_tunnels", scope).await.unwrap();
|
||||
tunnels.as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_tunnel_records_why_it_was_not_decrypted() {
|
||||
let (_dir, ctx, _events) = started(&["host:localhost", "!host:localhost"]);
|
||||
let echo = spawn_echo().await;
|
||||
|
||||
// Nothing names 127.0.0.1.
|
||||
let _plain = open_tunnel(&ctx, &format!("127.0.0.1:{}", echo.port())).await;
|
||||
let url = format!("https://127.0.0.1:{}", echo.port());
|
||||
let flow = wait_for(&ctx, "to 127.0.0.1", |f| f.url == url).await;
|
||||
assert_eq!(flow.tunnel_reason, Some(TunnelReason::NotListed));
|
||||
assert_eq!((flow.tunnel_excluded_by, flow.tunnel_rejected_by), (None, None));
|
||||
|
||||
// The person's exclusion beats their entry.
|
||||
let _excluded = open_tunnel(&ctx, &format!("localhost:{}", echo.port())).await;
|
||||
let url = format!("https://localhost:{}", echo.port());
|
||||
let flow = wait_for(&ctx, "to localhost", |f| f.url == url).await;
|
||||
assert_eq!(flow.tunnel_reason, Some(TunnelReason::Excluded));
|
||||
assert_eq!(flow.tunnel_excluded_by.as_deref(), Some("!host:localhost"));
|
||||
assert!(!flow.tunnel_excluded_built_in);
|
||||
|
||||
let encrypted = rpc(&ctx, "list_flows", json!({"query": "@is:encrypted"})).await.unwrap();
|
||||
assert_eq!(encrypted["flows"].as_array().unwrap().len(), 2);
|
||||
let flow = &encrypted["flows"][0];
|
||||
assert_eq!(flow["tunnelReason"], "excluded");
|
||||
assert_eq!(flow["tunnelExcludedBy"], "!host:localhost");
|
||||
}
|
||||
|
||||
/// A client refusing the certificate is one flow per address, however many refuse together,
|
||||
/// and the tunnels passed through after it name it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_refused_handshake_is_one_flow_per_address() {
|
||||
let (_dir, ctx, events) = started(&["*"]);
|
||||
let echo = spawn_echo().await;
|
||||
let target = format!("localhost:{}", echo.port());
|
||||
let url = format!("https://{target}");
|
||||
|
||||
refuse_certificate(&ctx, &target).await;
|
||||
let rejected = wait_for(&ctx, "refused", |f| f.tls_rejected.is_some()).await;
|
||||
assert_eq!(rejected.url, url);
|
||||
assert_eq!(rejected.method, "");
|
||||
assert_eq!(rejected.tls_rejected.as_deref(), Some("unknown_ca"));
|
||||
assert_eq!(rejected.error.as_deref(), Some("Rejected the proxy's certificate"));
|
||||
assert!(!rejected.tunnelled);
|
||||
assert!(rejected.elapsed_ms.is_some(), "ended, not pending");
|
||||
// No request was sent, so there is none to save.
|
||||
let preview = rpc(&ctx, "preview_save", json!({"flowId": rejected.id})).await;
|
||||
assert!(preview.unwrap_err().starts_with("Not a request"));
|
||||
|
||||
// Passed through from now on, naming the refusal.
|
||||
let _tunnel = open_tunnel(&ctx, &target).await;
|
||||
let tunnel = wait_for(&ctx, "passed through", |f| f.tunnelled && f.url == url).await;
|
||||
assert_eq!(tunnel.tunnel_reason, Some(TunnelReason::Rejected));
|
||||
assert_eq!(tunnel.tunnel_rejected_by.as_deref(), Some(rejected.id.as_str()));
|
||||
// It would be passed through again, so it is no tunnel to reconnect.
|
||||
assert!(reconnectable(&ctx, json!({})).await.is_empty());
|
||||
|
||||
// Several refusing at once to another address make one flow too.
|
||||
let other = format!("127.0.0.1:{}", echo.port());
|
||||
let mut tunnels = Vec::new();
|
||||
for _ in 0..6 {
|
||||
tunnels.push(connect_through(&ctx, &other).await);
|
||||
}
|
||||
let config = Arc::new(
|
||||
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(RootCertStore::empty())
|
||||
.with_no_client_auth(),
|
||||
);
|
||||
let attempts: Vec<_> = tunnels
|
||||
.into_iter()
|
||||
.map(|tcp| {
|
||||
let connector = TlsConnector::from(config.clone());
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
tokio::spawn(async move { connector.connect(name, tcp).await.map(drop) })
|
||||
})
|
||||
.collect();
|
||||
for attempt in attempts {
|
||||
let _ = attempt.await.unwrap();
|
||||
}
|
||||
let other_url = format!("https://{other}");
|
||||
wait_for(&ctx, "refused at once", |f| f.url == other_url && f.tls_rejected.is_some()).await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let refused: Vec<Flow> = flows(&ctx).into_iter().filter(|f| f.tls_rejected.is_some()).collect();
|
||||
assert_eq!(refused.len(), 2, "one for each address: {refused:#?}");
|
||||
let listed = rpc(&ctx, "list_flows", json!({"query": "@is:rejected"})).await.unwrap();
|
||||
assert_eq!(listed["flows"].as_array().unwrap().len(), 2);
|
||||
|
||||
// The set, read and changed.
|
||||
let set = rpc(&ctx, "list_passthrough", json!({})).await.unwrap();
|
||||
assert_eq!(set["addresses"], json!([other, target]));
|
||||
let pushed: Vec<RpcEvent> =
|
||||
events.try_iter().filter(|e| e.event == "passthrough_changed").collect();
|
||||
assert_eq!(pushed.len(), 2, "one push as each address was added");
|
||||
assert_eq!(pushed[1].payload["addresses"], json!([other, target]));
|
||||
|
||||
// Forgotten, by the flow's authority, the address is intercepted again, and a refusal is
|
||||
// another flow.
|
||||
let forgot = rpc(&ctx, "forget_passthrough", json!({"address": target})).await.unwrap();
|
||||
assert_eq!(forgot, json!({"forgotten": true, "addresses": [other]}));
|
||||
let pushed: Vec<RpcEvent> =
|
||||
events.try_iter().filter(|e| e.event == "passthrough_changed").collect();
|
||||
assert_eq!(pushed.len(), 1);
|
||||
assert_eq!(pushed[0].payload["addresses"], json!([other]));
|
||||
// Its tunnel still open would now be decrypted if it reconnected.
|
||||
let open = reconnectable(&ctx, json!({"flowId": tunnel.id})).await;
|
||||
assert_eq!(open.len(), 1, "forgotten, its tunnel counts again");
|
||||
let again = rpc(&ctx, "forget_passthrough", json!({"address": target})).await.unwrap();
|
||||
assert_eq!(again["forgotten"], false);
|
||||
assert!(rpc(&ctx, "forget_passthrough", json!({"address": ""})).await.is_err());
|
||||
refuse_certificate(&ctx, &target).await;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while flows(&ctx).iter().filter(|f| f.url == url && f.tls_rejected.is_some()).count() < 2 {
|
||||
assert!(Instant::now() < deadline, "no second refusal");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open tunnels are kept whether or not flows are recorded; saving the list closes none of
|
||||
/// them but counts those it would decrypt, and reconnecting closes them by flow, by entry or
|
||||
/// all at once.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn open_tunnels_are_reconnected_only_when_asked() {
|
||||
let (_dir, ctx, _events) = started(&[]);
|
||||
let echo = spawn_echo().await;
|
||||
let local = format!("localhost:{}", echo.port());
|
||||
let loopback = format!("127.0.0.1:{}", echo.port());
|
||||
|
||||
let mut a = open_tunnel(&ctx, &local).await;
|
||||
let a_flow = wait_for(&ctx, "a", |f| f.url == format!("https://{local}")).await;
|
||||
let mut b = open_tunnel(&ctx, &loopback).await;
|
||||
let b_flow = wait_for(&ctx, "b", |f| f.url == format!("https://{loopback}")).await;
|
||||
// Paused, a tunnel has no flow, and is kept all the same.
|
||||
rpc(&ctx, "set_recording", json!({"enabled": false})).await.unwrap();
|
||||
let mut c = open_tunnel(&ctx, &local).await;
|
||||
|
||||
// Nothing is listed, so nothing would be decrypted.
|
||||
assert!(reconnectable(&ctx, json!({})).await.is_empty());
|
||||
let saved = rpc(&ctx, "edit_decrypt_list", json!({"add": ["host:localhost"]})).await.unwrap();
|
||||
assert!(saved["stillEncrypted"].as_u64().unwrap() <= 2);
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.len() == 2).await;
|
||||
let listed = reconnectable(&ctx, json!({})).await;
|
||||
assert_eq!(listed[0]["flowId"], json!(a_flow.id));
|
||||
assert_eq!(listed[0]["host"], "localhost");
|
||||
assert_eq!(listed[0]["port"], echo.port());
|
||||
assert_eq!(listed[0]["reason"], "not_listed");
|
||||
assert_eq!(listed[1]["flowId"], Value::Null, "opened while paused");
|
||||
|
||||
// Saving counts what stays encrypted, and closes nothing.
|
||||
let saved = rpc(&ctx, "edit_decrypt_list", json!({"add": ["127.0.0.1"]})).await.unwrap();
|
||||
assert_eq!(saved["stillEncrypted"], 3);
|
||||
for tcp in [&mut a, &mut b, &mut c] {
|
||||
tcp.write_all(b"ping").await.unwrap();
|
||||
let mut echoed = [0u8; 4];
|
||||
tcp.read_exact(&mut echoed).await.unwrap();
|
||||
}
|
||||
|
||||
// Narrowed to an entry, or to a flow.
|
||||
let entry = reconnectable(&ctx, json!({"entry": "host:127.0.0.1"})).await;
|
||||
assert_eq!(entry.len(), 1);
|
||||
assert_eq!(entry[0]["flowId"], json!(b_flow.id));
|
||||
assert_eq!(reconnectable(&ctx, json!({"flowId": a_flow.id})).await.len(), 1);
|
||||
assert!(rpc(&ctx, "list_reconnectable_tunnels", json!({"entry": "host:a b"})).await.is_err());
|
||||
|
||||
// By flow.
|
||||
let closed = rpc(&ctx, "reconnect_tunnels", json!({"flowId": a_flow.id})).await.unwrap();
|
||||
assert_eq!(closed, json!({"closed": 1}));
|
||||
let mut rest = Vec::new();
|
||||
a.read_to_end(&mut rest).await.unwrap();
|
||||
let ended = wait_for(&ctx, "a ended", |f| f.id == a_flow.id && f.elapsed_ms.is_some()).await;
|
||||
assert!(ended.reconnect_requested);
|
||||
assert_eq!(ended.error, None);
|
||||
|
||||
// By entry.
|
||||
let closed = rpc(&ctx, "reconnect_tunnels", json!({"entry": "127.0.0.1"})).await.unwrap();
|
||||
assert_eq!(closed["closed"], 1);
|
||||
b.read_to_end(&mut rest).await.unwrap();
|
||||
let ended = wait_for(&ctx, "b ended", |f| f.id == b_flow.id && f.elapsed_ms.is_some()).await;
|
||||
assert!(ended.reconnect_requested);
|
||||
|
||||
// All, and by id what is closed already.
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.len() == 1).await;
|
||||
let id = reconnectable(&ctx, json!({})).await[0]["id"].clone();
|
||||
let closed = rpc(&ctx, "reconnect_tunnels", json!({})).await.unwrap();
|
||||
assert_eq!(closed["closed"], 1);
|
||||
c.read_to_end(&mut rest).await.unwrap();
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.is_empty()).await;
|
||||
let closed = rpc(&ctx, "reconnect_tunnels", json!({"ids": [id]})).await.unwrap();
|
||||
assert_eq!(closed["closed"], 0);
|
||||
|
||||
// An id listed before the engine restarted closes nothing after, though the new run
|
||||
// numbers its tunnels from 1 again. Each is opened while its host is unlisted.
|
||||
let unlisted = || rpc(&ctx, "edit_decrypt_list", json!({"remove": ["host:127.0.0.1"]}));
|
||||
let listed = || rpc(&ctx, "edit_decrypt_list", json!({"add": ["host:127.0.0.1"]}));
|
||||
unlisted().await.unwrap();
|
||||
let mut d = open_tunnel(&ctx, &loopback).await;
|
||||
listed().await.unwrap();
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.len() == 1).await;
|
||||
let old = reconnectable(&ctx, json!({})).await[0]["id"].clone();
|
||||
ctx.stop().unwrap();
|
||||
// Stopped, nothing is open, at once, whatever its event loop has still to read.
|
||||
assert!(reconnectable(&ctx, json!({})).await.is_empty());
|
||||
assert_eq!(listed().await.unwrap()["stillEncrypted"], 0);
|
||||
assert_eq!(rpc(&ctx, "reconnect_tunnels", json!({"ids": [old]})).await.unwrap()["closed"], 0);
|
||||
assert_eq!(rpc(&ctx, "list_passthrough", json!({})).await.unwrap()["addresses"], json!([]));
|
||||
let forgot = rpc(&ctx, "forget_passthrough", json!({"address": "localhost"})).await.unwrap();
|
||||
assert_eq!(forgot, json!({"forgotten": false, "addresses": []}));
|
||||
d.read_to_end(&mut rest).await.unwrap();
|
||||
ctx.start().unwrap();
|
||||
unlisted().await.unwrap();
|
||||
let mut e = open_tunnel(&ctx, &loopback).await;
|
||||
listed().await.unwrap();
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.len() == 1).await;
|
||||
assert_ne!(reconnectable(&ctx, json!({})).await[0]["id"], old);
|
||||
let closed = rpc(&ctx, "reconnect_tunnels", json!({"ids": [old]})).await.unwrap();
|
||||
assert_eq!(closed["closed"], 0);
|
||||
e.write_all(b"ping").await.unwrap();
|
||||
let mut echoed = [0u8; 4];
|
||||
e.read_exact(&mut echoed).await.unwrap();
|
||||
}
|
||||
|
||||
/// Dropping the last context stops its engine, which its event loop does not keep alive.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn dropping_the_context_stops_the_engine() {
|
||||
let (_dir, ctx, _events) = started(&[]);
|
||||
let port = ctx.port().unwrap();
|
||||
drop(ctx);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
|
||||
assert!(Instant::now() < deadline, "the engine still listens on {port}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A tunnel that ends on its own is no longer open, and is not marked for a reconnect.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_closed_tunnel_leaves_the_registry() {
|
||||
let (_dir, ctx, _events) = started(&["*"]);
|
||||
let echo = spawn_echo().await;
|
||||
// Kept out by the built-in exclusions' rival, an exclusion of the person's.
|
||||
rpc(&ctx, "edit_decrypt_list", json!({"add": ["!host:localhost"]})).await.unwrap();
|
||||
let tcp = open_tunnel(&ctx, &format!("localhost:{}", echo.port())).await;
|
||||
let url = format!("https://localhost:{}", echo.port());
|
||||
wait_for(&ctx, "open", |f| f.url == url).await;
|
||||
let saved = rpc(&ctx, "edit_decrypt_list", json!({"remove": ["!host:localhost"]})).await;
|
||||
assert_eq!(saved.unwrap()["stillEncrypted"], 1);
|
||||
drop(tcp);
|
||||
let ended = wait_for(&ctx, "ended", |f| f.url == url && f.elapsed_ms.is_some()).await;
|
||||
assert!(!ended.reconnect_requested);
|
||||
wait_for_tunnels(&ctx, json!({}), |t| t.is_empty()).await;
|
||||
}
|
||||
@@ -530,16 +530,17 @@ async fn the_decrypt_list_rpcs_save_and_apply() {
|
||||
json!([
|
||||
{"entry": "host:api.example.com", "builtIn": false},
|
||||
{"entry": "app:Google Chrome", "builtIn": false},
|
||||
{"entry": "!host:*.apple.com", "builtIn": true},
|
||||
{"entry": "!host:*.apple.com", "builtIn": true, "kind": "apple"},
|
||||
])
|
||||
);
|
||||
assert_eq!(list["stillEncrypted"], 0);
|
||||
let saved = ProxySettings::load(&dir.path().join("settings.json")).unwrap();
|
||||
assert_eq!(saved.decrypt, ["host:api.example.com", "app:Google Chrome"]);
|
||||
assert!(saved.decrypt_built_ins_removed.contains(&"!host:*.icloud.com".to_string()));
|
||||
|
||||
let invalid = rpc(&ctx, "set_decrypt_list", json!({"entries": ["host:a b"]})).await;
|
||||
assert!(invalid.unwrap_err().contains("Invalid host"));
|
||||
assert_eq!(rpc(&ctx, "get_decrypt_list", json!({})).await.unwrap(), list);
|
||||
assert_eq!(rpc(&ctx, "get_decrypt_list", json!({})).await.unwrap()["entries"], list["entries"]);
|
||||
|
||||
// Applied to the running engine's next connection: decrypting everything intercepts a
|
||||
// CONNECT, which a client that does not trust the CA then rejects.
|
||||
@@ -629,7 +630,7 @@ async fn decrypt_list_edits_apply_to_the_latest_list_and_are_announced() {
|
||||
let changes: Vec<_> =
|
||||
event_rx.try_iter().filter(|e| e.event == "decrypt_list_changed").collect();
|
||||
assert_eq!(changes.len(), 3);
|
||||
assert_eq!(changes[2].payload["list"], list);
|
||||
assert_eq!(changes[2].payload["list"]["entries"], list["entries"]);
|
||||
}
|
||||
|
||||
/// Capture throughput through the engine, end to end: 3,000 requests, 16 at a time over
|
||||
|
||||
@@ -14,29 +14,52 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Hosts excluded by default: Apple's own services, which macOS daemons reach with pinned
|
||||
/// certificates, and the sync hosts of common apps that pin theirs. Each is removable.
|
||||
pub const BUILT_IN_EXCLUSIONS: &[&str] = &[
|
||||
"!host:*.apple.com",
|
||||
"!host:*.icloud.com",
|
||||
"!host:*.mzstatic.com",
|
||||
"!host:*.apple-cloudkit.com",
|
||||
"!host:*.icloud-content.com",
|
||||
"!host:*.cdn-apple.com",
|
||||
/// Why a built-in exclusion ships: Apple's own services, which macOS daemons reach with pinned
|
||||
/// certificates, or the sync hosts of a common app that pins its certificates.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum BuiltInKind {
|
||||
Apple,
|
||||
Pinned,
|
||||
}
|
||||
|
||||
impl BuiltInKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Apple => "apple",
|
||||
Self::Pinned => "pinned",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts excluded by default, each with why: Apple's own services, and the sync hosts of common
|
||||
/// apps that pin their certificates. Each is removable.
|
||||
pub const BUILT_IN_EXCLUSIONS: &[(&str, BuiltInKind)] = &[
|
||||
("!host:*.apple.com", BuiltInKind::Apple),
|
||||
("!host:*.icloud.com", BuiltInKind::Apple),
|
||||
("!host:*.mzstatic.com", BuiltInKind::Apple),
|
||||
("!host:*.apple-cloudkit.com", BuiltInKind::Apple),
|
||||
("!host:*.icloud-content.com", BuiltInKind::Apple),
|
||||
("!host:*.cdn-apple.com", BuiltInKind::Apple),
|
||||
// Push and FaceTime, kept apart so they stay excluded without the rest of apple.com.
|
||||
"!host:*.push.apple.com",
|
||||
"!host:*.ess.apple.com",
|
||||
"!host:*.1password.com",
|
||||
"!host:*.1password.ca",
|
||||
"!host:*.1password.eu",
|
||||
"!host:*.signal.org",
|
||||
"!host:*.whispersystems.org",
|
||||
"!host:*.dropboxapi.com",
|
||||
"!host:client*.dropbox.com",
|
||||
"!host:bolt.dropbox.com",
|
||||
"!host:*.zoom.us",
|
||||
("!host:*.push.apple.com", BuiltInKind::Apple),
|
||||
("!host:*.ess.apple.com", BuiltInKind::Apple),
|
||||
("!host:*.1password.com", BuiltInKind::Pinned),
|
||||
("!host:*.1password.ca", BuiltInKind::Pinned),
|
||||
("!host:*.1password.eu", BuiltInKind::Pinned),
|
||||
("!host:*.signal.org", BuiltInKind::Pinned),
|
||||
("!host:*.whispersystems.org", BuiltInKind::Pinned),
|
||||
("!host:*.dropboxapi.com", BuiltInKind::Pinned),
|
||||
("!host:client*.dropbox.com", BuiltInKind::Pinned),
|
||||
("!host:bolt.dropbox.com", BuiltInKind::Pinned),
|
||||
("!host:*.zoom.us", BuiltInKind::Pinned),
|
||||
];
|
||||
|
||||
/// The kind of the built-in exclusion `entry` is, as stored (`!host:*.apple.com`), or None when
|
||||
/// it is not one.
|
||||
pub fn built_in_kind(entry: &str) -> Option<BuiltInKind> {
|
||||
BUILT_IN_EXCLUSIONS.iter().find(|(e, _)| *e == entry).map(|(_, kind)| *kind)
|
||||
}
|
||||
|
||||
/// What an entry matches.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DecryptTarget {
|
||||
@@ -83,7 +106,7 @@ impl DecryptEntry {
|
||||
parse_host(host).ok_or_else(|| format!("Invalid host in decrypt entry {input:?}"))?
|
||||
};
|
||||
let mut entry = Self { negated, target, built_in: false };
|
||||
entry.built_in = BUILT_IN_EXCLUSIONS.contains(&entry.to_string().as_str());
|
||||
entry.built_in = built_in_kind(&entry.to_string()).is_some();
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
@@ -252,6 +275,12 @@ impl DecryptPolicy {
|
||||
/// Whether to decrypt `conn`: a positive entry matches and no negative one excludes it. A
|
||||
/// built-in exclusion yields to a positive entry at least as specific as itself.
|
||||
pub fn decrypts(&self, conn: &DecryptQuery) -> bool {
|
||||
self.judge(conn) == Verdict::Decrypt
|
||||
}
|
||||
|
||||
/// [`Self::decrypts`], saying why not: no positive entry matches, or an exclusion keeps it
|
||||
/// out, the first in the list that does.
|
||||
pub fn judge(&self, conn: &DecryptQuery) -> Verdict {
|
||||
let Some(best) = self
|
||||
.entries
|
||||
.iter()
|
||||
@@ -259,12 +288,34 @@ impl DecryptPolicy {
|
||||
.map(DecryptEntry::specificity)
|
||||
.max()
|
||||
else {
|
||||
return false;
|
||||
return Verdict::NotListed;
|
||||
};
|
||||
!self
|
||||
match self
|
||||
.entries
|
||||
.iter()
|
||||
.any(|e| e.negated && e.matches(conn) && (!e.built_in || e.specificity() > best))
|
||||
.find(|e| e.negated && e.matches(conn) && (!e.built_in || e.specificity() > best))
|
||||
{
|
||||
Some(exclusion) => Verdict::Excluded(exclusion.clone()),
|
||||
None => Verdict::Decrypt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the policy makes of a connection.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Decrypt,
|
||||
/// No positive entry matches it.
|
||||
NotListed,
|
||||
/// A positive entry matches it, and this exclusion keeps it out.
|
||||
Excluded(DecryptEntry),
|
||||
}
|
||||
|
||||
impl DecryptEntry {
|
||||
/// Whether the entry names `conn`, read without its `!`: the connections it decrypts, or,
|
||||
/// for an exclusion, the ones it keeps out.
|
||||
pub fn covers(&self, conn: &DecryptQuery) -> bool {
|
||||
self.matches(conn)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +338,7 @@ mod tests {
|
||||
|
||||
fn with_built_ins(entries: &[&str]) -> DecryptPolicy {
|
||||
let mut all: Vec<&str> = entries.to_vec();
|
||||
all.extend(BUILT_IN_EXCLUSIONS);
|
||||
all.extend(BUILT_IN_EXCLUSIONS.iter().map(|(e, _)| *e));
|
||||
policy(&all)
|
||||
}
|
||||
|
||||
@@ -384,10 +435,53 @@ mod tests {
|
||||
assert!(with_built_ins(&["app:Safari"]).decrypts(&safari));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_verdict_says_why_not() {
|
||||
let p = with_built_ins(&["*", "!host:secret.example.com"]);
|
||||
assert_eq!(p.judge(&to("api.example.com", 443)), Verdict::Decrypt);
|
||||
let Verdict::Excluded(by) = p.judge(&to("secret.example.com", 443)) else {
|
||||
panic!("not excluded");
|
||||
};
|
||||
assert_eq!((by.to_string().as_str(), by.built_in), ("!host:secret.example.com", false));
|
||||
let Verdict::Excluded(by) = p.judge(&to("gateway.icloud.com", 443)) else {
|
||||
panic!("not excluded");
|
||||
};
|
||||
assert_eq!((by.to_string().as_str(), by.built_in), ("!host:*.icloud.com", true));
|
||||
assert_eq!(with_built_ins(&["host:a.com"]).judge(&to("b.com", 443)), Verdict::NotListed);
|
||||
assert_eq!(policy(&[]).judge(&to("b.com", 443)), Verdict::NotListed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn built_in_kinds() {
|
||||
assert_eq!(built_in_kind("!host:*.apple.com"), Some(BuiltInKind::Apple));
|
||||
assert_eq!(built_in_kind("!host:*.1password.com"), Some(BuiltInKind::Pinned));
|
||||
assert_eq!(built_in_kind("!host:*.example.com"), None);
|
||||
assert_eq!(built_in_kind("host:*.apple.com"), None);
|
||||
// Every one parses back to itself and reads as built in.
|
||||
for (entry, _) in BUILT_IN_EXCLUSIONS {
|
||||
let parsed = DecryptEntry::parse(entry).unwrap();
|
||||
assert!(parsed.built_in && parsed.negated, "{entry}");
|
||||
assert_eq!(parsed.to_string(), *entry);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_covers_what_it_names_either_way() {
|
||||
let exclusion = DecryptEntry::parse("!host:*.chase.com").unwrap();
|
||||
assert!(exclusion.covers(&to("www.chase.com", 443)));
|
||||
assert!(!exclusion.covers(&to("www.example.com", 443)));
|
||||
let app = DecryptEntry::parse("app:Dia").unwrap();
|
||||
assert!(app.covers(&from_app("a.com", "Dia", None)));
|
||||
assert!(!app.covers(&to("a.com", 443)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_exclusion_no_longer_applies() {
|
||||
let kept: Vec<&str> =
|
||||
BUILT_IN_EXCLUSIONS.iter().copied().filter(|e| *e != "!host:*.zoom.us").collect();
|
||||
let kept: Vec<&str> = BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.map(|(e, _)| *e)
|
||||
.filter(|e| *e != "!host:*.zoom.us")
|
||||
.collect();
|
||||
let mut entries = vec!["*"];
|
||||
entries.extend(kept);
|
||||
let p = policy(&entries);
|
||||
|
||||
+116
-18
@@ -12,8 +12,8 @@ mod sse;
|
||||
mod tunnel;
|
||||
mod ws;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
@@ -34,13 +34,15 @@ use tokio::net::TcpListener;
|
||||
pub use cert::{CaStore, KeyCipher};
|
||||
use connection::handle_connection;
|
||||
pub use decrypt::{
|
||||
BUILT_IN_EXCLUSIONS, DecryptApp, DecryptEntry, DecryptPolicy, DecryptQuery, DecryptTarget,
|
||||
BUILT_IN_EXCLUSIONS, BuiltInKind, DecryptApp, DecryptEntry, DecryptPolicy, DecryptQuery,
|
||||
DecryptTarget, Verdict, built_in_kind,
|
||||
};
|
||||
pub use grpc::{detect as detect_grpc, service_and_method};
|
||||
pub use messages::{MessageDirection, MessageKind, RAW_LIMIT, StreamKind, StreamMessage};
|
||||
use request::BoxBody;
|
||||
|
||||
const PASSTHROUGH_AFTER_FAILURES: u32 = 2;
|
||||
/// Hang-ups and other handshake errors in a row that pass an address through.
|
||||
pub const PASSTHROUGH_AFTER_FAILURES: u32 = 2;
|
||||
|
||||
/// Default for [`ProxyConfig::capture_body_limit`]: 10 MB.
|
||||
pub const DEFAULT_CAPTURE_BODY_LIMIT: usize = 10 * 1024 * 1024;
|
||||
@@ -103,8 +105,10 @@ impl ProxyConfig {
|
||||
/// server-sent events, gRPC) has a `StreamStart` and then a `Message` for each message as it
|
||||
/// passes. An HTTPS connection the engine tunnels without decrypting, because the decrypt policy
|
||||
/// leaves it out or its client rejected the engine's certificate, is a flow of its own, from
|
||||
/// `TunnelStart` to `TunnelEnd`. Other traffic tunnelled blind (non-TLS CONNECT payloads,
|
||||
/// upgrades to protocols other than WebSocket) produces no events.
|
||||
/// `TunnelStart` to `TunnelEnd`. A client's failed handshake that starts its address being
|
||||
/// passed through is a flow too, of the one event `HandshakeFailed`. Other traffic tunnelled
|
||||
/// blind (non-TLS CONNECT payloads, upgrades to protocols other than WebSocket) produces no
|
||||
/// events.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ProxyEvent {
|
||||
/// Request headers arrived from the client.
|
||||
@@ -215,14 +219,19 @@ pub enum ProxyEvent {
|
||||
error: Option<String>,
|
||||
},
|
||||
/// A CONNECT is tunnelled without being decrypted: its bytes pass untouched, and only their
|
||||
/// count is recorded.
|
||||
/// count is recorded. Open until its `TunnelEnd`; [`ProxyHandle::close_tunnels`] closes it
|
||||
/// by `id`.
|
||||
TunnelStart {
|
||||
id: u64,
|
||||
started_at: SystemTime,
|
||||
/// `host[:port]`, the port left out when it is 443.
|
||||
authority: String,
|
||||
/// The host, without an IPv6 address's brackets, and the port, as the policy judged them.
|
||||
host: String,
|
||||
port: u16,
|
||||
connection: u64,
|
||||
client_addr: SocketAddr,
|
||||
reason: TunnelReason,
|
||||
},
|
||||
/// The tunnel closed, with `error` when connecting upstream or relaying failed.
|
||||
TunnelEnd {
|
||||
@@ -233,7 +242,42 @@ pub enum ProxyEvent {
|
||||
received: u64,
|
||||
elapsed_ms: u64,
|
||||
error: Option<String>,
|
||||
/// Closed by [`ProxyHandle::close_tunnels`], so the client reconnects.
|
||||
reconnect_requested: bool,
|
||||
},
|
||||
/// A client's TLS handshake with the engine failed, and its address (`host:port`) is now
|
||||
/// passed through: sent once per address each time it joins the pass-through set, not for
|
||||
/// every failure. At once for a certificate alert; after [`PASSTHROUGH_AFTER_FAILURES`] in a
|
||||
/// row for a hang-up or any other handshake error. A flow of its own, which nothing follows.
|
||||
HandshakeFailed {
|
||||
id: u64,
|
||||
started_at: SystemTime,
|
||||
/// `host[:port]`, the port left out when it is 443.
|
||||
authority: String,
|
||||
connection: u64,
|
||||
client_addr: SocketAddr,
|
||||
/// How the client rejected the engine's certificate: its alert (`unknown_ca`,
|
||||
/// `bad_certificate`, `certificate_unknown`, ...) or `hang_up`. None for any other
|
||||
/// handshake error, which is not a rejection.
|
||||
rejection: Option<String>,
|
||||
/// The error the handshake ended with.
|
||||
error: String,
|
||||
/// Milliseconds from `started_at` to the failure.
|
||||
elapsed_ms: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Why a CONNECT is tunnelled rather than decrypted.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TunnelReason {
|
||||
/// No positive entry of the decrypt list matches it.
|
||||
NotListed,
|
||||
/// A positive entry matches it, and this exclusion keeps it out.
|
||||
Excluded { entry: String, built_in: bool },
|
||||
/// The policy decrypts it, but a client rejected the engine's certificate for its address,
|
||||
/// which is passed through for the rest of the run: `rejected_by` is the id of the
|
||||
/// `HandshakeFailed` flow that started it.
|
||||
Rejected { rejected_by: u64 },
|
||||
}
|
||||
|
||||
/// A running engine. Dropping it stops the listener and joins its thread.
|
||||
@@ -259,6 +303,34 @@ impl ProxyHandle {
|
||||
self.engine.handshake_failures.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
/// Forgets one address (`host:port`) passed through after a client rejected the CA, so its
|
||||
/// next connection is intercepted again. Returns whether it was passed through.
|
||||
pub fn forget_passthrough_address(&self, addr: &str) -> bool {
|
||||
self.engine.handshake_failures.lock().unwrap().remove(addr);
|
||||
self.engine.passthrough.lock().unwrap().remove(addr).is_some()
|
||||
}
|
||||
|
||||
/// The addresses (`host:port`) passed through after clients rejected the CA, sorted.
|
||||
pub fn passthrough(&self) -> Vec<String> {
|
||||
let mut addrs: Vec<String> =
|
||||
self.engine.passthrough.lock().unwrap().keys().cloned().collect();
|
||||
addrs.sort();
|
||||
addrs
|
||||
}
|
||||
|
||||
/// Closes the open tunnels among `ids`, the `id`s of their `TunnelStart`s, so their clients
|
||||
/// reconnect. Each ends with a `TunnelEnd` whose `reconnect_requested` is set. Returns how
|
||||
/// many were open.
|
||||
pub fn close_tunnels(&self, ids: &[u64]) -> usize {
|
||||
let mut tunnels = self.engine.tunnels.lock().unwrap();
|
||||
ids.iter()
|
||||
.filter_map(|id| tunnels.remove(id))
|
||||
.map(|close| {
|
||||
let _ = close.send(());
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Offers HTTP/2 to clients, or stops, from the next connection on. Connections already
|
||||
/// open keep the protocol they chose.
|
||||
pub fn set_http2(&self, enabled: bool) {
|
||||
@@ -312,8 +384,12 @@ pub(crate) struct Engine {
|
||||
http_client: HttpClient,
|
||||
upstream_tls: Arc<ClientConfig>,
|
||||
upstream_tls_h1: Arc<ClientConfig>,
|
||||
passthrough: Mutex<HashSet<String>>,
|
||||
/// Addresses (`host:port`) passed through after a client rejected the engine's certificate,
|
||||
/// each with the id of the `HandshakeFailed` flow that started it.
|
||||
passthrough: Mutex<HashMap<String, u64>>,
|
||||
handshake_failures: Mutex<HashMap<String, u32>>,
|
||||
/// Each open tunnel's way to close it, by its flow id. Touched as tunnels open and close.
|
||||
tunnels: Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>,
|
||||
/// Offer HTTP/2 to clients in intercepted TLS.
|
||||
http2: AtomicBool,
|
||||
websocket_capture: bool,
|
||||
@@ -346,12 +422,12 @@ impl Engine {
|
||||
self.decrypt.read().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Whether the policy decrypts a CONNECT to `host:port` on `connection`, looking up its app
|
||||
/// What the policy makes of a CONNECT to `host:port` on `connection`, looking up its app
|
||||
/// only when an entry names one.
|
||||
async fn decrypts(&self, host: &str, port: u16, connection: u64) -> bool {
|
||||
async fn verdict(&self, host: &str, port: u16, connection: u64) -> Verdict {
|
||||
let policy = self.decrypt_policy();
|
||||
if !policy.decrypts_anything() {
|
||||
return false;
|
||||
return Verdict::NotListed;
|
||||
}
|
||||
let app = match &self.app_of {
|
||||
Some(app_of) if policy.needs_app() => {
|
||||
@@ -360,16 +436,29 @@ impl Engine {
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
policy.decrypts(&DecryptQuery { host: host.to_string(), port, app })
|
||||
policy.judge(&DecryptQuery { host: host.to_string(), port, app })
|
||||
}
|
||||
|
||||
/// The id of the `HandshakeFailed` flow that started passing `addr` through, while it is.
|
||||
fn passthrough_of(&self, addr: &str) -> Option<u64> {
|
||||
self.passthrough.lock().unwrap().get(addr).copied()
|
||||
}
|
||||
|
||||
fn is_passthrough(&self, addr: &str) -> bool {
|
||||
self.passthrough.lock().unwrap().contains(addr)
|
||||
self.passthrough_of(addr).is_some()
|
||||
}
|
||||
|
||||
/// Returns whether `addr` is now passed through. macOS and Windows clients reject the CA with
|
||||
/// a bare hang-up, indistinguishable from an abandoned connection, so those need two in a row.
|
||||
fn record_handshake_failure(&self, addr: &str, certificate_rejected: bool) -> bool {
|
||||
/// Counts a failed handshake toward passing `addr` through. macOS and Windows clients reject
|
||||
/// the CA with a bare hang-up, indistinguishable from an abandoned connection, so those need
|
||||
/// two in a row. When this failure is the one that adds `addr` to the pass-through set, which
|
||||
/// happens once however many fail together, emits `failed` with a new flow id, before any
|
||||
/// tunnel passed through for it can name that id, and returns true.
|
||||
fn record_handshake_failure(
|
||||
&self,
|
||||
addr: &str,
|
||||
certificate_rejected: bool,
|
||||
failed: impl FnOnce(u64) -> ProxyEvent,
|
||||
) -> bool {
|
||||
let mut failures = self.handshake_failures.lock().unwrap();
|
||||
let count = failures.entry(addr.to_string()).or_default();
|
||||
*count += 1;
|
||||
@@ -377,8 +466,16 @@ impl Engine {
|
||||
return false;
|
||||
}
|
||||
failures.remove(addr);
|
||||
self.passthrough.lock().unwrap().insert(addr.to_string());
|
||||
true
|
||||
let mut passthrough = self.passthrough.lock().unwrap();
|
||||
match passthrough.entry(addr.to_string()) {
|
||||
std::collections::hash_map::Entry::Occupied(_) => false,
|
||||
std::collections::hash_map::Entry::Vacant(slot) => {
|
||||
let id = self.next_flow_id();
|
||||
slot.insert(id);
|
||||
self.emit(failed(id));
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_handshake_success(&self, addr: &str) {
|
||||
@@ -440,8 +537,9 @@ pub fn start_proxy(config: ProxyConfig) -> Result<ProxyHandle, String> {
|
||||
http_client: http_client(),
|
||||
upstream_tls: upstream_tls_config(&roots, &[b"h2", b"http/1.1"])?,
|
||||
upstream_tls_h1: upstream_tls_config(&roots, &[b"http/1.1"])?,
|
||||
passthrough: Mutex::new(HashSet::new()),
|
||||
passthrough: Mutex::new(HashMap::new()),
|
||||
handshake_failures: Mutex::new(HashMap::new()),
|
||||
tunnels: Mutex::new(HashMap::new()),
|
||||
http2: AtomicBool::new(config.http2),
|
||||
websocket_capture: config.websocket_capture,
|
||||
decrypt: RwLock::new(Arc::new(config.decrypt)),
|
||||
|
||||
@@ -28,12 +28,13 @@ use tokio_rustls::{LazyConfigAcceptor, TlsConnector};
|
||||
|
||||
use crate::body::{BodyParser, CaptureBody, Direction};
|
||||
use crate::connection::serve_tls;
|
||||
use crate::decrypt::Verdict;
|
||||
use crate::grpc::{self, GrpcParser};
|
||||
use crate::messages::{MessageDirection, StreamKind};
|
||||
use crate::sse::SseParser;
|
||||
use crate::tunnel::{Counted, Rewind, is_own_connection, splice, tunnel};
|
||||
use crate::ws::{self, WsFlow};
|
||||
use crate::{ClientConn, Engine, ProxyEvent};
|
||||
use crate::{ClientConn, Engine, ProxyEvent, TunnelReason};
|
||||
|
||||
pub(crate) type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
|
||||
type BoxError = Box<dyn Error + Send + Sync>;
|
||||
@@ -436,13 +437,23 @@ async fn intercept<S>(
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
if !engine.decrypts(&target.server_name, target.port, conn.connection).await {
|
||||
debug!("Tunneling {} undecrypted, as the decrypt list leaves it out", target.addr);
|
||||
return Ok(tunnel_flow(client, &target, conn, &engine).await?);
|
||||
match engine.verdict(&target.server_name, target.port, conn.connection).await {
|
||||
Verdict::Decrypt => {}
|
||||
Verdict::NotListed => {
|
||||
debug!("Tunneling {} undecrypted, as the decrypt list leaves it out", target.addr);
|
||||
return Ok(tunnel_flow(client, &target, conn, &engine, TunnelReason::NotListed).await?);
|
||||
}
|
||||
Verdict::Excluded(entry) => {
|
||||
debug!("Tunneling {} undecrypted, as {entry} excludes it", target.addr);
|
||||
let reason =
|
||||
TunnelReason::Excluded { entry: entry.to_string(), built_in: entry.built_in };
|
||||
return Ok(tunnel_flow(client, &target, conn, &engine, reason).await?);
|
||||
}
|
||||
}
|
||||
// The fallback for clients that rejected the engine's certificate.
|
||||
if engine.is_passthrough(&target.addr) {
|
||||
return Ok(tunnel_flow(client, &target, conn, &engine).await?);
|
||||
if let Some(rejected_by) = engine.passthrough_of(&target.addr) {
|
||||
let reason = TunnelReason::Rejected { rejected_by };
|
||||
return Ok(tunnel_flow(client, &target, conn, &engine, reason).await?);
|
||||
}
|
||||
|
||||
let mut buf = vec![0u8; 4096];
|
||||
@@ -461,6 +472,7 @@ where
|
||||
return Ok(tunnel(client, &target.addr, &buf).await?);
|
||||
}
|
||||
|
||||
let attempt = HandshakeAttempt { started_at: SystemTime::now(), start: Instant::now() };
|
||||
let acceptor = rustls::server::Acceptor::default();
|
||||
let start = LazyConfigAcceptor::new(acceptor, Rewind::new(Bytes::from(buf), client)).await?;
|
||||
let server_name = start
|
||||
@@ -472,7 +484,11 @@ where
|
||||
let mut tls = match start.into_stream(config).await {
|
||||
Ok(tls) => tls,
|
||||
Err(e) => {
|
||||
record_handshake_failure(&engine, &target.addr, is_certificate_rejection(&e), &e);
|
||||
let rejection = certificate_rejection(&e)
|
||||
.map(String::from)
|
||||
.or_else(|| is_hang_up(&e).then(|| HANG_UP.to_string()));
|
||||
let alert = certificate_rejection(&e).is_some();
|
||||
record_handshake_failure(&engine, &target, conn, &attempt, alert, rejection, &e);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -484,7 +500,8 @@ where
|
||||
let n = match tls.read(&mut buf).await {
|
||||
Ok(n) => n,
|
||||
Err(e) if is_hang_up(&e) => {
|
||||
record_handshake_failure(&engine, &target.addr, false, &e);
|
||||
let rejection = Some(HANG_UP.to_string());
|
||||
record_handshake_failure(&engine, &target, conn, &attempt, false, rejection, &e);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
@@ -509,6 +526,7 @@ async fn tunnel_flow<S>(
|
||||
target: &Target,
|
||||
conn: ClientConn,
|
||||
engine: &Engine,
|
||||
reason: TunnelReason,
|
||||
) -> std::io::Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
@@ -518,16 +536,27 @@ where
|
||||
}
|
||||
let id = engine.next_flow_id();
|
||||
let start = Instant::now();
|
||||
// Registered before its start is announced, so it can be closed as soon as it is known.
|
||||
let (close_tx, close_rx) = tokio::sync::oneshot::channel();
|
||||
engine.tunnels.lock().unwrap().insert(id, close_tx);
|
||||
engine.emit(ProxyEvent::TunnelStart {
|
||||
id,
|
||||
started_at: SystemTime::now(),
|
||||
authority: target.authority.clone(),
|
||||
host: target.server_name.clone(),
|
||||
port: target.port,
|
||||
connection: conn.connection,
|
||||
client_addr: conn.addr,
|
||||
reason,
|
||||
});
|
||||
let client = Counted::new(client);
|
||||
let (sent, received) = client.counters();
|
||||
let result = tunnel(client, &target.addr, &[]).await;
|
||||
// Closed on request: dropping the relay closes both sides.
|
||||
let (result, reconnect_requested) = tokio::select! {
|
||||
result = tunnel(client, &target.addr, &[]) => (result, false),
|
||||
_ = close_rx => (Ok(()), true),
|
||||
};
|
||||
engine.tunnels.lock().unwrap().remove(&id);
|
||||
let (sent, received) = (sent.load(Ordering::Relaxed), received.load(Ordering::Relaxed));
|
||||
// A tunnel that carried the server's bytes and then broke ended as connections do; one that
|
||||
// never did failed to reach the server.
|
||||
@@ -541,17 +570,43 @@ where
|
||||
received,
|
||||
elapsed_ms: start.elapsed().as_millis() as u64,
|
||||
error,
|
||||
reconnect_requested,
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// When a client's TLS handshake with the engine began.
|
||||
struct HandshakeAttempt {
|
||||
started_at: SystemTime,
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
/// How a client that hangs up on the engine's handshake is recorded as rejecting it.
|
||||
const HANG_UP: &str = "hang_up";
|
||||
|
||||
/// Counts a failed handshake toward passing the address through, and, when this one starts
|
||||
/// passing it through, records the failure as a flow of its own.
|
||||
fn record_handshake_failure(
|
||||
engine: &Engine,
|
||||
addr: &str,
|
||||
certificate_rejected: bool,
|
||||
target: &Target,
|
||||
conn: ClientConn,
|
||||
attempt: &HandshakeAttempt,
|
||||
certificate_alert: bool,
|
||||
rejection: Option<String>,
|
||||
e: &std::io::Error,
|
||||
) {
|
||||
if engine.record_handshake_failure(addr, certificate_rejected) {
|
||||
let addr = &target.addr;
|
||||
let failed = |id| ProxyEvent::HandshakeFailed {
|
||||
id,
|
||||
started_at: attempt.started_at,
|
||||
authority: target.authority.clone(),
|
||||
connection: conn.connection,
|
||||
client_addr: conn.addr,
|
||||
rejection,
|
||||
error: error_chain(e),
|
||||
elapsed_ms: attempt.start.elapsed().as_millis() as u64,
|
||||
};
|
||||
if engine.record_handshake_failure(addr, certificate_alert, failed) {
|
||||
info!("Client rejected the proxy for {addr}, passing it through: {e}");
|
||||
} else {
|
||||
debug!("TLS handshake with client failed for {addr}: {e}");
|
||||
@@ -564,22 +619,27 @@ fn is_hang_up(e: &std::io::Error) -> bool {
|
||||
matches!(e.kind(), UnexpectedEof | ConnectionReset | ConnectionAborted)
|
||||
}
|
||||
|
||||
fn is_certificate_rejection(e: &std::io::Error) -> bool {
|
||||
/// The alert a client sent rejecting the engine's certificate, by its name in the TLS spec, or
|
||||
/// None when `e` is not such an alert.
|
||||
fn certificate_rejection(e: &std::io::Error) -> Option<&'static str> {
|
||||
use rustls::AlertDescription::{
|
||||
BadCertificate, CertificateExpired, CertificateRevoked, CertificateUnknown, UnknownCA,
|
||||
UnsupportedCertificate,
|
||||
};
|
||||
matches!(
|
||||
e.get_ref().and_then(|inner| inner.downcast_ref::<rustls::Error>()),
|
||||
Some(rustls::Error::AlertReceived(
|
||||
BadCertificate
|
||||
| UnsupportedCertificate
|
||||
| CertificateRevoked
|
||||
| CertificateExpired
|
||||
| CertificateUnknown
|
||||
| UnknownCA
|
||||
))
|
||||
)
|
||||
let Some(rustls::Error::AlertReceived(alert)) =
|
||||
e.get_ref().and_then(|inner| inner.downcast_ref::<rustls::Error>())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
Some(match alert {
|
||||
BadCertificate => "bad_certificate",
|
||||
UnsupportedCertificate => "unsupported_certificate",
|
||||
CertificateRevoked => "certificate_revoked",
|
||||
CertificateExpired => "certificate_expired",
|
||||
CertificateUnknown => "certificate_unknown",
|
||||
UnknownCA => "unknown_ca",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
enum Upstream {
|
||||
|
||||
@@ -33,8 +33,8 @@ use tokio_tungstenite::tungstenite::protocol::Role;
|
||||
use tokio_tungstenite::tungstenite::protocol::frame::CloseFrame;
|
||||
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
|
||||
use yaak_proxy::{
|
||||
CaStore, DecryptApp, DecryptPolicy, MessageDirection, MessageKind, ProxyConfig, ProxyEvent,
|
||||
ProxyHandle, StreamKind, StreamMessage, start_proxy,
|
||||
BUILT_IN_EXCLUSIONS, CaStore, DecryptApp, DecryptPolicy, MessageDirection, MessageKind,
|
||||
ProxyConfig, ProxyEvent, ProxyHandle, StreamKind, StreamMessage, TunnelReason, start_proxy,
|
||||
};
|
||||
|
||||
const BIG_BODY: usize = 64 * 1024;
|
||||
@@ -406,6 +406,7 @@ fn is_terminal(event: &ProxyEvent) -> bool {
|
||||
| ProxyEvent::Cancelled { .. }
|
||||
| ProxyEvent::StreamEnd { .. }
|
||||
| ProxyEvent::TunnelEnd { .. }
|
||||
| ProxyEvent::HandshakeFailed { .. }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -426,7 +427,8 @@ fn flow_id(event: &ProxyEvent) -> u64 {
|
||||
| ProxyEvent::Message { id, .. }
|
||||
| ProxyEvent::StreamEnd { id, .. }
|
||||
| ProxyEvent::TunnelStart { id, .. }
|
||||
| ProxyEvent::TunnelEnd { id, .. } => *id,
|
||||
| ProxyEvent::TunnelEnd { id, .. }
|
||||
| ProxyEvent::HandshakeFailed { id, .. } => *id,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1318,8 +1320,12 @@ async fn an_empty_decrypt_list_tunnels_https_untouched() {
|
||||
let (connection, authority) = find!(events, ProxyEvent::TunnelStart { connection, authority, .. } => (*connection, authority.clone()));
|
||||
assert_eq!(connection, 1);
|
||||
assert_eq!(authority, format!("localhost:{}", upstream.port()));
|
||||
let (sent, received, error) = find!(events, ProxyEvent::TunnelEnd { sent, received, error, .. } => (*sent, *received, error.clone()));
|
||||
let (host, port, reason) = find!(events, ProxyEvent::TunnelStart { host, port, reason, .. } => (host.clone(), *port, reason.clone()));
|
||||
assert_eq!((host.as_str(), port), ("localhost", upstream.port()));
|
||||
assert_eq!(reason, TunnelReason::NotListed);
|
||||
let (sent, received, error, reconnect) = find!(events, ProxyEvent::TunnelEnd { sent, received, error, reconnect_requested, .. } => (*sent, *received, error.clone(), *reconnect_requested));
|
||||
assert_eq!(error, None);
|
||||
assert!(!reconnect);
|
||||
// The ClientHello and request one way, the certificate and response the other.
|
||||
assert!(sent > 100, "sent {sent}");
|
||||
assert!(received as usize > response.len(), "received {received}");
|
||||
@@ -1328,6 +1334,49 @@ async fn an_empty_decrypt_list_tunnels_https_untouched() {
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_excluded_host_is_tunnelled_with_the_exclusion_that_kept_it_out() {
|
||||
within(async {
|
||||
let mut entries = vec!["*", "!host:localhost"];
|
||||
entries.extend(BUILT_IN_EXCLUSIONS.iter().map(|(e, _)| *e));
|
||||
let h = Harness::start_with(1024, with_policy(&entries));
|
||||
let upstream = spawn_upstream(Some(h.pki.server.clone())).await;
|
||||
let tls = upstream_tls(&h, upstream.port(), &[b"http/1.1"]).await;
|
||||
assert!(get_hello_and_close(tls).await.ends_with("hello"));
|
||||
let events = h.flow_events();
|
||||
let reason = find!(events, ProxyEvent::TunnelStart { reason, .. } => reason.clone());
|
||||
let entry = "!host:localhost".to_string();
|
||||
assert_eq!(reason, TunnelReason::Excluded { entry, built_in: false });
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// A tunnel closed on request ends at once, both sides closed, marked as asked to reconnect.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_a_tunnel_ends_it_for_a_reconnect() {
|
||||
within(async {
|
||||
let h = Harness::start_with(1024, with_policy(&[]));
|
||||
let upstream = spawn_upstream(Some(h.pki.server.clone())).await;
|
||||
let mut tls = upstream_tls(&h, upstream.port(), &[b"http/1.1"]).await;
|
||||
let started = h.events.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let ProxyEvent::TunnelStart { id, .. } = started else {
|
||||
panic!("expected a tunnel, got {started:?}");
|
||||
};
|
||||
assert_eq!(h.proxy.close_tunnels(&[id + 100]), 0, "no such tunnel");
|
||||
assert_eq!(h.proxy.close_tunnels(&[id]), 1);
|
||||
// The client sees its connection end.
|
||||
let mut rest = Vec::new();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), tls.read_to_end(&mut rest))
|
||||
.await
|
||||
.expect("the tunnel stayed open");
|
||||
let events = h.flow_events();
|
||||
let (end_id, error, reconnect) = find!(events, ProxyEvent::TunnelEnd { id, error, reconnect_requested, .. } => (*id, error.clone(), *reconnect_requested));
|
||||
assert_eq!((end_id, error, reconnect), (id, None, true));
|
||||
assert_eq!(h.proxy.close_tunnels(&[id]), 0, "closed already");
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_tunnelled_host_passes_http2_through() {
|
||||
within(async {
|
||||
@@ -1439,11 +1488,68 @@ async fn certificate_alert_passes_through_on_the_next_connection() {
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
|
||||
assert!(pinned.connect(name.clone(), h.connect_tunnel(port).await).await.is_err());
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
pinned
|
||||
let failed = h.events.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let ProxyEvent::HandshakeFailed { id: rejected, authority, rejection, connection, .. } = failed
|
||||
else {
|
||||
panic!("expected the refused handshake, got {failed:?}");
|
||||
};
|
||||
assert_eq!(authority, format!("localhost:{port}"));
|
||||
assert_eq!(rejection.as_deref(), Some("unknown_ca"));
|
||||
assert_eq!(connection, 1);
|
||||
assert_eq!(h.proxy.passthrough(), vec![format!("localhost:{port}")]);
|
||||
let tls = pinned
|
||||
.connect(name, h.connect_tunnel(port).await)
|
||||
.await
|
||||
.expect("one certificate alert should be enough to pass the host through");
|
||||
let started = h.events.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let ProxyEvent::TunnelStart { reason, .. } = started else {
|
||||
panic!("expected a tunnel, got {started:?}");
|
||||
};
|
||||
assert_eq!(reason, TunnelReason::Rejected { rejected_by: rejected });
|
||||
drop(tls);
|
||||
|
||||
// Forgotten, the address is intercepted again, and a refusal is a new flow.
|
||||
let addr = format!("localhost:{port}");
|
||||
assert!(!h.proxy.forget_passthrough_address("localhost:1"));
|
||||
assert!(h.proxy.forget_passthrough_address(&addr));
|
||||
assert!(h.proxy.passthrough().is_empty());
|
||||
}
|
||||
|
||||
/// Clients refusing the certificate together make one flow for the address, not one each.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn concurrent_refusals_are_one_flow() {
|
||||
within(async {
|
||||
let h = Harness::start(1024);
|
||||
let upstream = spawn_upstream(Some(h.pki.server.clone())).await;
|
||||
let port = upstream.port();
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.add(h.pki.ca_der.clone()).unwrap();
|
||||
let config = ClientConfig::builder_with_provider(ring())
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
let pinned = TlsConnector::from(Arc::new(config));
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
// Every connection is made before any handshake starts, so they all race.
|
||||
let mut tunnels = Vec::new();
|
||||
for _ in 0..8 {
|
||||
tunnels.push(h.connect_tunnel(port).await);
|
||||
}
|
||||
let attempts = tunnels.into_iter().map(|tcp| {
|
||||
let (pinned, name) = (pinned.clone(), name.clone());
|
||||
tokio::spawn(async move { pinned.connect(name, tcp).await.map(drop) })
|
||||
});
|
||||
for attempt in attempts.collect::<Vec<_>>() {
|
||||
let _ = attempt.await.unwrap();
|
||||
}
|
||||
let mut failed = 0;
|
||||
while let Ok(event) = h.events.recv_timeout(Duration::from_millis(300)) {
|
||||
failed += usize::from(matches!(event, ProxyEvent::HandshakeFailed { .. }));
|
||||
}
|
||||
assert_eq!(failed, 1);
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// SChannel (native-tls on Windows) checks the certificate only after sending its Finished, so
|
||||
@@ -1462,6 +1568,13 @@ async fn hang_up_after_the_handshake_passes_through() {
|
||||
drop(tls);
|
||||
h.wait_for_handshake_state(&addr, state).await;
|
||||
}
|
||||
// Recorded once, as the second hang-up passes it through.
|
||||
let failed = h.events.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let ProxyEvent::HandshakeFailed { rejection, .. } = failed else {
|
||||
panic!("expected the refused handshake, got {failed:?}");
|
||||
};
|
||||
assert_eq!(rejection.as_deref(), Some("hang_up"));
|
||||
assert!(h.events.recv_timeout(Duration::from_millis(100)).is_err());
|
||||
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.add(h.pki.ca_der.clone()).unwrap();
|
||||
|
||||
Reference in new issue
Block a user