ethernet_interface: Validate gateway IPs

We don't want to allow loopback, network id, or multicast spaces to be
used for the gateway.

Change-Id: I1ff762268321f8c0dacb760611cce8383d880997
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/src/ethernet_interface.cpp b/src/ethernet_interface.cpp
index e7a2c29..3374c6f 100644
--- a/src/ethernet_interface.cpp
+++ b/src/ethernet_interface.cpp
@@ -71,6 +71,12 @@
     return ret;
 }
 
+template <typename Addr>
+static bool validIntfIP(Addr a) noexcept
+{
+    return a.isUnicast() && !a.isLoopback();
+}
+
 EthernetInterface::EthernetInterface(stdplus::PinnedRef<sdbusplus::bus_t> bus,
                                      stdplus::PinnedRef<Manager> manager,
                                      const AllIntfInfo& info,
@@ -826,6 +832,10 @@
             gw.clear();
             return;
         }
+        if (!validIntfIP(ip))
+        {
+            throw std::invalid_argument("Invalid unicast");
+        }
         gw = stdplus::toStr(ip);
     }
     catch (const std::exception& e)
diff --git a/test/test_ethernet_interface.cpp b/test/test_ethernet_interface.cpp
index 4156506..21062f4 100644
--- a/test/test_ethernet_interface.cpp
+++ b/test/test_ethernet_interface.cpp
@@ -19,6 +19,7 @@
 namespace network
 {
 
+using sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
 using std::literals::string_view_literals::operator""sv;
 using testing::Key;
 using testing::UnorderedElementsAre;
@@ -174,6 +175,10 @@
     std::string gateway = "10.3.3.3";
     interface.defaultGateway(gateway);
     EXPECT_EQ(interface.defaultGateway(), gateway);
+    EXPECT_THROW(interface.defaultGateway6("127.0.0.10"), InvalidArgument);
+    EXPECT_THROW(interface.defaultGateway6("0.0.0.0"), InvalidArgument);
+    EXPECT_THROW(interface.defaultGateway6("224.1.0.0"), InvalidArgument);
+    EXPECT_EQ(interface.defaultGateway(), gateway);
     interface.defaultGateway("");
     EXPECT_EQ(interface.defaultGateway(), "");
     interface.defaultGateway("0.0.0.0");
@@ -182,9 +187,11 @@
 
 TEST_F(TestEthernetInterface, addGateway6)
 {
-    std::string gateway6 = "ffff:ffff:ffff:fe80::1";
+    std::string gateway6 = "fe80::1";
     interface.defaultGateway6(gateway6);
     EXPECT_EQ(interface.defaultGateway6(), gateway6);
+    EXPECT_THROW(interface.defaultGateway6("::1"), InvalidArgument);
+    EXPECT_EQ(interface.defaultGateway6(), gateway6);
     interface.defaultGateway6("");
     EXPECT_EQ(interface.defaultGateway6(), "");
     interface.defaultGateway6("::");