Skip to content

Commit 748297a

Browse files
committed
read secret key from /etc/prairielearn.key in auth.c
1 parent e018c96 commit 748297a

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

auth/auth.c

+29-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
#define ENV_NAME "displayName"
1111

1212
#define SHA256_HASH_SIZE 32
13-
#define SECRET_KEY "THIS_IS_THE_SECRET_KEY"
13+
#define SECRET_KEY_FILE "/etc/prairielearn.key"
14+
#define MAX_KEY_LEN 10000
1415

1516
char *iso8601Now() {
1617
time_t current_time;
@@ -30,7 +31,7 @@ char *iso8601Now() {
3031
return time_string;
3132
}
3233

33-
char *sha256Signature(char *uid, char *name, char *date) {
34+
char *sha256Signature(char *uid, char *name, char *date, char *key) {
3435
size_t msg_size, sig_size, i;
3536
char *msg;
3637
char hash[SHA256_HASH_SIZE];
@@ -50,7 +51,7 @@ char *sha256Signature(char *uid, char *name, char *date) {
5051
msg[i++] = '/';
5152
strncpy(&msg[i], date, strlen(date));
5253

53-
hmac_sha256(SECRET_KEY, strlen(SECRET_KEY), msg, msg_size, hash, SHA256_HASH_SIZE);
54+
hmac_sha256(key, strlen(key), msg, msg_size, hash, SHA256_HASH_SIZE);
5455

5556
sig_size = 2 * SHA256_HASH_SIZE + 1;
5657
if (!(sig = malloc(sig_size * sizeof(char)))) {
@@ -63,12 +64,36 @@ char *sha256Signature(char *uid, char *name, char *date) {
6364
return sig;
6465
}
6566

67+
void readkey(char *key) {
68+
FILE *keyfile;
69+
size_t keysize;
70+
71+
if (!(keyfile = fopen(SECRET_KEY_FILE, "rb"))) {
72+
fprintf(stderr, "Error: unable to open key file: %s\n", SECRET_KEY_FILE);
73+
exit(1);
74+
}
75+
keysize = fread(key, sizeof(char), MAX_KEY_LEN, keyfile);
76+
if (!feof(keyfile)) {
77+
fprintf(stderr, "Error: key file too large: %s\n", SECRET_KEY_FILE);
78+
exit(1);
79+
}
80+
if (ferror(keyfile)) {
81+
fprintf(stderr, "Error: unable to read key from file: %s\n", SECRET_KEY_FILE);
82+
exit(1);
83+
}
84+
while (keysize > 1 && (key[keysize - 1] == '\n' || key[keysize - 1] == '\r'))
85+
keysize--;
86+
key[keysize] = 0;
87+
}
88+
6689
int main() {
6790
char *uid, *name;
6891
char *time_string;
6992
char *signature;
93+
char key[MAX_KEY_LEN + 1];
7094
// char **env;
7195

96+
readkey(key);
7297
if (!(uid = getenv(ENV_UID))) {
7398
fprintf(stderr, "Error: unable to get environment variable: %s\n", ENV_UID);
7499
exit(1);
@@ -83,7 +108,7 @@ int main() {
83108
printf(" \"name\": \"%s\",\n", name);
84109
time_string = iso8601Now();
85110
printf(" \"date\": \"%s\",\n", time_string);
86-
signature = sha256Signature(uid, name, time_string);
111+
signature = sha256Signature(uid, name, time_string, key);
87112
printf(" \"signature\": \"%s\"\n", signature);
88113
printf("}\n");
89114
/*

0 commit comments

Comments
 (0)