diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp index c9b72a0c72..2bd86949e3 100644 --- a/esphome/components/wifi/wifi_component.cpp +++ b/esphome/components/wifi/wifi_component.cpp @@ -364,7 +364,8 @@ WiFiAP WiFiComponent::build_selected_ap_() const { params.set_hidden(true); // For hidden networks, clear BSSID and channel even if set in config // There might be multiple hidden networks with same SSID but we can't know which is correct - // Rely on probe-req with just SSID. Leaving channel empty triggers ALL_CHANNEL_SCAN. + // Rely on probe-req with just SSID. Empty channel triggers ALL_CHANNEL_SCAN. + // Note: Scan data is never used for hidden networks (see check below at line ~390) params.set_bssid(optional{}); params.set_channel(optional{}); } else { @@ -810,7 +811,11 @@ void WiFiComponent::retry_connect() { if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_() && (this->num_retried_ > 3 || this->error_from_callback_)) { #ifdef USE_WIFI_FAST_CONNECT - if (this->trying_loaded_ap_) { + if (this->sta_.empty()) { + // No configured networks - shouldn't happen in fast_connect mode, but handle defensively + ESP_LOGW(TAG, "No configured networks available"); + this->restart_adapter(); + } else if (this->trying_loaded_ap_) { this->trying_loaded_ap_ = false; this->selected_sta_index_ = 0; // Retry from the first configured AP this->reset_for_next_ap_attempt_(); @@ -890,7 +895,7 @@ bool WiFiComponent::load_fast_connect_settings_() { if (this->fast_connect_pref_.load(&fast_connect_save)) { // Validate saved AP index - if (static_cast(fast_connect_save.ap_index) >= this->sta_.size()) { + if (fast_connect_save.ap_index < 0 || static_cast(fast_connect_save.ap_index) >= this->sta_.size()) { ESP_LOGW(TAG, "Saved AP index out of bounds"); return false; } diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index 9c7f9a4e7a..defce1d0ac 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -375,6 +375,10 @@ class WiFiComponent : public Component { for (size_t i = 0; i < this->sta_.size(); i++) { if (scan_res.matches(this->sta_[i])) { + if (i > std::numeric_limits::max()) { + ESP_LOGE(TAG, "Matched AP index %zu exceeds int8_t range", i); + continue; + } this->selected_sta_index_ = static_cast(i); // Links scan_result_[0] with sta_[i] return true; }