forked from congwang/ebpf-2-phase-signing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_key.c
More file actions
74 lines (64 loc) · 1.71 KB
/
add_key.c
File metadata and controls
74 lines (64 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <keyutils.h>
#include <fcntl.h>
#include <errno.h>
#define KEYCTL_NEWRING 27
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <der_file>\n", argv[0]);
return 1;
}
// Read the DER file
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
// Get file size
off_t size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
// Allocate buffer
unsigned char *buffer = malloc(size);
if (!buffer) {
perror("malloc");
close(fd);
return 1;
}
// Read file
if (read(fd, buffer, size) != size) {
perror("read");
free(buffer);
close(fd);
return 1;
}
close(fd);
// First add the key to the session keyring
key_serial_t key_id = add_key("asymmetric", ".ebpf:signing:x509", buffer, size, KEY_SPEC_SESSION_KEYRING);
if (key_id < 0) {
perror("add_key");
free(buffer);
return 1;
}
printf("Added key with ID: %d\n", key_id);
// Create a new keyring in the session keyring
key_serial_t keyring_id = add_key("keyring", "_ebpf", NULL, 0, KEY_SPEC_SESSION_KEYRING);
if (keyring_id < 0) {
perror("Failed to create keyring");
free(buffer);
return 1;
}
printf("Created keyring with ID: %d\n", keyring_id);
// Link the key to the keyring
if (keyctl_link(key_id, keyring_id) < 0) {
perror("keyctl_link");
free(buffer);
return 1;
}
printf("Linked key %d to keyring %d\n", key_id, keyring_id);
free(buffer);
return 0;
}