Skip to content

wasm: fix potential crash of extensions for failed remote code fetch - #20843

Merged
kyessenov merged 8 commits into
envoyproxy:mainfrom
johnlanni:fix-crash
May 23, 2022
Merged

kyessenov merged 8 commits into
envoyproxy:mainfrom
johnlanni:fix-crash

Conversation

@johnlanni

@johnlanni johnlanni commented Apr 15, 2022 •

Copy link
Copy Markdown
Contributor

Commit Message:
Additional Description:
Risk Level: low
Testing: ok
Docs Changes:
Release Notes:
Platform Specific Features:
[Optional Runtime guard:]
[Optional Fixes #Issue]
[Optional Fixes commit #PR or SHA]
[Optional Deprecated:]
[Optional API Considerations:]

image

image

this PluginHandleSharedPtr handle maybe null.

@johnlanni
johnlanni requested a review from lizan as a code owner April 15, 2022 10:00
@repokitteh-read-only

Copy link
Copy Markdown

Hi @johnlanni, welcome and thank you for your contribution.

We will try to review your Pull Request as quickly as possible.

In the meantime, please take a look at the contribution guidelines if you have not done so already.

🐱

Caused by: #20843 was opened by johnlanni.

see: more, trace.

@johnlanni

johnlanni commented Apr 18, 2022 •

Copy link
Copy Markdown
Contributor Author

return std::static_pointer_cast<PluginHandle>(proxy_wasm::getOrCreateThreadLocalPlugin(

The reason is this line may return a nullptr since wasm configure failed here:

https://github.com/proxy-wasm/proxy-wasm-cpp-host/blob/61135c5a431cd8d68d73f41025f27d26db1807ac/src/wasm.cc#L582-L586

This crash definitely occurs when two wasm filters use the same vm configuration, the first is configured correctly and the second is wrong. The logic here only checks the plugin config of the first one:

https://github.com/proxy-wasm/proxy-wasm-cpp-host/blob/61135c5a431cd8d68d73f41025f27d26db1807ac/src/wasm.cc#L499-L503

and the logic here will make the second one reuse the base_wasm of the same vm:

https://github.com/proxy-wasm/proxy-wasm-cpp-host/blob/61135c5a431cd8d68d73f41025f27d26db1807ac/src/wasm.cc#L467-L469

This crash also occurs in dynamic filter config scenarios such as ECDS is used to discover the config.

@johnlanni

johnlanni commented Apr 18, 2022 •

Copy link
Copy Markdown
Contributor Author

test config:

admin:
  address:
    socket_address:
      protocol: TCP
      address: 0.0.0.0
      port_value: 9901
static_resources:
  listeners:
  - name: listener_0
    # enable_reuse_port: true
    connection_balance_config:
      exact_balance: {}
    address:
      socket_address:
        protocol: TCP
        address: 0.0.0.0
        port_value: 10000
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          scheme_header_transformation:
            scheme_to_overwrite: https
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains: ["*"]
              routes:
              - match:
                  prefix: "/"
                direct_response:
                  status: 200
                  body:
                    inline_string: "hello world"
          http_filters:
          - name: basic-auth-1
            typed_config:
              "@type": type.googleapis.com/udpa.type.v1.TypedStruct
              type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
              value:
                config:
                  name: basic-auth
                  vm_config:
                    runtime: envoy.wasm.runtime.v8
                    code:
                      local:
                        filename: ./basic-auth.wasm
                  configuration:
                    "@type": "type.googleapis.com/google.protobuf.StringValue"
                    value: |
                      {
                      "credentials":[ "ok:test2"]
                      }
          - name: basic-auth-2
            typed_config:
              "@type": type.googleapis.com/udpa.type.v1.TypedStruct
              type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
              value:
                config:
                  name: basic-auth
                  vm_config:
                    runtime: envoy.wasm.runtime.v8
                    code:
                      local:
                        filename: ./basic-auth.wasm
                  configuration:
                    "@type": "type.googleapis.com/google.protobuf.StringValue"
                    value: |
                      {
                      "credentials":[ "ok:test2"
                      }
          - name: envoy.filters.http.router

start envoy, and execute curl localhost:10000, then it will crash.

the basic-auth.wasm here will parse the config through json, and the second filter's config is not a valid json format.

basic-auth.wasm.zip

Signed-off-by: johnlanni <[email protected]>
@johnlanni

Copy link
Copy Markdown
Contributor Author

cc @PiotrSikora

@PiotrSikora PiotrSikora left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Could you make similar changes in other Wasm extensions?


std::shared_ptr<Context> createFilter() {
Wasm* wasm = nullptr;
if (!tls_slot_->currentThreadRegistered()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When can this happen? cc @jmarantz for TLS bits.

@johnlanni johnlanni Apr 19, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When using remote wasm code, createWasm here will return without calling this callback, which makes the tls_slot not yet registered when it starts serving the request:

auto callback = [plugin, this](const Common::Wasm::WasmHandleSharedPtr& base_wasm) {
// NB: the Slot set() call doesn't complete inline, so all arguments must outlive this call.
tls_slot_->set([base_wasm, plugin](Event::Dispatcher& dispatcher) {
return std::make_shared<PluginHandleSharedPtrThreadLocal>(
Common::Wasm::getOrCreateThreadLocalPlugin(base_wasm, plugin, dispatcher));
});
};
if (!Common::Wasm::createWasm(plugin, context.scope().createScope(""), context.clusterManager(),
context.initManager(), context.mainThreadDispatcher(),
context.api(), context.lifecycleNotifier(), remote_data_provider_,
std::move(callback))) {
throw Common::Wasm::WasmException(
fmt::format("Unable to create Wasm HTTP filter {}", plugin->name_));
}

the createWasm logic of using remote wasm code:

if (fetch) {
auto holder = std::make_shared<std::unique_ptr<Event::DeferredDeletable>>();
auto fetch_callback = [vm_config, complete_cb, source, &dispatcher, scope, holder, plugin,
&stats_handler](const std::string& code) {
{
std::lock_guard<std::mutex> guard(code_cache_mutex);
auto& e = (*code_cache)[vm_config.code().remote().sha256()];
e.in_progress = false;
e.code = code;
Stats::ScopeSharedPtr create_wasm_stats_scope = stats_handler.lockAndCreateStats(scope);
if (code.empty()) {
stats_handler.onEvent(WasmEvent::RemoteLoadCacheFetchFailure);
} else {
stats_handler.onEvent(WasmEvent::RemoteLoadCacheFetchSuccess);
}
stats_handler.onRemoteCacheEntriesChanged(code_cache->size());
}
// NB: xDS currently does not support failing asynchronously, so we fail immediately
// if remote Wasm code is not cached and do a background fill.
if (!vm_config.nack_on_code_cache_miss()) {
if (code.empty()) {
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::wasm), trace,
"Failed to load Wasm code (fetch failed) from {}", source);
}
complete_cb(code);
}
// NB: must be deleted explicitly.
if (*holder) {
dispatcher.deferredDelete(Envoy::Event::DeferredDeletablePtr{holder->release()});
}
};
if (vm_config.nack_on_code_cache_miss()) {
auto adapter = std::make_unique<RemoteDataFetcherAdapter>(fetch_callback);
auto fetcher = std::make_unique<Config::DataFetcher::RemoteDataFetcher>(
cluster_manager, vm_config.code().remote().http_uri(), vm_config.code().remote().sha256(),
*adapter);
auto fetcher_ptr = fetcher.get();
adapter->setFetcher(std::move(fetcher));
*holder = std::move(adapter);
fetcher_ptr->fetch();
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::wasm), trace,
fmt::format("Failed to load Wasm code (fetching) from {}", source));
cb(nullptr);
return false;
} else {
remote_data_provider = std::make_unique<Config::DataSource::RemoteAsyncDataProvider>(
cluster_manager, init_manager, vm_config.code().remote(), dispatcher,
api.randomGenerator(), true, fetch_callback);
}

Signed-off-by: johnlanni <[email protected]>
@johnlanni

Copy link
Copy Markdown
Contributor Author

Thanks! Could you make similar changes in other Wasm extensions?

The same changes have been made to the access_logger and network filter extensions, and bootstrap extension doesn't seem to have this problem.

Signed-off-by: johnlanni <[email protected]>
Signed-off-by: johnlanni <[email protected]>
Signed-off-by: johnlanni <[email protected]>
Signed-off-by: johnlanni <[email protected]>
@johnlanni johnlanni changed the title fix potential crash of wasm filter fix potential crash of wasm extension Apr 20, 2022
@johnlanni

Copy link
Copy Markdown
Contributor Author

@PiotrSikora @lizan All checks have passed, could you help me review it? Thanks!

@kyessenov

Copy link
Copy Markdown
Contributor

/assign @kyessenov

@kyessenov

Copy link
Copy Markdown
Contributor

Have you tried the latest version of Envoy?
I've tried running #20843 (comment), but cannot replicate the crash:

[2022-05-13 10:31:19.125][24003][info][config] [source/server/configuration_impl.cc:97] loading 1 listener(s)
[2022-05-13 10:31:19.364][24003][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:133]::configure() cannot parse plugin configuration JSON string: {
"credentials":[ "ok:test2"
}

[2022-05-13 10:31:19.364][24003][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:120]::onConfigure() configuration has errors initialization will not continue.
[2022-05-13 10:31:19.364][24003][error][wasm] [source/extensions/common/wasm/wasm.cc:109] Wasm VM failed Failed to configure thread-local Wasm plugin
[2022-05-13 10:31:19.368][24003][info][config] [source/server/configuration_impl.cc:109] loading stats configuration
[2022-05-13 10:31:19.368][24003][info][runtime] [source/common/runtime/runtime_impl.cc:463] RTDS has finished initialization
[2022-05-13 10:31:19.368][24003][info][upstream] [source/common/upstream/cluster_manager_impl.cc:220] cm init: all clusters initialized
[2022-05-13 10:31:19.368][24003][warning][main] [source/server/server.cc:761] there is no configured limit to the number of allowed active connections. Set a limit via the runtime key overload.global_downstream_max_connections
[2022-05-13 10:31:19.369][24003][info][main] [source/server/server.cc:863] all clusters initialized. initializing init manager
[2022-05-13 10:31:19.369][24003][info][config] [source/server/listener_manager_impl.cc:789] all dependencies initialized. starting workers
[2022-05-13 10:31:19.401][24026][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:133]::configure() cannot parse plugin configuration JSON string: {
"credentials":[ "ok:test2"
}

[2022-05-13 10:31:19.401][24026][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:120]::onConfigure() configuration has errors initialization will not continue.
[2022-05-13 10:31:19.401][24026][error][wasm] [source/extensions/common/wasm/wasm.cc:109] Wasm VM failed Failed to configure thread-local Wasm plugin
[2022-05-13 10:31:19.402][24003][info][main] [source/server/server.cc:882] starting main dispatch loop

@johnlanni

johnlanni commented May 19, 2022 •

Copy link
Copy Markdown
Contributor Author

Have you tried the latest version of Envoy? I've tried running #20843 (comment), but cannot replicate the crash:

[2022-05-13 10:31:19.125][24003][info][config] [source/server/configuration_impl.cc:97] loading 1 listener(s)
[2022-05-13 10:31:19.364][24003][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:133]::configure() cannot parse plugin configuration JSON string: {
"credentials":[ "ok:test2"
}

[2022-05-13 10:31:19.364][24003][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:120]::onConfigure() configuration has errors initialization will not continue.
[2022-05-13 10:31:19.364][24003][error][wasm] [source/extensions/common/wasm/wasm.cc:109] Wasm VM failed Failed to configure thread-local Wasm plugin
[2022-05-13 10:31:19.368][24003][info][config] [source/server/configuration_impl.cc:109] loading stats configuration
[2022-05-13 10:31:19.368][24003][info][runtime] [source/common/runtime/runtime_impl.cc:463] RTDS has finished initialization
[2022-05-13 10:31:19.368][24003][info][upstream] [source/common/upstream/cluster_manager_impl.cc:220] cm init: all clusters initialized
[2022-05-13 10:31:19.368][24003][warning][main] [source/server/server.cc:761] there is no configured limit to the number of allowed active connections. Set a limit via the runtime key overload.global_downstream_max_connections
[2022-05-13 10:31:19.369][24003][info][main] [source/server/server.cc:863] all clusters initialized. initializing init manager
[2022-05-13 10:31:19.369][24003][info][config] [source/server/listener_manager_impl.cc:789] all dependencies initialized. starting workers
[2022-05-13 10:31:19.401][24026][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:133]::configure() cannot parse plugin configuration JSON string: {
"credentials":[ "ok:test2"
}

[2022-05-13 10:31:19.401][24026][warning][wasm] [source/extensions/common/wasm/context.cc:1173] wasm log: [extensions/basic_auth/plugin.cc:120]::onConfigure() configuration has errors initialization will not continue.
[2022-05-13 10:31:19.401][24026][error][wasm] [source/extensions/common/wasm/wasm.cc:109] Wasm VM failed Failed to configure thread-local Wasm plugin
[2022-05-13 10:31:19.402][24003][info][main] [source/server/server.cc:882] starting main dispatch loop

@kyessenov I tried the latest version and the problem persists.
image
image

Did you execute the command curl localhost:10000 after envoy started?

@kyessenov

Copy link
Copy Markdown
Contributor

Sorry for the delay, and yes, indeed this is a crash. I am quite confused by the sequence of events. Is this the right way to interpret it:

  • On the first filter instantiation, a plugin is created with the correct filter config. Wasm extension creates both the VM and instantiates this plugin in the VM. As part of instantiation, it runs a canary VM with the correct plugin filter config.
  • On the second filter instantiation, Wasm finds an existing VM with the same VM config. It skips canarying the config, and then shortcuts somewhere down the line a plugin handle to nullptr because of incorrect VM config.

I think this whole sequence is confusing. I'd expect the second instance of the plugin to behave the same whether or not there is another plugin somewhere. With this change, I think it silently accepts it (can you confirm?), but if i remove the first instance, LDS is rejected. That's not very consistent.

So I think we have two choices here:

  • Make the second filter do config canarying when VMs are shared.
  • Do not share VM. Add plugin config to the VM key.

WDYT?
@PiotrSikora

@johnlanni

Copy link
Copy Markdown
Contributor Author

So I think we have two choices here:

  • Make the second filter do config canarying when VMs are shared.
  • Do not share VM. Add plugin config to the VM key.

WDYT? @PiotrSikora

@kyessenov I think having the second filter do config canarying is a better opion, since plugins may need to share rootContext over the shared VM, and shared VM can also reduce the memory usage.

@johnlanni

Copy link
Copy Markdown
Contributor Author

@kyessenov There is another problem that causes envoy to crash: when using remote wasm code, createWasm here will return without calling this callback, which makes the tls_slot not yet registered when it starts serving the request:

auto callback = [plugin, this](const Common::Wasm::WasmHandleSharedPtr& base_wasm) {
// NB: the Slot set() call doesn't complete inline, so all arguments must outlive this call.
tls_slot_->set([base_wasm, plugin](Event::Dispatcher& dispatcher) {
return std::make_shared<PluginHandleSharedPtrThreadLocal>(
Common::Wasm::getOrCreateThreadLocalPlugin(base_wasm, plugin, dispatcher));
});
};
if (!Common::Wasm::createWasm(plugin, context.scope().createScope(""), context.clusterManager(),
context.initManager(), context.mainThreadDispatcher(),
context.api(), context.lifecycleNotifier(), remote_data_provider_,
std::move(callback))) {
throw Common::Wasm::WasmException(
fmt::format("Unable to create Wasm HTTP filter {}", plugin->name_));
}

UT for this scene:
https://github.com/envoyproxy/envoy/pull/20843/files#diff-49c5c7017e906b6ecb111a8333eb74322c650c4a6ba16613750a4952097ed252R904

This UT would also crash without this code:
https://github.com/envoyproxy/envoy/pull/20843/files#diff-90e133f83d91e5c22d1f7c7e8c0cf8017536a23765978bf81c7efd0482be0d81R31

@johnlanni
johnlanni requested a review from PiotrSikora May 23, 2022 02:49

@kyessenov kyessenov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is definitely an improvement, so thank you for the fix! I think it's fair to handle failed remote code load by not crashing, even though it's potentially risky to load authorization filters this way (because xDS is accepted but filter is not applied when fetching fails). We should probably add a note somewhere explaining the risk.

Could you file an issue upstream in proxy-wasm requesting canarying for duplicate filter configs?

@kyessenov kyessenov changed the title fix potential crash of wasm extension wasm: fix potential crash of extensions for failed remote code fetch May 23, 2022
@kyessenov
kyessenov merged commit d81a796 into envoyproxy:main May 23, 2022
ravenblackx pushed a commit to ravenblackx/envoy that referenced this pull request Jun 8, 2022
…nvoyproxy#20843)

Signed-off-by: johnlanni [email protected]

Commit Message: Handle null plugins handle when skipping config canarying for duplicate filters and also when the remote code fetch is in progress or fails.
Risk Level: low
Testing: ok
phlax pushed a commit to phlax/envoy that referenced this pull request Nov 15, 2022
…nvoyproxy#20843)

Signed-off-by: johnlanni [email protected]

Commit Message: Handle null plugins handle when skipping config canarying for duplicate filters and also when the remote code fetch is in progress or fails.
Risk Level: low
Testing: ok

Signed-off-by: 澄潭 <[email protected]>

Signed-off-by: Ryan Northey <[email protected]>
phlax pushed a commit that referenced this pull request Nov 16, 2022
…20843)

Signed-off-by: johnlanni [email protected]

Commit Message: Handle null plugins handle when skipping config canarying for duplicate filters and also when the remote code fetch is in progress or fails.
Risk Level: low
Testing: ok

Signed-off-by: 澄潭 <[email protected]>

Signed-off-by: Ryan Northey <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants