Skip to content

Commit

Permalink
Use partial rule in allow/block/reject-device commands
Browse files Browse the repository at this point in the history
  • Loading branch information
ZoltanFridrich committed Oct 29, 2020
1 parent ca62acf commit 8267c2a
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions src/CLI/usbguard-apply-device-policy.cpp
Expand Up @@ -27,6 +27,7 @@
#include "usbguard/IPCClient.hpp"

#include <iostream>
#include <list>

namespace usbguard
{
Expand Down Expand Up @@ -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;

Expand All @@ -81,47 +81,53 @@ 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<std::string> arguments(argv, argv + argc);
rule_string = joinElements(arguments.begin(), arguments.end());
}
std::list<std::string> 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;
showHelp(std::cerr, target);
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 */
Expand Down

0 comments on commit 8267c2a

Please sign in to comment.