~jkaivo/deonebook

78d6a052fc6431ad45ff3a24461fd7744a3c1c28 — Jakob Kaivo 1 year, 8 months ago dbd1640
enforce device type of mmcblk, fail if /sys/block/<device>/device is not a readable directory
3 files changed, 26 insertions(+), 14 deletions(-)

M deonebook.c
M deonebook.h
M genkey.c
M deonebook.c => deonebook.c +11 -1
@@ 1,4 1,5 @@
#define _XOPEN_SOURCE 700
#include <dirent.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>


@@ 37,12 38,21 @@ int main(int argc, char *argv[])
			if (optind < argc) {
				device = argv[optind];
			}

			if (strstr(device, "mmcblk") != device) {
				fprintf(stderr, "device must be an mmcblk device\n");
				return 1;
			}

			key = genkey(device);
			char path[256];
			snprintf(path, sizeof(path), "/sys/block/%s/device", device);
			DIR *d = opendir(path);
			if (d == NULL) {
				fprintf(stderr, "device '%s' not found\n", device);
				return 1;
			}

			key = genkey(dirfd(d));
		}

		if (key == NULL) {

M deonebook.h => deonebook.h +1 -1
@@ 3,7 3,7 @@

#define KEY_SIZE 16

unsigned char *genkey(const char *dev);
unsigned char *genkey(int dirfd);
unsigned char *readkey(const char *path);

#endif

M genkey.c => genkey.c +14 -12
@@ 1,8 1,12 @@
#define _XOPEN_SOURCE 700
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>

#include "deonebook.h"

#define SCR_SIZE 8


@@ 34,27 38,25 @@ static unsigned char twiddle(unsigned char buf[2])
	return c;
}

static bool get_sd_register(const char *dev, const char *reg, size_t n, unsigned char buf[n])
static bool get_sd_register(int dirfd, const char *reg, size_t n, unsigned char buf[n])
{
	char path[256];
	snprintf(path, sizeof(path), "/sys/block/%s/device/%s", dev, reg);

	FILE *f = fopen(path, "r");
	if (f == NULL) {
	int fd = openat(dirfd, reg, O_RDONLY);
	if (fd == -1) {
		return false;
	}

	for (size_t i = 0; i < n; i++) {
		unsigned char hex[2];
		fread(hex, 2, 1, f);
		read(fd, hex, sizeof(hex));
		buf[i] = twiddle(hex);
	}

	fclose(f);
	close(fd);

	return true;
}

unsigned char * genkey(const char *dev)
unsigned char * genkey(int dirfd)
{
	static unsigned char key[KEY_SIZE];
	const unsigned char keycode[] = "eone";


@@ 65,15 67,15 @@ unsigned char * genkey(const char *dev)
	unsigned char csd[CSD_SIZE] = "testtesttesttest";
	unsigned char cid[CID_SIZE] = "testtesttesttest";

	if (!get_sd_register(dev, "cid", sizeof(cid), cid)) {
	if (!get_sd_register(dirfd, "cid", sizeof(cid), cid)) {
		fprintf(stderr, "warning: CID register not read\n");
		allread = false;
	}
	if (!get_sd_register(dev, "csd", sizeof(csd), csd)) {
	if (!get_sd_register(dirfd, "csd", sizeof(csd), csd)) {
		fprintf(stderr, "warning: CSD register not read\n");
		allread = false;
	}
	if (!get_sd_register(dev, "scr", sizeof(scr), scr)) {
	if (!get_sd_register(dirfd, "scr", sizeof(scr), scr)) {
		fprintf(stderr, "warning: SCR register not read\n");
		allread = false;
	}