xref: /openbmc/bmcweb/features/redfish/lib/network_protocol.hpp (revision ed4de7a8a5601b58b2e29824b10bf7fcc699a1b8)
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 "app.hpp"
19 #include "dbus_utility.hpp"
20 #include "error_messages.hpp"
21 #include "openbmc_dbus_rest.hpp"
22 #include "query.hpp"
23 #include "redfish_util.hpp"
24 #include "registries/privilege_registry.hpp"
25 #include "utils/json_utils.hpp"
26 #include "utils/stl_utils.hpp"
27 
28 #include <boost/system/error_code.hpp>
29 #include <sdbusplus/asio/property.hpp>
30 
31 #include <array>
32 #include <optional>
33 #include <string_view>
34 #include <variant>
35 
36 namespace redfish
37 {
38 
39 void getNTPProtocolEnabled(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp);
40 std::string getHostName();
41 
42 static constexpr std::string_view sshServiceName = "dropbear";
43 static constexpr std::string_view httpsServiceName = "bmcweb";
44 static constexpr std::string_view ipmiServiceName = "phosphor-ipmi-net";
45 
46 // Mapping from Redfish NetworkProtocol key name to backend service that hosts
47 // that protocol.
48 static constexpr std::array<std::pair<std::string_view, std::string_view>, 3>
49     networkProtocolToDbus = {{{"SSH", sshServiceName},
50                               {"HTTPS", httpsServiceName},
51                               {"IPMI", ipmiServiceName}}};
52 
53 inline void extractNTPServersAndDomainNamesData(
54     const dbus::utility::ManagedObjectType& dbusData,
55     std::vector<std::string>& ntpData, std::vector<std::string>& dnData)
56 {
57     for (const auto& obj : dbusData)
58     {
59         for (const auto& ifacePair : obj.second)
60         {
61             if (ifacePair.first !=
62                 "xyz.openbmc_project.Network.EthernetInterface")
63             {
64                 continue;
65             }
66 
67             for (const auto& propertyPair : ifacePair.second)
68             {
69                 if (propertyPair.first == "StaticNTPServers")
70                 {
71                     const std::vector<std::string>* ntpServers =
72                         std::get_if<std::vector<std::string>>(
73                             &propertyPair.second);
74                     if (ntpServers != nullptr)
75                     {
76                         ntpData.insert(ntpData.end(), ntpServers->begin(),
77                                        ntpServers->end());
78                     }
79                 }
80                 else if (propertyPair.first == "DomainName")
81                 {
82                     const std::vector<std::string>* domainNames =
83                         std::get_if<std::vector<std::string>>(
84                             &propertyPair.second);
85                     if (domainNames != nullptr)
86                     {
87                         dnData.insert(dnData.end(), domainNames->begin(),
88                                       domainNames->end());
89                     }
90                 }
91             }
92         }
93     }
94     stl_utils::removeDuplicate(ntpData);
95     stl_utils::removeDuplicate(dnData);
96 }
97 
98 template <typename CallbackFunc>
99 void getEthernetIfaceData(CallbackFunc&& callback)
100 {
101     sdbusplus::message::object_path path("/xyz/openbmc_project/network");
102     dbus::utility::getManagedObjects(
103         "xyz.openbmc_project.Network", path,
104         [callback = std::forward<CallbackFunc>(callback)](
105             const boost::system::error_code& ec,
106             const dbus::utility::ManagedObjectType& dbusData) {
107         std::vector<std::string> ntpServers;
108         std::vector<std::string> domainNames;
109 
110         if (ec)
111         {
112             callback(false, ntpServers, domainNames);
113             return;
114         }
115 
116         extractNTPServersAndDomainNamesData(dbusData, ntpServers, domainNames);
117 
118         callback(true, ntpServers, domainNames);
119     });
120 }
121 
122 inline void afterNetworkPortRequest(
123     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
124     const boost::system::error_code& ec,
125     const std::vector<std::tuple<std::string, std::string, bool>>& socketData)
126 {
127     if (ec)
128     {
129         messages::internalError(asyncResp->res);
130         return;
131     }
132     for (const auto& data : socketData)
133     {
134         const std::string& socketPath = get<0>(data);
135         const std::string& protocolName = get<1>(data);
136         bool isProtocolEnabled = get<2>(data);
137 
138         asyncResp->res.jsonValue[protocolName]["ProtocolEnabled"] =
139             isProtocolEnabled;
140         asyncResp->res.jsonValue[protocolName]["Port"] = nullptr;
141         getPortNumber(socketPath, [asyncResp, protocolName](
142                                       const boost::system::error_code& ec2,
143                                       int portNumber) {
144             if (ec2)
145             {
146                 messages::internalError(asyncResp->res);
147                 return;
148             }
149             asyncResp->res.jsonValue[protocolName]["Port"] = portNumber;
150         });
151     }
152 }
153 
154 inline void getNetworkData(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
155                            const crow::Request& req)
156 {
157     if (req.session == nullptr)
158     {
159         messages::internalError(asyncResp->res);
160         return;
161     }
162 
163     asyncResp->res.addHeader(
164         boost::beast::http::field::link,
165         "</redfish/v1/JsonSchemas/ManagerNetworkProtocol/NetworkProtocol.json>; rel=describedby");
166     asyncResp->res.jsonValue["@odata.type"] =
167         "#ManagerNetworkProtocol.v1_5_0.ManagerNetworkProtocol";
168     asyncResp->res.jsonValue["@odata.id"] =
169         "/redfish/v1/Managers/bmc/NetworkProtocol";
170     asyncResp->res.jsonValue["Id"] = "NetworkProtocol";
171     asyncResp->res.jsonValue["Name"] = "Manager Network Protocol";
172     asyncResp->res.jsonValue["Description"] = "Manager Network Service";
173     asyncResp->res.jsonValue["Status"]["Health"] = "OK";
174     asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
175     asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
176 
177     // HTTP is Mandatory attribute as per OCP Baseline Profile - v1.0.0,
178     // but from security perspective it is not recommended to use.
179     // Hence using protocolEnabled as false to make it OCP and security-wise
180     // compliant
181     asyncResp->res.jsonValue["HTTP"]["Port"] = nullptr;
182     asyncResp->res.jsonValue["HTTP"]["ProtocolEnabled"] = false;
183 
184     // The ProtocolEnabled of the following protocols is determined by
185     // inspecting the state of associated systemd sockets. If these protocols
186     // have been disabled, then the systemd socket unit files will not be found
187     // and the protocols will not be returned in this Redfish query. Set some
188     // defaults to ensure something is always returned.
189     for (const auto& nwkProtocol : networkProtocolToDbus)
190     {
191         asyncResp->res.jsonValue[nwkProtocol.first]["Port"] = nullptr;
192         asyncResp->res.jsonValue[nwkProtocol.first]["ProtocolEnabled"] = false;
193     }
194 
195     std::string hostName = getHostName();
196 
197     asyncResp->res.jsonValue["HostName"] = hostName;
198 
199     getNTPProtocolEnabled(asyncResp);
200 
201     getEthernetIfaceData(
202         [hostName, asyncResp](const bool& success,
203                               const std::vector<std::string>& ntpServers,
204                               const std::vector<std::string>& domainNames) {
205         if (!success)
206         {
207             messages::resourceNotFound(asyncResp->res, "ManagerNetworkProtocol",
208                                        "NetworkProtocol");
209             return;
210         }
211         asyncResp->res.jsonValue["NTP"]["NTPServers"] = ntpServers;
212         if (!hostName.empty())
213         {
214             std::string fqdn = hostName;
215             if (!domainNames.empty())
216             {
217                 fqdn += ".";
218                 fqdn += domainNames[0];
219             }
220             asyncResp->res.jsonValue["FQDN"] = std::move(fqdn);
221         }
222     });
223 
224     Privileges effectiveUserPrivileges =
225         redfish::getUserPrivileges(*req.session);
226 
227     // /redfish/v1/Managers/bmc/NetworkProtocol/HTTPS/Certificates is
228     // something only ConfigureManager can access then only display when
229     // the user has permissions ConfigureManager
230     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
231                                          effectiveUserPrivileges))
232     {
233         asyncResp->res.jsonValue["HTTPS"]["Certificates"]["@odata.id"] =
234             "/redfish/v1/Managers/bmc/NetworkProtocol/HTTPS/Certificates";
235     }
236 
237     getPortStatusAndPath(std::span(networkProtocolToDbus),
238                          std::bind_front(afterNetworkPortRequest, asyncResp));
239 } // namespace redfish
240 
241 inline void handleNTPProtocolEnabled(
242     const bool& ntpEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
243 {
244     std::string timeSyncMethod;
245     if (ntpEnabled)
246     {
247         timeSyncMethod = "xyz.openbmc_project.Time.Synchronization.Method.NTP";
248     }
249     else
250     {
251         timeSyncMethod =
252             "xyz.openbmc_project.Time.Synchronization.Method.Manual";
253     }
254 
255     setDbusProperty(asyncResp, "xyz.openbmc_project.Settings",
256                     sdbusplus::message::object_path(
257                         "/xyz/openbmc_project/time/sync_method"),
258                     "xyz.openbmc_project.Time.Synchronization",
259                     "TimeSyncMethod", "NTP/ProtocolEnabled", timeSyncMethod);
260 }
261 
262 // Redfish states that ip addresses can be
263 // string, to set a value
264 // null, to delete the value
265 // object_t, empty json object, to ignore the value
266 using IpAddress =
267     std::variant<std::string, nlohmann::json::object_t, std::nullptr_t>;
268 
269 inline void
270     handleNTPServersPatch(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
271                           const std::vector<IpAddress>& ntpServerObjects,
272                           std::vector<std::string> currentNtpServers)
273 {
274     std::vector<std::string>::iterator currentNtpServer =
275         currentNtpServers.begin();
276     for (size_t index = 0; index < ntpServerObjects.size(); index++)
277     {
278         const IpAddress& ntpServer = ntpServerObjects[index];
279         if (std::holds_alternative<std::nullptr_t>(ntpServer))
280         {
281             // Can't delete an item that doesn't exist
282             if (currentNtpServer == currentNtpServers.end())
283             {
284                 messages::propertyValueNotInList(asyncResp->res, "null",
285                                                  "NTP/NTPServers/" +
286                                                      std::to_string(index));
287 
288                 return;
289             }
290             currentNtpServer = currentNtpServers.erase(currentNtpServer);
291             continue;
292         }
293         const nlohmann::json::object_t* ntpServerObject =
294             std::get_if<nlohmann::json::object_t>(&ntpServer);
295         if (ntpServerObject != nullptr)
296         {
297             if (!ntpServerObject->empty())
298             {
299                 messages::propertyValueNotInList(
300                     asyncResp->res, *ntpServerObject,
301                     "NTP/NTPServers/" + std::to_string(index));
302                 return;
303             }
304             // Can't retain an item that doesn't exist
305             if (currentNtpServer == currentNtpServers.end())
306             {
307                 messages::propertyValueOutOfRange(
308                     asyncResp->res, *ntpServerObject,
309                     "NTP/NTPServers/" + std::to_string(index));
310 
311                 return;
312             }
313             // empty objects should leave the NtpServer unmodified
314             currentNtpServer++;
315             continue;
316         }
317 
318         const std::string* ntpServerStr = std::get_if<std::string>(&ntpServer);
319         if (ntpServerStr == nullptr)
320         {
321             messages::internalError(asyncResp->res);
322             return;
323         }
324         if (currentNtpServer == currentNtpServers.end())
325         {
326             // if we're at the end of the list, append to the end
327             currentNtpServers.push_back(*ntpServerStr);
328             currentNtpServer = currentNtpServers.end();
329             continue;
330         }
331         *currentNtpServer = *ntpServerStr;
332         currentNtpServer++;
333     }
334 
335     // Any remaining array elements should be removed
336     currentNtpServers.erase(currentNtpServer, currentNtpServers.end());
337 
338     constexpr std::array<std::string_view, 1> ethInterfaces = {
339         "xyz.openbmc_project.Network.EthernetInterface"};
340     dbus::utility::getSubTree(
341         "/xyz/openbmc_project", 0, ethInterfaces,
342         [asyncResp, currentNtpServers](
343             const boost::system::error_code& ec,
344             const dbus::utility::MapperGetSubTreeResponse& subtree) {
345         if (ec)
346         {
347             BMCWEB_LOG_WARNING("D-Bus error: {}, {}", ec, ec.message());
348             messages::internalError(asyncResp->res);
349             return;
350         }
351 
352         for (const auto& [objectPath, serviceMap] : subtree)
353         {
354             for (const auto& [service, interfaces] : serviceMap)
355             {
356                 for (const auto& interface : interfaces)
357                 {
358                     if (interface !=
359                         "xyz.openbmc_project.Network.EthernetInterface")
360                     {
361                         continue;
362                     }
363 
364                     setDbusProperty(asyncResp, service, objectPath, interface,
365                                     "StaticNTPServers", "NTP/NTPServers/",
366                                     currentNtpServers);
367                 }
368             }
369         }
370     });
371 }
372 
373 inline void
374     handleProtocolEnabled(const bool protocolEnabled,
375                           const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
376                           const std::string& netBasePath)
377 {
378     constexpr std::array<std::string_view, 1> interfaces = {
379         "xyz.openbmc_project.Control.Service.Attributes"};
380     dbus::utility::getSubTree(
381         "/xyz/openbmc_project/control/service", 0, interfaces,
382         [protocolEnabled, asyncResp,
383          netBasePath](const boost::system::error_code& ec,
384                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
385         if (ec)
386         {
387             messages::internalError(asyncResp->res);
388             return;
389         }
390 
391         for (const auto& entry : subtree)
392         {
393             if (entry.first.starts_with(netBasePath))
394             {
395                 setDbusProperty(
396                     asyncResp, entry.second.begin()->first, entry.first,
397                     "xyz.openbmc_project.Control.Service.Attributes", "Running",
398                     "IPMI/ProtocolEnabled", protocolEnabled);
399                 setDbusProperty(
400                     asyncResp, entry.second.begin()->first, entry.first,
401                     "xyz.openbmc_project.Control.Service.Attributes", "Enabled",
402                     "IPMI/ProtocolEnabled", protocolEnabled);
403             }
404         }
405     });
406 }
407 
408 inline std::string getHostName()
409 {
410     std::string hostName;
411 
412     std::array<char, HOST_NAME_MAX> hostNameCStr{};
413     if (gethostname(hostNameCStr.data(), hostNameCStr.size()) == 0)
414     {
415         hostName = hostNameCStr.data();
416     }
417     return hostName;
418 }
419 
420 inline void
421     getNTPProtocolEnabled(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
422 {
423     sdbusplus::asio::getProperty<std::string>(
424         *crow::connections::systemBus, "xyz.openbmc_project.Settings",
425         "/xyz/openbmc_project/time/sync_method",
426         "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod",
427         [asyncResp](const boost::system::error_code& ec,
428                     const std::string& timeSyncMethod) {
429         if (ec)
430         {
431             return;
432         }
433 
434         if (timeSyncMethod ==
435             "xyz.openbmc_project.Time.Synchronization.Method.NTP")
436         {
437             asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = true;
438         }
439         else if (timeSyncMethod == "xyz.openbmc_project.Time.Synchronization."
440                                    "Method.Manual")
441         {
442             asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = false;
443         }
444     });
445 }
446 
447 inline std::string encodeServiceObjectPath(std::string_view serviceName)
448 {
449     sdbusplus::message::object_path objPath(
450         "/xyz/openbmc_project/control/service");
451     objPath /= serviceName;
452     return objPath.str;
453 }
454 
455 inline void handleBmcNetworkProtocolHead(
456     crow::App& app, const crow::Request& req,
457     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
458 {
459     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
460     {
461         return;
462     }
463     asyncResp->res.addHeader(
464         boost::beast::http::field::link,
465         "</redfish/v1/JsonSchemas/ManagerNetworkProtocol/ManagerNetworkProtocol.json>; rel=describedby");
466 }
467 
468 inline void handleManagersNetworkProtocolPatch(
469     App& app, const crow::Request& req,
470     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
471 {
472     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
473     {
474         return;
475     }
476     std::optional<std::string> newHostName;
477 
478     std::optional<std::vector<IpAddress>> ntpServerObjects;
479     std::optional<bool> ntpEnabled;
480     std::optional<bool> ipmiEnabled;
481     std::optional<bool> sshEnabled;
482 
483     // clang-format off
484         if (!json_util::readJsonPatch(
485                 req, asyncResp->res,
486                 "HostName", newHostName,
487                 "NTP/NTPServers", ntpServerObjects,
488                 "NTP/ProtocolEnabled", ntpEnabled,
489                 "IPMI/ProtocolEnabled", ipmiEnabled,
490                 "SSH/ProtocolEnabled", sshEnabled))
491         {
492             return;
493         }
494     // clang-format on
495 
496     asyncResp->res.result(boost::beast::http::status::no_content);
497     if (newHostName)
498     {
499         messages::propertyNotWritable(asyncResp->res, "HostName");
500         return;
501     }
502 
503     if (ntpEnabled)
504     {
505         handleNTPProtocolEnabled(*ntpEnabled, asyncResp);
506     }
507     if (ntpServerObjects)
508     {
509         getEthernetIfaceData(
510             [asyncResp, ntpServerObjects](
511                 const bool success, std::vector<std::string>& currentNtpServers,
512                 const std::vector<std::string>& /*domainNames*/) {
513             if (!success)
514             {
515                 messages::internalError(asyncResp->res);
516                 return;
517             }
518             handleNTPServersPatch(asyncResp, *ntpServerObjects,
519                                   std::move(currentNtpServers));
520         });
521     }
522 
523     if (ipmiEnabled)
524     {
525         handleProtocolEnabled(
526             *ipmiEnabled, asyncResp,
527             encodeServiceObjectPath(std::string(ipmiServiceName) + '@'));
528     }
529 
530     if (sshEnabled)
531     {
532         handleProtocolEnabled(*sshEnabled, asyncResp,
533                               encodeServiceObjectPath(sshServiceName));
534     }
535 }
536 
537 inline void handleManagersNetworkProtocolHead(
538     App& app, const crow::Request& req,
539     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
540 {
541     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
542     {
543         return;
544     }
545     asyncResp->res.addHeader(
546         boost::beast::http::field::link,
547         "</redfish/v1/JsonSchemas/ManagerNetworkProtocol/ManagerNetworkProtocol.json>; rel=describedby");
548 }
549 
550 inline void handleManagersNetworkProtocolGet(
551     App& app, const crow::Request& req,
552     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
553 {
554     handleManagersNetworkProtocolHead(app, req, asyncResp);
555     getNetworkData(asyncResp, req);
556 }
557 
558 inline void requestRoutesNetworkProtocol(App& app)
559 {
560     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/NetworkProtocol/")
561         .privileges(redfish::privileges::patchManagerNetworkProtocol)
562         .methods(boost::beast::http::verb::patch)(
563             std::bind_front(handleManagersNetworkProtocolPatch, std::ref(app)));
564 
565     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/NetworkProtocol/")
566         .privileges(redfish::privileges::headManagerNetworkProtocol)
567         .methods(boost::beast::http::verb::head)(
568             std::bind_front(handleManagersNetworkProtocolHead, std::ref(app)));
569 
570     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/NetworkProtocol/")
571         .privileges(redfish::privileges::getManagerNetworkProtocol)
572         .methods(boost::beast::http::verb::get)(
573             std::bind_front(handleManagersNetworkProtocolGet, std::ref(app)));
574 }
575 
576 } // namespace redfish
577