[logging] Fix possible overflow in syslog::SetTags

Bug: 40982
Change-Id: I574ce3cb445b3b595e0f3b865a7e68dea5a56d99
Reviewed-on: https://fuchsia-review.googlesource.com/c/fuchsia/+/385993
Commit-Queue: Saman Sami <samans@google.com>
Reviewed-by: Adam Barth <abarth@google.com>
Testability-Review: Adam Barth <abarth@google.com>
diff --git a/sdk/lib/syslog/cpp/logging_backend_fuchsia.cc b/sdk/lib/syslog/cpp/logging_backend_fuchsia.cc
index e1a1f690b..ad5ba05 100644
--- a/sdk/lib/syslog/cpp/logging_backend_fuchsia.cc
+++ b/sdk/lib/syslog/cpp/logging_backend_fuchsia.cc
@@ -26,9 +26,11 @@
 void SetLogSettings(const syslog::LogSettings& settings,
                     const std::initializer_list<std::string>& tags) {
   const char* ctags[FX_LOG_MAX_TAGS];
-  int i = 0;
+  size_t num_tags = 0;
   for (auto& tag : tags) {
-    ctags[i++] = tag.c_str();
+    ctags[num_tags++] = tag.c_str();
+    if (num_tags >= FX_LOG_MAX_TAGS)
+      break;
   }
   int fd = -1;
   if (!settings.log_file.empty()) {
@@ -41,7 +43,7 @@
                                .console_fd = fd,
                                .log_service_channel = ZX_HANDLE_INVALID,
                                .tags = ctags,
-                               .num_tags = tags.size()};
+                               .num_tags = num_tags};
   fx_log_reconfigure(&config);
 }
 
diff --git a/sdk/lib/syslog/cpp/logging_socket_unittest.cc b/sdk/lib/syslog/cpp/logging_socket_unittest.cc
index 5e9cc67..c450b3f1 100644
--- a/sdk/lib/syslog/cpp/logging_socket_unittest.cc
+++ b/sdk/lib/syslog/cpp/logging_socket_unittest.cc
@@ -199,5 +199,13 @@
   CheckSocketEmpty();
 }
 
+TEST_F(LoggingSocketTest, TooManyTags) {
+  constexpr const char* kLogMessage = "Hello";
+  syslog::SetTags({"1", "2", "3", "4", "5"});
+  FX_LOGS(ERROR) << kLogMessage;
+  ReadPacketAndCompare(FX_LOG_ERROR, kLogMessage, {"1", "2", "3", "4"});
+  CheckSocketEmpty();
+}
+
 }  // namespace
 }  // namespace syslog