diff --git a/src/CLI/usbguard-apply-device-policy.cpp b/src/CLI/usbguard-apply-device-policy.cpp index 8743c1a4..596064e4 100644 --- a/src/CLI/usbguard-apply-device-policy.cpp +++ b/src/CLI/usbguard-apply-device-policy.cpp @@ -27,6 +27,7 @@ #include "usbguard/IPCClient.hpp" #include +#include namespace usbguard { @@ -57,7 +58,6 @@ namespace usbguard int usbguard_apply_device_policy(int argc, char** argv, Rule::Target target) { - uint32_t id = 0; bool permanent = false; int opt = 0; @@ -81,28 +81,27 @@ namespace usbguard argc -= optind; argv += optind; - usbguard::IPCClient ipc(/*connected=*/true); if (argc == 0) { showHelp(std::cerr, target); return EXIT_FAILURE; } - else if (argc == 1 && isNumeric(std::string(argv[0]))) { /* Change device policy by ID */ + + usbguard::IPCClient ipc(/*connected=*/true); + uint32_t id = 0; + + if (argc == 1 && isNumeric(std::string(argv[0]))) { /* Change device policy by ID */ id = std::stoul(argv[0]); ipc.applyDevicePolicy(id, target, permanent); } else { /* Change device policy by Rule */ - std::string rule_string; - if (argc == 1) - rule_string = argv[0]; - else { - std::vector arguments(argv, argv + argc); - rule_string = joinElements(arguments.begin(), arguments.end()); - } + std::list args(argv, argv + argc); + args.push_front(Rule::targetToString(Rule::Target::Match)); + std::string rule_string = joinElements(args.begin(), args.end()); - usbguard::Rule rule; + usbguard::Rule query; try { - rule = Rule::fromString(rule_string); + query = Rule::fromString(rule_string); } catch (const usbguard::RuleParserError& ex) { std::cerr << "ERROR: " << ex.what() << std::endl; @@ -110,18 +109,25 @@ namespace usbguard return EXIT_FAILURE; } - std::string rule_target = rule_string.substr(0, rule_string.find(" ")); - for (auto rule_device : ipc.listDevices(rule_target)) { - if (rule.appliesTo(rule_device)) { - id = rule_device.getRuleID(); + for (auto device_rule : ipc.listDevices(query)) { + if (target != device_rule.getTarget()) { + id = device_rule.getRuleID(); try { ipc.applyDevicePolicy(id, target, permanent); } - catch (const usbguard::Exception& ex) {} + catch (const usbguard::Exception& ex) { + /* + * When a parent device is blocked/rejected, all its child + * devices are removed from the device map. If we try to apply + * device policy to a device whose parent has been + * blocked/rejected, therefore this device is not present in + * the device map anymore, we will receive an exception. + * We ignore such exceptions. + */ + } } } } - return EXIT_SUCCESS; } } /* namespace usbguard */