From 96d77429748edef8b64dbad67d7188daee7958dd Mon Sep 17 00:00:00 2001 From: Niklas Date: Wed, 11 Nov 2026 01:48:28 +0100 Subject: [PATCH] Trust the per-printer CA file for Bambu LAN connections (#17062) The HTTPS CA file in the IP and access code dialog had no effect for Bambu Lab printers. For Bambu printers, the CA path is now saved with the printer's local machine entry instead of being read from the selected preset. On connect, Orca builds `/cert` with the bundled `printer.cer` plus the CA of each printer connected in this session, and points the network plug-in there. The file must contain only CA certificates. If it doesn't, Orca logs a warning and keeps the bundled certs. Other printer agents still use `printhost_cafile` from the preset. A CA chosen before this change is not migrated. Choose it again in the dialog. Fixes #17061 --- src/libslic3r/AppConfig.cpp | 4 + src/libslic3r/AppConfig.hpp | 5 +- src/slic3r/GUI/DeviceCore/DevManager.cpp | 17 ++- src/slic3r/GUI/DeviceManager.cpp | 20 ++- src/slic3r/GUI/DeviceManager.hpp | 4 + src/slic3r/GUI/ReleaseNote.cpp | 85 ++++++++--- src/slic3r/GUI/ReleaseNote.hpp | 4 +- src/slic3r/Utils/BBLPrinterAgent.cpp | 137 ++++++++++++++++++ src/slic3r/Utils/BBLPrinterAgent.hpp | 11 ++ tests/libslic3r/test_appconfig.cpp | 2 + tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_bbl_cert_dir.cpp | 128 ++++++++++++++++ .../test_device_manager_integration.cpp | 54 +++++++ 13 files changed, 447 insertions(+), 25 deletions(-) create mode 100644 tests/slic3rutils/test_bbl_cert_dir.cpp diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 19142e3d97..b8ec3743c2 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -998,6 +998,8 @@ std::string AppConfig::load(bool read_only) local_machine.printer_agent_id = p["printer_agent_id"].get(); if (p.contains("access_code")) local_machine.access_code = p["access_code"].get(); + if (p.contains("ca_file")) + local_machine.ca_file = p["ca_file"].get(); m_local_machines[local_machine.dev_id] = local_machine; } } else { @@ -1211,6 +1213,8 @@ void AppConfig::save() m_json["printer_type"] = local_machine.second.printer_type; m_json["printer_agent_id"] = local_machine.second.printer_agent_id; m_json["access_code"] = local_machine.second.access_code; + if (!local_machine.second.ca_file.empty()) + m_json["ca_file"] = local_machine.second.ca_file; j["local_machines"][local_machine.first] = m_json; } diff --git a/src/libslic3r/AppConfig.hpp b/src/libslic3r/AppConfig.hpp index 852080c50c..cc63f4129e 100644 --- a/src/libslic3r/AppConfig.hpp +++ b/src/libslic3r/AppConfig.hpp @@ -90,11 +90,14 @@ struct BBLocalMachine // since BBL was the only agent when they were saved) - see // get_access_code_with_legacy_fallback() in DevManager.cpp. std::string access_code; + // Path of a CA certificate the user chose in the connect dialog, for a printer behind a proxy + // with its own CA. Kept per device, never taken from a printer preset. + std::string ca_file; bool operator==(const BBLocalMachine& other) const { return dev_name == other.dev_name && dev_ip == other.dev_ip && dev_id == other.dev_id && printer_type == other.printer_type && - printer_agent_id == other.printer_agent_id && access_code == other.access_code; + printer_agent_id == other.printer_agent_id && access_code == other.access_code && ca_file == other.ca_file; } bool operator!=(const BBLocalMachine& other) const { return !operator==(other); } }; diff --git a/src/slic3r/GUI/DeviceCore/DevManager.cpp b/src/slic3r/GUI/DeviceCore/DevManager.cpp index b84e5bf533..be59142997 100644 --- a/src/slic3r/GUI/DeviceCore/DevManager.cpp +++ b/src/slic3r/GUI/DeviceCore/DevManager.cpp @@ -66,6 +66,14 @@ namespace { } return ""; } + + // Scoped to the agent like the access code above; there is no legacy flat key to fall back to. + std::string get_stored_ca_file(Slic3r::AppConfig* config, const std::string& dev_id, const std::string& agent_id) + { + const auto& machines = config->get_local_machines(); + auto it = machines.find(dev_id); + return it != machines.end() && it->second.printer_agent_id == agent_id ? it->second.ca_file : ""; + } } namespace Slic3r @@ -110,6 +118,7 @@ namespace Slic3r obj->m_is_online = true; obj->last_alive = Slic3r::Utils::get_current_time_utc(); obj->set_access_code(get_access_code_with_legacy_fallback(config, m.dev_id, obj->printer_agent_id), false); + obj->set_ca_file(m.ca_file, false); if (obj->has_access_right()) { localMachineList.insert(std::make_pair(m.dev_id, obj)); } else { @@ -131,6 +140,7 @@ namespace Slic3r local_machine.printer_type = m.printer_type; local_machine.printer_agent_id = m.printer_agent_id; local_machine.access_code = m.get_access_code(); + local_machine.ca_file = m.get_ca_file(); config->update_local_machine(local_machine); } } else { @@ -446,6 +456,7 @@ namespace Slic3r //load access code if (config) { obj->set_access_code(get_access_code_with_legacy_fallback(config, dev_id, obj->printer_agent_id), false); + obj->set_ca_file(get_stored_ca_file(config, dev_id, obj->printer_agent_id), false); } localMachineList.insert(std::make_pair(dev_id, obj)); @@ -478,11 +489,13 @@ namespace Slic3r std::string version, std::string access_code) { MachineObject* obj; - auto it = localMachineList.find(machine.dev_id); + bool agent_changed = false; + auto it = localMachineList.find(machine.dev_id); if (it != localMachineList.end()) { obj = it->second; // insert_local_device is called by the active agent, so a reused entry must follow // that agent as well; otherwise the agent-scoped printer list hides it. + agent_changed = obj->printer_agent_id != get_current_printer_agent_id(); obj->printer_agent_id = get_current_printer_agent_id(); } else { obj = new MachineObject(this, m_agent, machine.dev_name, machine.dev_id, machine.dev_ip); @@ -500,6 +513,8 @@ namespace Slic3r obj->m_is_online = true; obj->last_alive = Slic3r::Utils::get_current_time_utc(); obj->set_access_code(access_code, false); + if ((agent_changed || obj->get_ca_file().empty()) && get_app_config()) + obj->set_ca_file(get_stored_ca_file(get_app_config(), machine.dev_id, obj->printer_agent_id), false); update_local_machine(*obj, get_app_config()); diff --git a/src/slic3r/GUI/DeviceManager.cpp b/src/slic3r/GUI/DeviceManager.cpp index 31fe6e6438..f42bc87b0f 100644 --- a/src/slic3r/GUI/DeviceManager.cpp +++ b/src/slic3r/GUI/DeviceManager.cpp @@ -579,6 +579,15 @@ void MachineObject::set_access_code(std::string code, bool only_refresh) } } +void MachineObject::set_ca_file(std::string path, bool only_refresh) +{ + ca_file = std::move(path); + if (only_refresh && is_lan_mode_printer() && has_access_right()) { + if (AppConfig* config = m_manager ? m_manager->get_app_config() : GUI::wxGetApp().app_config) + DeviceManager::update_local_machine(*this, config); + } +} + std::string MachineObject::get_show_printer_type() const { std::string printer_type = this->printer_type; @@ -2706,13 +2715,20 @@ int MachineObject::connect() // bare IP as dev_ip, so take the port from the dev_id rather than falling back to port 80. if (port.empty() && connects_through_moonraker_agent(printer_agent_id)) Http::get_host_from_url(get_dev_id(), &port); - std::string ca_file; + // A Bambu printer's CA is chosen per device in the connect dialog. Never take it from the + // selected preset: it may belong to another printer, or come from an imported profile. + // A local machine saved before agent ids existed belongs to the agent that connects it now. + const std::string agent_id = !printer_agent_id.empty() ? printer_agent_id : + m_manager ? m_manager->get_current_printer_agent_id() : std::string(); + const bool is_bbl = agent_id == BBL_PRINTER_AGENT_ID; + std::string ca_file = is_bbl ? get_ca_file() : std::string(); if (wxTheApp && GUI::wxGetApp().preset_bundle) { const auto& config = GUI::wxGetApp().preset_bundle->printers.get_edited_preset().config; if (port.empty()) port = config.opt_string("printhost_port"); - ca_file = config.opt_string("printhost_cafile"); + if (!is_bbl) + ca_file = config.opt_string("printhost_cafile"); // Refresh credentials from the matching preset for connections that bypass GUI_App::select_machine(). const std::string print_host = config.opt_string("print_host"); diff --git a/src/slic3r/GUI/DeviceManager.hpp b/src/slic3r/GUI/DeviceManager.hpp index 455d37fe49..8944a769d0 100644 --- a/src/slic3r/GUI/DeviceManager.hpp +++ b/src/slic3r/GUI/DeviceManager.hpp @@ -119,6 +119,7 @@ private: std::string dev_name; std::string dev_ip; std::string access_code; + std::string ca_file; bool m_access_revoked = false; // type, time stamp, delay @@ -234,6 +235,9 @@ public: void revoke_access(); std::string get_access_code() const; void set_access_code(std::string code, bool only_refresh = true); + // CA certificate the user chose for this LAN printer (see BBLocalMachine::ca_file). + std::string get_ca_file() const { return ca_file; } + void set_ca_file(std::string path, bool only_refresh = true); //PRINTER_TYPE printer_type = PRINTER_3DPrinter_UKNOWN; std::string printer_type; /* model_id */ diff --git a/src/slic3r/GUI/ReleaseNote.cpp b/src/slic3r/GUI/ReleaseNote.cpp index e7b70ab88a..f8845443a2 100644 --- a/src/slic3r/GUI/ReleaseNote.cpp +++ b/src/slic3r/GUI/ReleaseNote.cpp @@ -71,7 +71,9 @@ #include "slic3r/GUI/DeviceManager.hpp" #include "slic3r/GUI/HMS.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" +#include "slic3r/Utils/BBLPrinterAgent.hpp" #include "slic3r/Utils/NetworkAgent.hpp" +#include "slic3r/Utils/NetworkAgentFactory.hpp" #include #include @@ -1535,19 +1537,7 @@ InputIpAddressDialog::InputIpAddressDialog(wxWindow *parent) m_input_top_sizer->Add(m_tips_cafile, 0, wxTOP | wxEXPAND, FromDIP(10)); m_input_top_sizer->Add(cafile_input_sizer, 0, wxTOP | wxEXPAND, FromDIP(4)); m_input_top_sizer->Add(m_cafile_hint, 0, wxTOP | wxEXPAND, FromDIP(4)); - - if (!Http::ca_file_supported()) { - m_input_cafile->Disable(); - m_button_cafile->Disable(); - m_cafile_hint->SetLabel(_L("This system uses HTTPS certificates from the system Certificate Store or Keychain. To use a custom CA file, import it there.")); - m_cafile_hint->Wrap(FromDIP(352)); - } - - if (wxGetApp().preset_bundle) { - const auto& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; - if (config.has("printhost_cafile")) - m_input_cafile->SetValue(from_u8(config.opt_string("printhost_cafile"))); - } + init_cafile_input(); ip_input_top_panel->SetSizer(m_input_top_sizer); ip_input_top_panel->Layout(); @@ -1815,6 +1805,7 @@ void InputIpAddressDialog::set_machine_obj(MachineObject* obj) m_input_ip->GetTextCtrl()->ChangeValue(m_obj->get_dev_ip()); m_input_access_code->GetTextCtrl()->ChangeValue(m_obj->get_access_code()); m_input_printer_name->GetTextCtrl()->ChangeValue(m_obj->get_dev_name()); + init_cafile_input(); // m_obj may use another agent than the current one std::string img_str = DevPrinterConfigUtil::get_printer_connect_help_img(m_obj->printer_type); if (img_str.empty()) { img_str = "input_access_code_x1"; } @@ -1928,12 +1919,47 @@ void InputIpAddressDialog::on_ok(wxMouseEvent& evt) config.opt_string("print_host") = str_ip; if (!port.empty()) config.opt_string("printhost_port") = port; - if (Http::ca_file_supported()) + if (!is_bbl_agent() && Http::ca_file_supported()) config.opt_string("printhost_cafile") = m_input_cafile->GetValue().ToStdString(); } + std::string str_ca_file = is_bbl_agent() ? into_u8(m_input_cafile->GetValue().Strip(wxString::both)) : std::string(); token_.reset(this, nop_deleter); - m_thread = new boost::thread(boost::bind(&InputIpAddressDialog::workerThreadFunc, this, str_ip, str_access_code, str_sn, str_model_id, str_name)); + m_thread = new boost::thread(boost::bind(&InputIpAddressDialog::workerThreadFunc, this, str_ip, str_access_code, str_sn, str_model_id, str_name, str_ca_file)); +} + +// Bambu printers check certificates in the network plug-in and keep their CA per device; other +// printers use curl and the printer preset's CA. +void InputIpAddressDialog::init_cafile_input() +{ + const bool bbl_agent = is_bbl_agent(); + const bool editable = bbl_agent || Http::ca_file_supported(); + m_input_cafile->Enable(editable); + m_button_cafile->Enable(editable); + m_cafile_hint->SetLabel(editable ? _L("HTTPS CA file is optional. It is only needed if you use HTTPS with a self-signed certificate.") : + _L("This system uses HTTPS certificates from the system Certificate Store or Keychain. To use a custom CA file, import it there.")); + m_cafile_hint->Wrap(FromDIP(352)); + + wxString ca_file; + if (bbl_agent) { + if (m_obj) + ca_file = from_u8(m_obj->get_ca_file()); + } else if (wxGetApp().preset_bundle) { + const auto& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; + if (config.has("printhost_cafile")) + ca_file = from_u8(config.opt_string("printhost_cafile")); + } + m_input_cafile->ChangeValue(ca_file); +} + +bool InputIpAddressDialog::is_bbl_agent() const +{ + // Like MachineObject::connect: a printer without an agent id belongs to the current agent. + std::string agent_id = m_obj ? m_obj->printer_agent_id : std::string(); + if (agent_id.empty()) + if (DeviceManager* dev = wxGetApp().getDeviceManager()) + agent_id = dev->get_current_printer_agent_id(); + return agent_id.empty() || agent_id == BBL_PRINTER_AGENT_ID; } void InputIpAddressDialog::on_send_retry() @@ -1952,7 +1978,11 @@ void InputIpAddressDialog::on_send_retry() // check support function if (!m_obj) return; + const bool bbl_agent = is_bbl_agent(); + const std::string ca_file = into_u8(m_input_cafile->GetValue().Strip(wxString::both)); if (!m_obj->is_support_send_to_sdcard) { + if (bbl_agent) + m_obj->set_ca_file(ca_file); wxString input_str = wxString::Format("%s|%s", ip, str_access_code); auto event = wxCommandEvent(EVT_ENTER_IP_ADDRESS); event.SetString(input_str); @@ -1994,20 +2024,34 @@ void InputIpAddressDialog::on_send_retry() m_send_job->has_sdcard = m_obj->GetStorage()->get_sdcard_state() == DevStorage::SdcardState::HAS_SDCARD_NORMAL; m_send_job->set_check_mode(); m_send_job->set_project_name("verify_job"); + // The check connects before the CA is saved. + if (bbl_agent) + BBLPrinterAgent::trust_ca_file(m_obj->get_dev_id(), ca_file); m_send_job->on_check_ip_address_fail([this](int result) { this->check_ip_address_failed(result); }); - m_send_job->on_check_ip_address_success([this, ip, str_access_code]() { + // Runs on the job's worker thread. + m_send_job->on_check_ip_address_success([this, ip, str_access_code, bbl_agent, ca_file, dev_id = m_obj->get_dev_id()]() { + if (bbl_agent) { + wxGetApp().CallAfter([dev_id, ca_file]() { + if (DeviceManager* dev = wxGetApp().getDeviceManager()) + if (MachineObject* obj = dev->get_my_machine(dev_id)) + obj->set_ca_file(ca_file); + wxGetApp().app_config->save(); + }); + } wxString input_str = wxString::Format("%s|%s", ip, str_access_code); auto event = wxCommandEvent(EVT_ENTER_IP_ADDRESS); event.SetString(input_str); event.SetEventObject(this); wxPostEvent(this, event); - m_result = 0; - update_test_msg(_L("IP and Access Code Verified! You may close the window"), true); + CallAfter([this]() { + m_result = 0; + update_test_msg(_L("IP and Access Code Verified! You may close the window"), true); + }); }); replace_job(*m_worker, std::move(m_send_job)); @@ -2033,7 +2077,7 @@ void InputIpAddressDialog::post_update_test_msg(std::weak_ptr w = std::weak_ptr(token_); @@ -2090,7 +2134,7 @@ void InputIpAddressDialog::workerThreadFunc(std::string str_ip, std::string str_ } if (w.expired()) return; - CallAfter([this, detectData, str_ip, str_access_code, w]() { + CallAfter([this, detectData, str_ip, str_access_code, ca_file, w]() { DeviceManager* dev = wxGetApp().getDeviceManager(); BBLocalMachine machine; machine.dev_name = detectData.dev_name; @@ -2105,6 +2149,7 @@ void InputIpAddressDialog::workerThreadFunc(std::string str_ip, std::string str_ if (w.expired()) return; if (m_obj) { + m_obj->set_ca_file(ca_file, false); // saved together with the access code below m_obj->set_access_code(str_access_code); wxGetApp().getDeviceManager()->set_selected_machine(m_obj->get_dev_id()); } diff --git a/src/slic3r/GUI/ReleaseNote.hpp b/src/slic3r/GUI/ReleaseNote.hpp index fbb01ac0ee..71159feada 100644 --- a/src/slic3r/GUI/ReleaseNote.hpp +++ b/src/slic3r/GUI/ReleaseNote.hpp @@ -364,7 +364,9 @@ public: void on_send_retry(); void update_test_msg_event(wxCommandEvent &evt); void post_update_test_msg(std::weak_ptr w, wxString text, bool beconnect); - void workerThreadFunc(std::string str_ip, std::string str_access_code, std::string sn, std::string model_id, std::string name); + void workerThreadFunc(std::string str_ip, std::string str_access_code, std::string sn, std::string model_id, std::string name, std::string ca_file); + bool is_bbl_agent() const; + void init_cafile_input(); void OnTimer(wxTimerEvent& event); void on_text(wxCommandEvent& evt); void on_dpi_changed(const wxRect& suggested_rect) override; diff --git a/src/slic3r/Utils/BBLPrinterAgent.cpp b/src/slic3r/Utils/BBLPrinterAgent.cpp index fbf4826184..b71d6cd768 100644 --- a/src/slic3r/Utils/BBLPrinterAgent.cpp +++ b/src/slic3r/Utils/BBLPrinterAgent.cpp @@ -9,16 +9,31 @@ #include #include +#include +#include +#include +#include #include #include #include #include #include +#include +#include #include +#include +#include +#include +#include +#include +#include #include +#include +#include #include #include #include +#include #include #include using json = nlohmann::json; @@ -123,8 +138,84 @@ To as_abi(From fn) return reinterpret_cast(reinterpret_cast(fn)); } +// The certificates in pem, re-encoded, when there is at least one and every one is a CA; else "". +// Only what OpenSSL parsed ends up in printer.cer, never the rest of the file. +std::string ca_certificates_pem(const std::string& pem) +{ + std::unique_ptr in(BIO_new_mem_buf(pem.data(), int(pem.size())), &BIO_free); + std::unique_ptr out(BIO_new(BIO_s_mem()), &BIO_free); + if (!in || !out) + return {}; + + ERR_clear_error(); + int count = 0; + bool ok = true; + // Never prompt for a passphrase: an encrypted block counts as broken. + pem_password_cb* const no_passphrase = [](char*, int, int, void*) { return 0; }; + while (X509* cert = PEM_read_bio_X509(in.get(), nullptr, no_passphrase, nullptr)) { + ok = ok && X509_check_ca(cert) >= 1 && PEM_write_bio_X509(out.get(), cert) == 1; + X509_free(cert); + ++count; + } + // Reading ends with "no start line" at the end of the input; any other error is a broken certificate. + const unsigned long err = ERR_peek_last_error(); + ok = ok && count > 0 && ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE; + ERR_clear_error(); + if (!ok) + return {}; + + char* data = nullptr; + const long size = BIO_get_mem_data(out.get(), &data); + return std::string(data, size_t(size)); +} + +// Replaces path in one step and only when its content changes: the plug-in may read it at any time. +void replace_file(const boost::filesystem::path& path, const std::string& content) +{ + if (boost::filesystem::exists(path)) { + std::string current; + load_string_file(path, current); + if (current == content) + return; + } + const boost::filesystem::path tmp = path.string() + ".tmp"; + save_string_file(tmp, content); + if (const std::error_code ec = rename_file(tmp.string(), path.string())) + throw std::system_error(ec, "Cannot replace " + path.string()); +} + } // namespace +// The plug-in has one cert folder for all printers, and multi-printer sending talks to several at +// once, so the folder trusts the CA file of every printer connected this session. It is rebuilt and +// re-pointed on every connect: restarting networking points the plug-in back at the bundled folder +// (GUI_App), and a renewed, changed or cleared CA file is picked up. Re-pointing after start() +// takes effect on the next connection. +void BBLPrinterAgent::trust_ca_file(const std::string& dev_id, const std::string& ca_file) +{ + static std::mutex mutex; + static std::map ca_file_by_dev; + + auto& plugin = BBLNetworkPlugin::instance(); + auto agent = plugin.get_agent(); + auto set_cert_file = plugin.get_set_cert_file(); + if (!agent || !set_cert_file) + return; + + std::lock_guard lock(mutex); + if (ca_file.empty() && ca_file_by_dev.erase(dev_id) == 0) + return; // a printer without a CA leaves the folder as it is + if (!ca_file.empty()) + ca_file_by_dev[dev_id] = ca_file; + + std::set ca_files; + for (const auto& [id, file] : ca_file_by_dev) + ca_files.insert(file); + const std::string cert_dir = cert_dir_with_cas(resources_dir() + "/cert", data_dir() + "/cert", ca_files); + if (const int ret = set_cert_file(agent, cert_dir, "slicer_base64.cer"); ret != 0) + BOOST_LOG_TRIVIAL(warning) << "BBLPrinterAgent: set_cert_file(" << cert_dir << ") failed, ret = " << ret; +} + std::string BBLPrinterAgent::to_orca_filament_id(const std::string& printer_filament_id) const { const auto& map = bambu_filament_id_map().to_orca; @@ -296,11 +387,57 @@ int BBLPrinterAgent::connect_printer(const PrinterConnectionParams& params) } #endif if (func && agent) { + trust_ca_file(params.dev_id, params.ca_file); return func(agent, params.dev_id, params.host, params.username, params.password, use_ssl_for_mqtt); } return -1; } +std::string BBLPrinterAgent::cert_dir_with_cas(const std::string& bundled_dir, const std::string& out_dir, const std::set& extra_cas) +{ + namespace fs = boost::filesystem; + + std::string extra; + for (const std::string& ca_file : extra_cas) { + std::string pem; + try { + load_string_file(ca_file, pem); + } catch (const std::exception&) { + pem.clear(); + } + const std::string certs = ca_certificates_pem(pem); + if (certs.empty()) { + BOOST_LOG_TRIVIAL(warning) << "Ignoring CA file, it holds no readable CA certificate: " << ca_file; + continue; + } + extra += certs; + } + if (extra.empty()) + return bundled_dir; + + try { + std::string bundle; + load_string_file(fs::path(bundled_dir) / "printer.cer", bundle); + if (!bundle.empty() && bundle.back() != '\n') + bundle += '\n'; + + const fs::path out(out_dir); + fs::create_directories(out); + for (const fs::directory_entry& entry : fs::directory_iterator(bundled_dir)) { + if (!fs::is_regular_file(entry.status()) || entry.path().filename() == "printer.cer") + continue; + std::string content; + load_string_file(entry.path(), content); + replace_file(out / entry.path().filename(), content); + } + replace_file(out / "printer.cer", bundle + extra); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "Cannot build cert folder with custom CAs, using the bundled one: " << e.what(); + return bundled_dir; + } + return out_dir; +} + int BBLPrinterAgent::disconnect_printer() { auto& plugin = BBLNetworkPlugin::instance(); diff --git a/src/slic3r/Utils/BBLPrinterAgent.hpp b/src/slic3r/Utils/BBLPrinterAgent.hpp index 02e45276b6..73c20ee7c9 100644 --- a/src/slic3r/Utils/BBLPrinterAgent.hpp +++ b/src/slic3r/Utils/BBLPrinterAgent.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace Slic3r { class ICloudServiceAgent; } @@ -112,6 +113,16 @@ public: static std::string to_orca_payload(std::string json_text); static std::string from_orca_payload(std::string json_text); + // The plug-in checks LAN MQTT and FTPS certificates against /printer.cer. A printer + // behind a proxy with its own CA (the "HTTPS CA File" of the connect dialog) needs that CA there + // too. Writes out_dir/printer.cer as bundled_dir/printer.cer plus the certificates of every file + // in extra_cas that holds only CA certificates, copies the other files of bundled_dir, and + // returns out_dir. Files are replaced in one step, and only when their content changes. + // Returns bundled_dir when no extra CA is usable or out_dir cannot be written. + static std::string cert_dir_with_cas(const std::string& bundled_dir, const std::string& out_dir, const std::set& extra_cas); + // Sets the CA file the plug-in's cert folder trusts for dev_id; an empty ca_file removes it. + static void trust_ca_file(const std::string& dev_id, const std::string& ca_file); + private: int publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode); }; diff --git a/tests/libslic3r/test_appconfig.cpp b/tests/libslic3r/test_appconfig.cpp index 17c1bc268c..05990e7108 100644 --- a/tests/libslic3r/test_appconfig.cpp +++ b/tests/libslic3r/test_appconfig.cpp @@ -117,6 +117,7 @@ TEST_CASE("Local machine agent replacements survive save and reload", "[AppConfi saved.printer_type = "test-model"; saved.printer_agent_id = "orca"; saved.access_code = "old-key"; + saved.ca_file = "old-ca.crt"; config.update_local_machine(saved); config.save(); REQUIRE_FALSE(config.dirty()); @@ -124,6 +125,7 @@ TEST_CASE("Local machine agent replacements survive save and reload", "[AppConfi BBLocalMachine replacement = saved; replacement.printer_agent_id = "moonraker"; replacement.access_code = GENERATE("", "new-key", "88888888"); + replacement.ca_file = GENERATE("", "new-ca.crt"); config.update_local_machine(replacement); REQUIRE(config.dirty()); REQUIRE(config.get_local_machines().at(saved.dev_id) == replacement); diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index ef279428cf..d04f2e8e41 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -2,6 +2,7 @@ get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME) add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests_main.cpp test_bambu_filament_ids.cpp + test_bbl_cert_dir.cpp test_bed_exclusion_fields.cpp test_cloud_delete_queue.cpp test_config_value_formatter.cpp diff --git a/tests/slic3rutils/test_bbl_cert_dir.cpp b/tests/slic3rutils/test_bbl_cert_dir.cpp new file mode 100644 index 0000000000..671153b6a7 --- /dev/null +++ b/tests/slic3rutils/test_bbl_cert_dir.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include "libslic3r/Utils.hpp" +#include "slic3r/Utils/BBLPrinterAgent.hpp" +#include "test_utils.hpp" + +using namespace Slic3r; +namespace fs = boost::filesystem; + +namespace { + +// Stand-in for the bundled CA list. It is copied as it is, never parsed. +const std::string bundled_pem = "-----BEGIN CERTIFICATE-----\nBUNDLED\n-----END CERTIFICATE-----\n"; + +// Self-signed, basicConstraints CA:TRUE, valid until 2126. +const std::string ca_pem = "-----BEGIN CERTIFICATE-----\n" + "MIIBdDCCARqgAwIBAgIUHgU8NZU4wLWpjhUvuDFYyLC462YwCgYIKoZIzj0EAwIw\n" + "FzEVMBMGA1UEAwwMT3JjYSBUZXN0IENBMCAXDTI2MTAzMDE3NTcyNFoYDzIxMjYx\n" + "MDA2MTc1NzI0WjAXMRUwEwYDVQQDDAxPcmNhIFRlc3QgQ0EwWTATBgcqhkjOPQIB\n" + "BggqhkjOPQMBBwNCAASgb/DwDMUKTWsm+8Mqc9o646Co6OZsgZZUMkj/uZf8ZmcM\n" + "hJLS+iciD44/h37HHxw/r9f2l1kqv3mk3RalWJdWo0IwQDAdBgNVHQ4EFgQUYqhd\n" + "KI+8k/orAS81GcJ1D14QteIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" + "AgQwCgYIKoZIzj0EAwIDSAAwRQIgXgYJ+qQTNM0Cg0j7QilqsowswWaFX8eM8gLv\n" + "Jqa8nWcCIQCnLysLNA0PlKGWcfIqZ093RJg/y4lDq9vn9lp5Ss5NrQ==\n" + "-----END CERTIFICATE-----\n"; + +// Signed by the CA above, basicConstraints CA:FALSE: a server certificate, not a CA. +const std::string leaf_pem = "-----BEGIN CERTIFICATE-----\n" + "MIIBRjCB7aADAgECAhQETSnonAw6sZXxIjMMJZJr58MS8TAKBggqhkjOPQQDAjAX\n" + "MRUwEwYDVQQDDAxPcmNhIFRlc3QgQ0EwIBcNMjYxMDMwMTc1NzI0WhgPMjEyNjEw\n" + "MDYxNzU3MjRaMBwxGjAYBgNVBAMMEW9yY2EtdGVzdC1wcmludGVyMFkwEwYHKoZI\n" + "zj0CAQYIKoZIzj0DAQcDQgAEuLIhVucena1P1KJzYyW1i6kWmgqbG0/KrfosMeA+\n" + "+9Lt0zxSKwEntR5Gl9B1SuQsdsrBUv61toCyKctXp/lfXqMQMA4wDAYDVR0TAQH/\n" + "BAIwADAKBggqhkjOPQQDAgNIADBFAiEA7Qp7rXzT1UfVKSkVqmUICjFzxkTbSrxQ\n" + "5JHSKxTn6eICIES+RhZNXmt1D6MX04UYGeIF+LXKcSImuhaDWVDYoAPS\n" + "-----END CERTIFICATE-----\n"; + +std::string read_file(const fs::path& path) +{ + std::string content; + load_string_file(path, content); + return content; +} + +// A stand-in for resources/cert: the plug-in's CA bundle and the cloud certificate next to it. +struct BundledCertDir +{ + ScopedTemporaryDir dir{"orca-bbl-cert-bundled"}; + BundledCertDir() + { + save_string_file(dir.path() / "printer.cer", bundled_pem); + save_string_file(dir.path() / "slicer_base64.cer", "cloud"); + } +}; + +} // namespace + +TEST_CASE("A custom CA is appended to a copy of the bundled printer.cer", "[BBLCertDir]") +{ + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path ca = scratch.path() / "proxy-ca.crt"; + save_string_file(ca, ca_pem + "text after the certificate\n"); + + const std::string used = BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + + CHECK(used == out.string()); + CHECK(read_file(out / "printer.cer") == bundled_pem + ca_pem); // only the parsed certificate, not the trailing text + CHECK(read_file(out / "slicer_base64.cer") == "cloud"); + CHECK(read_file(bundled.dir.path() / "printer.cer") == bundled_pem); +} + +TEST_CASE("The bundled cert folder is kept when no custom CA is usable", "[BBLCertDir]") +{ + const std::string unusable = GENERATE("none", "missing", "not-pem", "broken-pem", "encrypted", "leaf-only", "ca-and-leaf"); + + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path file = scratch.path() / "ca.crt"; + + std::set extra_cas; + if (unusable != "none") + extra_cas.insert(file.string()); + if (unusable == "not-pem") + save_string_file(file, "hello"); + else if (unusable == "broken-pem") + save_string_file(file, "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"); + else if (unusable == "encrypted") // must not prompt for a passphrase + save_string_file(file, "-----BEGIN CERTIFICATE-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,000102030405060708090A0B0C0D0E0F\n\n" + + ca_pem.substr(ca_pem.find('\n') + 1)); + else if (unusable == "leaf-only") + save_string_file(file, leaf_pem); + else if (unusable == "ca-and-leaf") + save_string_file(file, ca_pem + leaf_pem); + + INFO("unusable CA: " << unusable); + CHECK(BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), extra_cas) == bundled.dir.path().string()); + CHECK_FALSE(fs::exists(out)); +} + +TEST_CASE("An unchanged cert folder is not rewritten", "[BBLCertDir]") +{ + BundledCertDir bundled; + ScopedTemporaryDir scratch{"orca-bbl-cert-out"}; + const fs::path out = scratch.path() / "cert"; + const fs::path ca = scratch.path() / "proxy-ca.crt"; + save_string_file(ca, ca_pem); + + BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + const std::time_t long_ago = 1000000000; + fs::last_write_time(out / "printer.cer", long_ago); + fs::last_write_time(out / "slicer_base64.cer", long_ago); + + BBLPrinterAgent::cert_dir_with_cas(bundled.dir.path().string(), out.string(), {ca.string()}); + + CHECK(fs::last_write_time(out / "printer.cer") == long_ago); + CHECK(fs::last_write_time(out / "slicer_base64.cer") == long_ago); + CHECK_FALSE(fs::exists(out / "printer.cer.tmp")); +} diff --git a/tests/slic3rutils/test_device_manager_integration.cpp b/tests/slic3rutils/test_device_manager_integration.cpp index 85b9170ba0..2994ca6793 100644 --- a/tests/slic3rutils/test_device_manager_integration.cpp +++ b/tests/slic3rutils/test_device_manager_integration.cpp @@ -64,8 +64,15 @@ public: return send_message(std::move(dev_id), std::move(json_str), qos, flag); } + int connect_printer(const PrinterConnectionParams& params) override + { + connected_ca_file = params.ca_file; + return 0; + } + std::string published_device; json published_message; + std::string connected_ca_file; private: AgentInfo m_info; @@ -270,6 +277,53 @@ TEST_CASE("Logging out cancels a pending last-machine restore", "[DeviceManager] CHECK_FALSE(manager.has_pending_last_machine_restore()); } +TEST_CASE("A CA file stays with the agent that saved it when a device is rebound", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + auto agent_a = std::make_shared("integration-agent-a"); + auto agent_b = std::make_shared("integration-agent-b"); + NetworkAgent network(nullptr, agent_a); + DeviceManager manager(&network, false, &app_config.config); + + BBLocalMachine machine; + machine.dev_id = "integration-lan-device"; + machine.dev_name = "Integration LAN device"; + machine.dev_ip = "192.0.2.10"; + machine.printer_type = "C11"; + + MachineObject* object = manager.insert_local_device(machine, "lan", "free", "", "access-code"); + REQUIRE(object != nullptr); + object->set_ca_file("agent-a-ca.crt"); + CHECK(app_config.config.get_local_machines().at(machine.dev_id).ca_file == "agent-a-ca.crt"); + + // Rebinding under the same agent keeps the CA file. + manager.insert_local_device(machine, "lan", "free", "", "access-code"); + CHECK(object->get_ca_file() == "agent-a-ca.crt"); + + network.set_printer_agent(agent_b); + manager.insert_local_device(machine, "lan", "free", "", "access-code"); + CHECK(object->printer_agent_id == "integration-agent-b"); + CHECK(object->get_ca_file().empty()); + CHECK(app_config.config.get_local_machines().at(machine.dev_id).ca_file.empty()); +} + +TEST_CASE("A device saved without an agent id connects with the CA file of the agent that connects it", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + const std::string agent_id = GENERATE(std::string(BBL_PRINTER_AGENT_ID), std::string("integration-agent")); + auto agent = std::make_shared(agent_id); + NetworkAgent network(nullptr, agent); + DeviceManager manager(&network, false, &app_config.config); + MachineObject object(&manager, &network, "Test printer", "integration-device", "192.0.2.10"); + object.set_access_code("access-code", false); + object.set_ca_file("device-ca.crt", false); + REQUIRE(object.printer_agent_id.empty()); + + REQUIRE(object.connect() == 0); + // Other agents take the CA from the printer preset, which this test has none of. + CHECK(agent->connected_ca_file == (agent_id == BBL_PRINTER_AGENT_ID ? "device-ca.crt" : "")); +} + TEST_CASE("AMS filament settings keep legacy single-color commands compatible", "[DeviceManager][AMSMaterialsSetting][integration]") { ScopedAppConfig app_config;