Skip to content

Instantly share code, notes, and snippets.

@artemist
Created August 18, 2024 05:16
Show Gist options
  • Select an option

  • Save artemist/4c0380dc0a30e4e114501417023fb69a to your computer and use it in GitHub Desktop.

Select an option

Save artemist/4c0380dc0a30e4e114501417023fb69a to your computer and use it in GitHub Desktop.
#include <sys/cdefs.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/conf.h>
#include <fs/devfs/devfs.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>
#include <iostream>
#include <exception>
#include <vector>
#include <string>
static devfs_rsnum first_free_ruleset(int fd) {
devfs_rsnum prev = 0;
devfs_rsnum current = 0;
while (current < (devfs_rsnum)-1) {
prev = current;
int rv = ioctl(fd, DEVFSIO_SGETNEXT, &current);
if (rv == -1 && errno != ENOENT) {
throw std::runtime_error("DEVFSIO_SGETNEXT");
} else if(current - prev > 1) {
// There's a gap between the rulesets
return prev + 1;
} else if(rv == -1) {
// current is the final ruleset
return current + 1;
}
}
throw std::runtime_error("no free rulesets");
}
void real_main() {
int fd = open("/dev/", O_RDONLY);
if (fd < 0) throw std::runtime_error("could not open dev");
devfs_rsnum ruleset = first_free_ruleset(fd);
std::cout << "next free ruleset: " << ruleset << std::endl;
struct devfs_rule rule{};
rule.dr_magic = DEVFS_MAGIC;
// rule id 0 means allocate new ID
rule.dr_id = mkrid(ruleset, 0);
rule.dr_iacts = DRA_BACTS;
rule.dr_bacts = DRB_HIDE;
if (ioctl(fd, DEVFSIO_RADD, &rule) == -1) throw std::runtime_error("DEVFSIO_RADD");
std::vector<std::string> unhide_names = {
"null",
"zero",
"random",
"urandom",
"pts",
"pts/*",
"fd",
"fd/*",
"stdin",
"stdout",
"stderr"
};
for(auto& name : unhide_names) {
if(name.size() > DEVFS_MAXPTRNLEN) {
throw std::runtime_error("pattern too long");
}
struct devfs_rule rule{};
rule.dr_magic = DEVFS_MAGIC;
rule.dr_id = mkrid(ruleset, 0);
rule.dr_iacts = DRA_BACTS;
rule.dr_bacts = DRB_UNHIDE;
rule.dr_icond = DRC_PATHPTRN;
strcpy(rule.dr_pathptrn, name.data());
if (ioctl(fd, DEVFSIO_RADD, &rule) == -1) throw std::runtime_error("DEVFSIO_RADD");
}
}
int main() {
try {
real_main();
} catch(const std::exception& ex) {
std::cout << ex.what() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment