1 /**
2  * Copyright © 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 #include "config.h"
17 
18 #include "settings.hpp"
19 
20 #include <dlfcn.h>
21 
22 #include <algorithm>
23 #include <any>
24 #include <dcmihandler.hpp>
25 #include <exception>
26 #include <filesystem>
27 #include <forward_list>
28 #include <host-cmd-manager.hpp>
29 #include <ipmid-host/cmd.hpp>
30 #include <ipmid/api.hpp>
31 #include <ipmid/handler.hpp>
32 #include <ipmid/message.hpp>
33 #include <ipmid/oemrouter.hpp>
34 #include <ipmid/registration.hpp>
35 #include <ipmid/types.hpp>
36 #include <map>
37 #include <memory>
38 #include <optional>
39 #include <phosphor-logging/log.hpp>
40 #include <sdbusplus/asio/connection.hpp>
41 #include <sdbusplus/asio/object_server.hpp>
42 #include <sdbusplus/asio/sd_event.hpp>
43 #include <sdbusplus/bus.hpp>
44 #include <sdbusplus/bus/match.hpp>
45 #include <sdbusplus/timer.hpp>
46 #include <tuple>
47 #include <unordered_map>
48 #include <utility>
49 #include <vector>
50 
51 namespace fs = std::filesystem;
52 
53 using namespace phosphor::logging;
54 
55 // IPMI Spec, shared Reservation ID.
56 static unsigned short selReservationID = 0xFFFF;
57 static bool selReservationValid = false;
58 
59 unsigned short reserveSel(void)
60 {
61     // IPMI spec, Reservation ID, the value simply increases against each
62     // execution of the Reserve SEL command.
63     if (++selReservationID == 0)
64     {
65         selReservationID = 1;
66     }
67     selReservationValid = true;
68     return selReservationID;
69 }
70 
71 bool checkSELReservation(unsigned short id)
72 {
73     return (selReservationValid && selReservationID == id);
74 }
75 
76 void cancelSELReservation(void)
77 {
78     selReservationValid = false;
79 }
80 
81 EInterfaceIndex getInterfaceIndex(void)
82 {
83     return interfaceKCS;
84 }
85 
86 sd_bus* bus;
87 sd_event* events = nullptr;
88 sd_event* ipmid_get_sd_event_connection(void)
89 {
90     return events;
91 }
92 sd_bus* ipmid_get_sd_bus_connection(void)
93 {
94     return bus;
95 }
96 
97 namespace ipmi
98 {
99 
100 static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
101 {
102     return (cluster << 8) | cmd;
103 }
104 
105 using HandlerTuple = std::tuple<int,                        /* prio */
106                                 Privilege, HandlerBase::ptr /* handler */
107                                 >;
108 
109 /* map to handle standard registered commands */
110 static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
111                           HandlerTuple>
112     handlerMap;
113 
114 /* special map for decoding Group registered commands (NetFn 2Ch) */
115 static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
116                           HandlerTuple>
117     groupHandlerMap;
118 
119 /* special map for decoding OEM registered commands (NetFn 2Eh) */
120 static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
121                           HandlerTuple>
122     oemHandlerMap;
123 
124 using FilterTuple = std::tuple<int,            /* prio */
125                                FilterBase::ptr /* filter */
126                                >;
127 
128 /* list to hold all registered ipmi command filters */
129 static std::forward_list<FilterTuple> filterList;
130 
131 namespace impl
132 {
133 /* common function to register all standard IPMI handlers */
134 bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
135                      HandlerBase::ptr handler)
136 {
137     // check for valid NetFn: even; 00-0Ch, 30-3Eh
138     if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
139         netFn > netFnOemEight)
140     {
141         return false;
142     }
143 
144     // create key and value for this handler
145     unsigned int netFnCmd = makeCmdKey(netFn, cmd);
146     HandlerTuple item(prio, priv, handler);
147 
148     // consult the handler map and look for a match
149     auto& mapCmd = handlerMap[netFnCmd];
150     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
151     {
152         mapCmd = item;
153         return true;
154     }
155     return false;
156 }
157 
158 /* common function to register all Group IPMI handlers */
159 bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
160                           HandlerBase::ptr handler)
161 {
162     // create key and value for this handler
163     unsigned int netFnCmd = makeCmdKey(group, cmd);
164     HandlerTuple item(prio, priv, handler);
165 
166     // consult the handler map and look for a match
167     auto& mapCmd = groupHandlerMap[netFnCmd];
168     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
169     {
170         mapCmd = item;
171         return true;
172     }
173     return false;
174 }
175 
176 /* common function to register all OEM IPMI handlers */
177 bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
178                         HandlerBase::ptr handler)
179 {
180     // create key and value for this handler
181     unsigned int netFnCmd = makeCmdKey(iana, cmd);
182     HandlerTuple item(prio, priv, handler);
183 
184     // consult the handler map and look for a match
185     auto& mapCmd = oemHandlerMap[netFnCmd];
186     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
187     {
188         mapCmd = item;
189         return true;
190     }
191     return false;
192 }
193 
194 /* common function to register all IPMI filter handlers */
195 void registerFilter(int prio, FilterBase::ptr filter)
196 {
197     // check for initial placement
198     if (filterList.empty() || std::get<int>(filterList.front()) < prio)
199     {
200         filterList.emplace_front(std::make_tuple(prio, filter));
201     }
202     // walk the list and put it in the right place
203     auto j = filterList.begin();
204     for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
205     {
206         j = i;
207     }
208     filterList.emplace_after(j, std::make_tuple(prio, filter));
209 }
210 
211 } // namespace impl
212 
213 message::Response::ptr filterIpmiCommand(message::Request::ptr request)
214 {
215     // pass the command through the filter mechanism
216     // This can be the firmware firewall or any OEM mechanism like
217     // whitelist filtering based on operational mode
218     for (auto& item : filterList)
219     {
220         FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
221         ipmi::Cc cc = filter->call(request);
222         if (ipmi::ccSuccess != cc)
223         {
224             return errorResponse(request, cc);
225         }
226     }
227     return message::Response::ptr();
228 }
229 
230 message::Response::ptr executeIpmiCommandCommon(
231     std::unordered_map<unsigned int, HandlerTuple>& handlers,
232     unsigned int keyCommon, message::Request::ptr request)
233 {
234     // filter the command first; a non-null message::Response::ptr
235     // means that the message has been rejected for some reason
236     message::Response::ptr response = filterIpmiCommand(request);
237     if (response)
238     {
239         return response;
240     }
241 
242     Cmd cmd = request->ctx->cmd;
243     unsigned int key = makeCmdKey(keyCommon, cmd);
244     auto cmdIter = handlers.find(key);
245     if (cmdIter != handlers.end())
246     {
247         HandlerTuple& chosen = cmdIter->second;
248         if (request->ctx->priv < std::get<Privilege>(chosen))
249         {
250             return errorResponse(request, ccInsufficientPrivilege);
251         }
252         return std::get<HandlerBase::ptr>(chosen)->call(request);
253     }
254     else
255     {
256         unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
257         cmdIter = handlers.find(wildcard);
258         if (cmdIter != handlers.end())
259         {
260             HandlerTuple& chosen = cmdIter->second;
261             if (request->ctx->priv < std::get<Privilege>(chosen))
262             {
263                 return errorResponse(request, ccInsufficientPrivilege);
264             }
265             return std::get<HandlerBase::ptr>(chosen)->call(request);
266         }
267     }
268     return errorResponse(request, ccInvalidCommand);
269 }
270 
271 message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
272 {
273     // look up the group for this request
274     Group group;
275     if (0 != request->payload.unpack(group))
276     {
277         return errorResponse(request, ccReqDataLenInvalid);
278     }
279     // The handler will need to unpack group as well; we just need it for lookup
280     request->payload.reset();
281     message::Response::ptr response =
282         executeIpmiCommandCommon(groupHandlerMap, group, request);
283     // if the handler should add the group; executeIpmiCommandCommon does not
284     if (response->cc != ccSuccess && response->payload.size() == 0)
285     {
286         response->pack(group);
287     }
288     return response;
289 }
290 
291 message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
292 {
293     // look up the iana for this request
294     Iana iana;
295     if (0 != request->payload.unpack(iana))
296     {
297         return errorResponse(request, ccReqDataLenInvalid);
298     }
299     request->payload.reset();
300     message::Response::ptr response =
301         executeIpmiCommandCommon(oemHandlerMap, iana, request);
302     // if the handler should add the iana; executeIpmiCommandCommon does not
303     if (response->cc != ccSuccess && response->payload.size() == 0)
304     {
305         response->pack(iana);
306     }
307     return response;
308 }
309 
310 message::Response::ptr executeIpmiCommand(message::Request::ptr request)
311 {
312     NetFn netFn = request->ctx->netFn;
313     if (netFnGroup == netFn)
314     {
315         return executeIpmiGroupCommand(request);
316     }
317     else if (netFnOem == netFn)
318     {
319         return executeIpmiOemCommand(request);
320     }
321     return executeIpmiCommandCommon(handlerMap, netFn, request);
322 }
323 
324 /* called from sdbus async server context */
325 auto executionEntry(boost::asio::yield_context yield, NetFn netFn, uint8_t lun,
326                     Cmd cmd, std::vector<uint8_t>& data,
327                     std::map<std::string, ipmi::Value>& options)
328 {
329     auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, 0, 0,
330                                                ipmi::Privilege::Admin, &yield);
331     auto request = std::make_shared<ipmi::message::Request>(
332         ctx, std::forward<std::vector<uint8_t>>(data));
333     message::Response::ptr response = executeIpmiCommand(request);
334 
335     // Responses in IPMI require a bit set.  So there ya go...
336     netFn |= 0x01;
337     return std::make_tuple(netFn, lun, cmd, response->cc,
338                            response->payload.raw);
339 }
340 
341 /** @struct IpmiProvider
342  *
343  *  RAII wrapper for dlopen so that dlclose gets called on exit
344  */
345 struct IpmiProvider
346 {
347   public:
348     /** @brief address of the opened library */
349     void* addr;
350     std::string name;
351 
352     IpmiProvider() = delete;
353     IpmiProvider(const IpmiProvider&) = delete;
354     IpmiProvider& operator=(const IpmiProvider&) = delete;
355     IpmiProvider(IpmiProvider&&) = delete;
356     IpmiProvider& operator=(IpmiProvider&&) = delete;
357 
358     /** @brief dlopen a shared object file by path
359      *  @param[in]  filename - path of shared object to open
360      */
361     explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
362     {
363         log<level::DEBUG>("Open IPMI provider library",
364                           entry("PROVIDER=%s", name.c_str()));
365         try
366         {
367             addr = dlopen(name.c_str(), RTLD_NOW);
368         }
369         catch (std::exception& e)
370         {
371             log<level::ERR>("ERROR opening IPMI provider",
372                             entry("PROVIDER=%s", name.c_str()),
373                             entry("ERROR=%s", e.what()));
374         }
375         catch (...)
376         {
377             std::exception_ptr eptr = std::current_exception();
378             try
379             {
380                 std::rethrow_exception(eptr);
381             }
382             catch (std::exception& e)
383             {
384                 log<level::ERR>("ERROR opening IPMI provider",
385                                 entry("PROVIDER=%s", name.c_str()),
386                                 entry("ERROR=%s", e.what()));
387             }
388         }
389         if (!isOpen())
390         {
391             log<level::ERR>("ERROR opening IPMI provider",
392                             entry("PROVIDER=%s", name.c_str()),
393                             entry("ERROR=%s", dlerror()));
394         }
395     }
396 
397     ~IpmiProvider()
398     {
399         if (isOpen())
400         {
401             dlclose(addr);
402         }
403     }
404     bool isOpen() const
405     {
406         return (nullptr != addr);
407     }
408 };
409 
410 // Plugin libraries need to contain .so either at the end or in the middle
411 constexpr const char ipmiPluginExtn[] = ".so";
412 
413 /* return a list of self-closing library handles */
414 std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
415 {
416     std::vector<fs::path> libs;
417     for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
418     {
419         std::error_code ec;
420         fs::path fname = libPath.path();
421         if (fs::is_symlink(fname, ec) || ec)
422         {
423             // it's a symlink or some other error; skip it
424             continue;
425         }
426         while (fname.has_extension())
427         {
428             fs::path extn = fname.extension();
429             if (extn == ipmiPluginExtn)
430             {
431                 libs.push_back(libPath.path());
432                 break;
433             }
434             fname.replace_extension();
435         }
436     }
437     std::sort(libs.begin(), libs.end());
438 
439     std::forward_list<IpmiProvider> handles;
440     for (auto& lib : libs)
441     {
442 #ifdef __IPMI_DEBUG__
443         log<level::DEBUG>("Registering handler",
444                           entry("HANDLER=%s", lib.c_str()));
445 #endif
446         handles.emplace_front(lib.c_str());
447     }
448     return handles;
449 }
450 
451 } // namespace ipmi
452 
453 #ifdef ALLOW_DEPRECATED_API
454 /* legacy registration */
455 void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
456                             ipmi_context_t context, ipmid_callback_t handler,
457                             ipmi_cmd_privilege_t priv)
458 {
459     auto h = ipmi::makeLegacyHandler(handler, context);
460     // translate priv from deprecated enum to current
461     ipmi::Privilege realPriv;
462     switch (priv)
463     {
464         case PRIVILEGE_CALLBACK:
465             realPriv = ipmi::Privilege::Callback;
466             break;
467         case PRIVILEGE_USER:
468             realPriv = ipmi::Privilege::User;
469             break;
470         case PRIVILEGE_OPERATOR:
471             realPriv = ipmi::Privilege::Operator;
472             break;
473         case PRIVILEGE_ADMIN:
474             realPriv = ipmi::Privilege::Admin;
475             break;
476         case PRIVILEGE_OEM:
477             realPriv = ipmi::Privilege::Oem;
478             break;
479         case SYSTEM_INTERFACE:
480             realPriv = ipmi::Privilege::Admin;
481             break;
482         default:
483             realPriv = ipmi::Privilege::Admin;
484             break;
485     }
486     // The original ipmi_register_callback allowed for group OEM handlers
487     // to be registered via this same interface. It just so happened that
488     // all the handlers were part of the DCMI group, so default to that.
489     if (netFn == NETFUN_GRPEXT)
490     {
491         ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase,
492                                          dcmi::groupExtId, cmd, realPriv, h);
493     }
494     else
495     {
496         ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
497                                     h);
498     }
499 }
500 
501 namespace oem
502 {
503 
504 class LegacyRouter : public oem::Router
505 {
506   public:
507     virtual ~LegacyRouter()
508     {
509     }
510 
511     /// Enable message routing to begin.
512     void activate() override
513     {
514     }
515 
516     void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
517     {
518         auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
519         ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
520                                        ipmi::Privilege::Admin, h);
521     }
522 };
523 static LegacyRouter legacyRouter;
524 
525 Router* mutableRouter()
526 {
527     return &legacyRouter;
528 }
529 
530 } // namespace oem
531 
532 /* legacy alternative to executionEntry */
533 void handleLegacyIpmiCommand(sdbusplus::message::message& m)
534 {
535     unsigned char seq, netFn, lun, cmd;
536     std::vector<uint8_t> data;
537 
538     m.read(seq, netFn, lun, cmd, data);
539 
540     auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, 0, 0,
541                                                ipmi::Privilege::Admin);
542     auto request = std::make_shared<ipmi::message::Request>(
543         ctx, std::forward<std::vector<uint8_t>>(data));
544     ipmi::message::Response::ptr response = ipmi::executeIpmiCommand(request);
545 
546     // Responses in IPMI require a bit set.  So there ya go...
547     netFn |= 0x01;
548 
549     const char *dest, *path;
550     constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
551 
552     dest = m.get_sender();
553     path = m.get_path();
554     getSdBus()->async_method_call([](boost::system::error_code ec) {}, dest,
555                                   path, DBUS_INTF, "sendMessage", seq, netFn,
556                                   lun, cmd, response->cc,
557                                   response->payload.raw);
558 }
559 
560 #endif /* ALLOW_DEPRECATED_API */
561 
562 // Calls host command manager to do the right thing for the command
563 using CommandHandler = phosphor::host::command::CommandHandler;
564 std::unique_ptr<phosphor::host::command::Manager> cmdManager;
565 void ipmid_send_cmd_to_host(CommandHandler&& cmd)
566 {
567     return cmdManager->execute(std::forward<CommandHandler>(cmd));
568 }
569 
570 std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
571 {
572     return cmdManager;
573 }
574 
575 // These are symbols that are present in libipmid, but not expected
576 // to be used except here (or maybe a unit test), so declare them here
577 extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
578 extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
579 
580 int main(int argc, char* argv[])
581 {
582     // Connect to system bus
583     auto io = std::make_shared<boost::asio::io_context>();
584     setIoContext(io);
585     if (argc > 1 && std::string(argv[1]) == "-session")
586     {
587         sd_bus_default_user(&bus);
588     }
589     else
590     {
591         sd_bus_default_system(&bus);
592     }
593     auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
594     setSdBus(sdbusp);
595     sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
596 
597     // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
598     //       queue stops running if we don't have a timer that keeps re-arming
599     phosphor::Timer t2([]() { ; });
600     t2.start(std::chrono::microseconds(500000), true);
601 
602     // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
603     //       until that is done, add the sd_event wrapper to the io object
604     sdbusplus::asio::sd_event_wrapper sdEvents(*io);
605 
606     cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
607 
608     // Register all command providers and filters
609     std::forward_list<ipmi::IpmiProvider> providers =
610         ipmi::loadProviders(HOST_IPMI_LIB_PATH);
611 
612     // Add bindings for inbound IPMI requests
613     auto server = sdbusplus::asio::object_server(sdbusp);
614     auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
615                                       "xyz.openbmc_project.Ipmi.Server");
616     iface->register_method("execute", ipmi::executionEntry);
617     iface->initialize();
618 
619 #ifdef ALLOW_DEPRECATED_API
620     // listen on deprecated signal interface for kcs/bt commands
621     constexpr const char* FILTER = "type='signal',interface='org.openbmc."
622                                    "HostIpmi',member='ReceivedMessage'";
623     sdbusplus::bus::match::match oldIpmiInterface(*sdbusp, FILTER,
624                                                   handleLegacyIpmiCommand);
625 #endif /* ALLOW_DEPRECATED_API */
626 
627     // set up boost::asio signal handling
628     std::function<SignalResponse(int)> stopAsioRunLoop =
629         [&io](int signalNumber) {
630             log<level::INFO>("Received signal; quitting",
631                              entry("SIGNAL=%d", signalNumber));
632             io->stop();
633             return SignalResponse::breakExecution;
634         };
635     registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
636     registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
637 
638     io->run();
639 
640     // destroy all the IPMI handlers so the providers can unload safely
641     ipmi::handlerMap.clear();
642     ipmi::groupHandlerMap.clear();
643     ipmi::oemHandlerMap.clear();
644     ipmi::filterList.clear();
645     // unload the provider libraries
646     providers.clear();
647 
648     return 0;
649 }
650