xref: /openbmc/bmcweb/redfish-core/lib/network_protocol.hpp (revision 52cc112d962920b035c870127784bcbd98948fad)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include "error_messages.hpp"
19 #include "node.hpp"
20 #include "openbmc_dbus_rest.hpp"
21 
22 #include <utils/json_utils.hpp>
23 
24 #include <optional>
25 #include <variant>
26 namespace redfish
27 {
28 
29 enum NetworkProtocolUnitStructFields
30 {
31     NET_PROTO_UNIT_NAME,
32     NET_PROTO_UNIT_DESC,
33     NET_PROTO_UNIT_LOAD_STATE,
34     NET_PROTO_UNIT_ACTIVE_STATE,
35     NET_PROTO_UNIT_SUB_STATE,
36     NET_PROTO_UNIT_DEVICE,
37     NET_PROTO_UNIT_OBJ_PATH,
38     NET_PROTO_UNIT_ALWAYS_0,
39     NET_PROTO_UNIT_ALWAYS_EMPTY,
40     NET_PROTO_UNIT_ALWAYS_ROOT_PATH
41 };
42 
43 enum NetworkProtocolListenResponseElements
44 {
45     NET_PROTO_LISTEN_TYPE,
46     NET_PROTO_LISTEN_STREAM
47 };
48 
49 /**
50  * @brief D-Bus Unit structure returned in array from ListUnits Method
51  */
52 using UnitStruct =
53     std::tuple<std::string, std::string, std::string, std::string, std::string,
54                std::string, sdbusplus::message::object_path, uint32_t,
55                std::string, sdbusplus::message::object_path>;
56 
57 const static boost::container::flat_map<const char*, std::string>
58     protocolToDBus{{"SSH", "dropbear"},
59                    {"HTTPS", "bmcweb"},
60                    {"IPMI", "phosphor-ipmi-net"}};
61 
62 inline void
63     extractNTPServersAndDomainNamesData(const GetManagedObjects& dbus_data,
64                                         std::vector<std::string>& ntpData,
65                                         std::vector<std::string>& dnData)
66 {
67     for (const auto& obj : dbus_data)
68     {
69         for (const auto& ifacePair : obj.second)
70         {
71             if (obj.first == "/xyz/openbmc_project/network/eth0")
72             {
73                 if (ifacePair.first ==
74                     "xyz.openbmc_project.Network.EthernetInterface")
75                 {
76                     for (const auto& propertyPair : ifacePair.second)
77                     {
78                         if (propertyPair.first == "NTPServers")
79                         {
80                             const std::vector<std::string>* ntpServers =
81                                 std::get_if<std::vector<std::string>>(
82                                     &propertyPair.second);
83                             if (ntpServers != nullptr)
84                             {
85                                 ntpData = std::move(*ntpServers);
86                             }
87                         }
88                         else if (propertyPair.first == "DomainName")
89                         {
90                             const std::vector<std::string>* domainNames =
91                                 std::get_if<std::vector<std::string>>(
92                                     &propertyPair.second);
93                             if (domainNames != nullptr)
94                             {
95                                 dnData = std::move(*domainNames);
96                             }
97                         }
98                     }
99                 }
100             }
101         }
102     }
103 }
104 
105 template <typename CallbackFunc>
106 void getEthernetIfaceData(CallbackFunc&& callback)
107 {
108     crow::connections::systemBus->async_method_call(
109         [callback{std::move(callback)}](
110             const boost::system::error_code error_code,
111             const GetManagedObjects& dbus_data) {
112             std::vector<std::string> ntpServers;
113             std::vector<std::string> domainNames;
114 
115             if (error_code)
116             {
117                 callback(false, ntpServers, domainNames);
118                 return;
119             }
120 
121             extractNTPServersAndDomainNamesData(dbus_data, ntpServers,
122                                                 domainNames);
123 
124             callback(true, ntpServers, domainNames);
125         },
126         "xyz.openbmc_project.Network", "/xyz/openbmc_project/network",
127         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
128 }
129 
130 class NetworkProtocol : public Node
131 {
132   public:
133     NetworkProtocol(App& app) :
134         Node(app, "/redfish/v1/Managers/bmc/NetworkProtocol/")
135     {
136         entityPrivileges = {
137             {boost::beast::http::verb::get, {{"Login"}}},
138             {boost::beast::http::verb::head, {{"Login"}}},
139             {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
140             {boost::beast::http::verb::put, {{"ConfigureManager"}}},
141             {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
142             {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
143     }
144 
145   private:
146     void doGet(crow::Response& res, const crow::Request& req,
147                const std::vector<std::string>& params) override
148     {
149         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
150 
151         getData(asyncResp);
152     }
153 
154     std::string getHostName() const
155     {
156         std::string hostName;
157 
158         std::array<char, HOST_NAME_MAX> hostNameCStr;
159         if (gethostname(hostNameCStr.data(), hostNameCStr.size()) == 0)
160         {
161             hostName = hostNameCStr.data();
162         }
163         return hostName;
164     }
165 
166     void getNTPProtocolEnabled(const std::shared_ptr<AsyncResp>& asyncResp)
167     {
168         crow::connections::systemBus->async_method_call(
169             [asyncResp](const boost::system::error_code error_code,
170                         const std::variant<std::string>& timeSyncMethod) {
171                 const std::string* s =
172                     std::get_if<std::string>(&timeSyncMethod);
173 
174                 if (*s == "xyz.openbmc_project.Time.Synchronization.Method.NTP")
175                 {
176                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = true;
177                 }
178                 else if (*s == "xyz.openbmc_project.Time.Synchronization."
179                                "Method.Manual")
180                 {
181                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = false;
182                 }
183             },
184             "xyz.openbmc_project.Settings",
185             "/xyz/openbmc_project/time/sync_method",
186             "org.freedesktop.DBus.Properties", "Get",
187             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod");
188     }
189 
190     void getData(const std::shared_ptr<AsyncResp>& asyncResp)
191     {
192         asyncResp->res.jsonValue["@odata.type"] =
193             "#ManagerNetworkProtocol.v1_5_0.ManagerNetworkProtocol";
194         asyncResp->res.jsonValue["@odata.id"] =
195             "/redfish/v1/Managers/bmc/NetworkProtocol";
196         asyncResp->res.jsonValue["Id"] = "NetworkProtocol";
197         asyncResp->res.jsonValue["Name"] = "Manager Network Protocol";
198         asyncResp->res.jsonValue["Description"] = "Manager Network Service";
199         asyncResp->res.jsonValue["Status"]["Health"] = "OK";
200         asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
201         asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
202         asyncResp->res.jsonValue["SNMP"]["ProtocolEnabled"] = true;
203         asyncResp->res.jsonValue["SNMP"]["Port"] = 161;
204         asyncResp->res.jsonValue["SNMP"]["AuthenticationProtocol"] =
205             "CommunityString";
206         asyncResp->res.jsonValue["SNMP"]["CommunityAccessMode"] = "Full";
207         asyncResp->res.jsonValue["SNMP"]["HideCommunityStrings"] = true;
208         asyncResp->res
209             .jsonValue["SNMP"]["EngineId"]["EnterpriseSpecificMethod"] =
210             nullptr;
211         asyncResp->res.jsonValue["SNMP"]["EngineId"]["PrivateEnterpriseId"] =
212             nullptr;
213         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv1"] = false;
214         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv2c"] = true;
215         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv3"] = false;
216         asyncResp->res.jsonValue["SNMP"]["EncryptionProtocol"] = "None";
217         nlohmann::json& memberArray =
218             asyncResp->res.jsonValue["SNMP"]["CommunityStrings"];
219         memberArray = nlohmann::json::array();
220         memberArray.push_back({{"AccessMode", "Full"}});
221         memberArray.push_back({{"CommunityString", ""}});
222         memberArray.push_back({{"Name", ""}});
223 
224         // HTTP is Mandatory attribute as per OCP Baseline Profile - v1.0.0,
225         // but from security perspective it is not recommended to use.
226         // Hence using protocolEnabled as false to make it OCP and security-wise
227         // compliant
228         asyncResp->res.jsonValue["HTTP"]["Port"] = 0;
229         asyncResp->res.jsonValue["HTTP"]["ProtocolEnabled"] = false;
230 
231         for (auto& protocol : protocolToDBus)
232         {
233             asyncResp->res.jsonValue[protocol.first]["Port"] =
234                 nlohmann::detail::value_t::null;
235             asyncResp->res.jsonValue[protocol.first]["ProtocolEnabled"] = false;
236         }
237 
238         std::string hostName = getHostName();
239 
240         asyncResp->res.jsonValue["HostName"] = hostName;
241 
242         getNTPProtocolEnabled(asyncResp);
243 
244         // TODO Get eth0 interface data, and call the below callback for JSON
245         // preparation
246         getEthernetIfaceData(
247             [hostName, asyncResp](const bool& success,
248                                   const std::vector<std::string>& ntpServers,
249                                   const std::vector<std::string>& domainNames) {
250                 if (!success)
251                 {
252                     messages::resourceNotFound(asyncResp->res,
253                                                "EthernetInterface", "eth0");
254                     return;
255                 }
256                 asyncResp->res.jsonValue["NTP"]["NTPServers"] = ntpServers;
257                 if (hostName.empty() == false)
258                 {
259                     std::string FQDN = std::move(hostName);
260                     if (domainNames.empty() == false)
261                     {
262                         FQDN += "." + domainNames[0];
263                     }
264                     asyncResp->res.jsonValue["FQDN"] = std::move(FQDN);
265                 }
266             });
267 
268         crow::connections::systemBus->async_method_call(
269             [asyncResp](const boost::system::error_code e,
270                         const std::vector<UnitStruct>& r) {
271                 if (e)
272                 {
273                     asyncResp->res.jsonValue = nlohmann::json::object();
274                     messages::internalError(asyncResp->res);
275                     return;
276                 }
277                 asyncResp->res.jsonValue["HTTPS"]["Certificates"] = {
278                     {"@odata.id", "/redfish/v1/Managers/bmc/NetworkProtocol/"
279                                   "HTTPS/Certificates"}};
280 
281                 for (auto& unit : r)
282                 {
283                     /* Only traverse through <xyz>.socket units */
284                     std::string unitName = std::get<NET_PROTO_UNIT_NAME>(unit);
285                     if (!boost::ends_with(unitName, ".socket"))
286                     {
287                         continue;
288                     }
289 
290                     for (auto& kv : protocolToDBus)
291                     {
292                         // We are interested in services, which starts with
293                         // mapped service name
294                         if (!boost::starts_with(unitName, kv.second))
295                         {
296                             continue;
297                         }
298                         const char* rfServiceKey = kv.first;
299                         std::string socketPath =
300                             std::get<NET_PROTO_UNIT_OBJ_PATH>(unit);
301                         std::string unitState =
302                             std::get<NET_PROTO_UNIT_SUB_STATE>(unit);
303 
304                         asyncResp->res
305                             .jsonValue[rfServiceKey]["ProtocolEnabled"] =
306                             (unitState == "running") ||
307                             (unitState == "listening");
308 
309                         crow::connections::systemBus->async_method_call(
310                             [asyncResp,
311                              rfServiceKey{std::string(rfServiceKey)}](
312                                 const boost::system::error_code ec,
313                                 const std::variant<std::vector<std::tuple<
314                                     std::string, std::string>>>& resp) {
315                                 if (ec)
316                                 {
317                                     messages::internalError(asyncResp->res);
318                                     return;
319                                 }
320                                 const std::vector<
321                                     std::tuple<std::string, std::string>>*
322                                     responsePtr = std::get_if<std::vector<
323                                         std::tuple<std::string, std::string>>>(
324                                         &resp);
325                                 if (responsePtr == nullptr ||
326                                     responsePtr->size() < 1)
327                                 {
328                                     return;
329                                 }
330 
331                                 const std::string& listenStream =
332                                     std::get<NET_PROTO_LISTEN_STREAM>(
333                                         (*responsePtr)[0]);
334                                 std::size_t lastColonPos =
335                                     listenStream.rfind(":");
336                                 if (lastColonPos == std::string::npos)
337                                 {
338                                     // Not a port
339                                     return;
340                                 }
341                                 std::string portStr =
342                                     listenStream.substr(lastColonPos + 1);
343                                 if (portStr.empty())
344                                 {
345                                     return;
346                                 }
347                                 char* endPtr = nullptr;
348                                 errno = 0;
349                                 // Use strtol instead of stroi to avoid
350                                 // exceptions
351                                 long port =
352                                     std::strtol(portStr.c_str(), &endPtr, 10);
353                                 if ((errno == 0) && (*endPtr == '\0'))
354                                 {
355                                     asyncResp->res
356                                         .jsonValue[rfServiceKey]["Port"] = port;
357                                 }
358                                 return;
359                             },
360                             "org.freedesktop.systemd1", socketPath,
361                             "org.freedesktop.DBus.Properties", "Get",
362                             "org.freedesktop.systemd1.Socket", "Listen");
363 
364                         // We found service, break the inner loop.
365                         break;
366                     }
367                 }
368             },
369             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
370             "org.freedesktop.systemd1.Manager", "ListUnits");
371     }
372 
373     void handleHostnamePatch(const std::string& hostName,
374                              const std::shared_ptr<AsyncResp>& asyncResp)
375     {
376         crow::connections::systemBus->async_method_call(
377             [asyncResp](const boost::system::error_code ec) {
378                 if (ec)
379                 {
380                     messages::internalError(asyncResp->res);
381                     return;
382                 }
383             },
384             "xyz.openbmc_project.Network",
385             "/xyz/openbmc_project/network/config",
386             "org.freedesktop.DBus.Properties", "Set",
387             "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
388             std::variant<std::string>(hostName));
389     }
390 
391     void handleNTPProtocolEnabled(const bool& ntpEnabled,
392                                   const std::shared_ptr<AsyncResp>& asyncResp)
393     {
394         std::string timeSyncMethod;
395         if (ntpEnabled)
396         {
397             timeSyncMethod =
398                 "xyz.openbmc_project.Time.Synchronization.Method.NTP";
399         }
400         else
401         {
402             timeSyncMethod =
403                 "xyz.openbmc_project.Time.Synchronization.Method.Manual";
404         }
405 
406         crow::connections::systemBus->async_method_call(
407             [asyncResp](const boost::system::error_code error_code) {},
408             "xyz.openbmc_project.Settings",
409             "/xyz/openbmc_project/time/sync_method",
410             "org.freedesktop.DBus.Properties", "Set",
411             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod",
412             std::variant<std::string>{timeSyncMethod});
413     }
414 
415     void handleNTPServersPatch(const std::vector<std::string>& ntpServers,
416                                const std::shared_ptr<AsyncResp>& asyncResp)
417     {
418         crow::connections::systemBus->async_method_call(
419             [asyncResp](const boost::system::error_code ec) {
420                 if (ec)
421                 {
422                     messages::internalError(asyncResp->res);
423                     return;
424                 }
425             },
426             "xyz.openbmc_project.Network", "/xyz/openbmc_project/network/eth0",
427             "org.freedesktop.DBus.Properties", "Set",
428             "xyz.openbmc_project.Network.EthernetInterface", "NTPServers",
429             std::variant<std::vector<std::string>>{ntpServers});
430     }
431 
432     void handleIpmiProtocolEnabled(const bool ipmiProtocolEnabled,
433                                    const std::shared_ptr<AsyncResp>& asyncResp)
434     {
435         crow::connections::systemBus->async_method_call(
436             [ipmiProtocolEnabled,
437              asyncResp](const boost::system::error_code ec,
438                         const crow::openbmc_mapper::GetSubTreeType& subtree) {
439                 if (ec)
440                 {
441                     messages::internalError(asyncResp->res);
442                     return;
443                 }
444 
445                 constexpr char const* netipmidBasePath =
446                     "/xyz/openbmc_project/control/service/"
447                     "phosphor_2dipmi_2dnet_40";
448 
449                 for (const auto& entry : subtree)
450                 {
451                     if (boost::algorithm::starts_with(entry.first,
452                                                       netipmidBasePath))
453                     {
454                         crow::connections::systemBus->async_method_call(
455                             [ipmiProtocolEnabled,
456                              asyncResp](const boost::system::error_code ec) {
457                                 if (ec)
458                                 {
459                                     messages::internalError(asyncResp->res);
460                                     return;
461                                 }
462                             },
463                             entry.second.begin()->first, entry.first,
464                             "org.freedesktop.DBus.Properties", "Set",
465                             "xyz.openbmc_project.Control.Service.Attributes",
466                             "Running", std::variant<bool>{ipmiProtocolEnabled});
467 
468                         crow::connections::systemBus->async_method_call(
469                             [ipmiProtocolEnabled,
470                              asyncResp](const boost::system::error_code ec) {
471                                 if (ec)
472                                 {
473                                     messages::internalError(asyncResp->res);
474                                     return;
475                                 }
476                             },
477                             entry.second.begin()->first, entry.first,
478                             "org.freedesktop.DBus.Properties", "Set",
479                             "xyz.openbmc_project.Control.Service.Attributes",
480                             "Enabled", std::variant<bool>{ipmiProtocolEnabled});
481                     }
482                 }
483             },
484             "xyz.openbmc_project.ObjectMapper",
485             "/xyz/openbmc_project/object_mapper",
486             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
487             "/xyz/openbmc_project/control/service", 0,
488             std::array<const char*, 1>{
489                 "xyz.openbmc_project.Control.Service.Attributes"});
490     }
491 
492     void doPatch(crow::Response& res, const crow::Request& req,
493                  const std::vector<std::string>& params) override
494     {
495         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
496         std::optional<std::string> newHostName;
497         std::optional<nlohmann::json> ntp;
498         std::optional<nlohmann::json> ipmi;
499 
500         if (!json_util::readJson(req, res, "HostName", newHostName, "NTP", ntp,
501                                  "IPMI", ipmi))
502         {
503             return;
504         }
505 
506         res.result(boost::beast::http::status::no_content);
507         if (newHostName)
508         {
509             handleHostnamePatch(*newHostName, asyncResp);
510         }
511 
512         if (ntp)
513         {
514             std::optional<std::vector<std::string>> ntpServers;
515             std::optional<bool> ntpEnabled;
516             if (!json_util::readJson(*ntp, res, "NTPServers", ntpServers,
517                                      "ProtocolEnabled", ntpEnabled))
518             {
519                 return;
520             }
521 
522             if (ntpEnabled)
523             {
524                 handleNTPProtocolEnabled(*ntpEnabled, asyncResp);
525             }
526 
527             if (ntpServers)
528             {
529                 std::sort((*ntpServers).begin(), (*ntpServers).end());
530                 (*ntpServers)
531                     .erase(
532                         std::unique((*ntpServers).begin(), (*ntpServers).end()),
533                         (*ntpServers).end());
534                 handleNTPServersPatch(*ntpServers, asyncResp);
535             }
536         }
537 
538         if (ipmi)
539         {
540             std::optional<bool> ipmiProtocolEnabled;
541             if (!json_util::readJson(*ipmi, res, "ProtocolEnabled",
542                                      ipmiProtocolEnabled))
543             {
544                 return;
545             }
546 
547             if (ipmiProtocolEnabled)
548             {
549                 handleIpmiProtocolEnabled(*ipmiProtocolEnabled, asyncResp);
550             }
551         }
552     }
553 };
554 
555 } // namespace redfish
556