]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/secret.c
import new upstream nautilus stable release 14.2.8
[ceph.git] / ceph / src / common / secret.c
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4 * Ceph - scalable distributed file system
5 *
6 * Copyright (C) 2011 New Dream Network
7 *
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
12 *
13 */
14
15 #include <string.h>
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <keyutils.h>
21
22 #include "common/armor.h"
23 #include "common/safe_io.h"
24
25 int read_secret_from_file(const char *filename, char *secret, size_t max_len)
26 {
27 char *end;
28 int fd;
29 int len;
30
31 fd = open(filename, O_RDONLY);
32 if (fd < 0) {
33 perror("unable to read secretfile");
34 return -errno;
35 }
36 len = safe_read(fd, secret, max_len);
37 if (len <= 0) {
38 perror("unable to read secret from file");
39 close(fd);
40 return len ? len : -ENODATA;
41 }
42 end = secret;
43 while (end < secret + len && *end && *end != '\n' && *end != '\r')
44 end++;
45 *end = '\0';
46 close(fd);
47
48 return 0;
49 }
50
51 int set_kernel_secret(const char *secret, const char *key_name)
52 {
53 /* try to submit key to kernel via the keys api */
54 key_serial_t serial;
55 int ret;
56 int secret_len = strlen(secret);
57 char payload[((secret_len * 3) / 4) + 4];
58
59 if (!secret_len) {
60 fprintf(stderr, "secret is empty.\n");
61 return -EINVAL;
62 }
63
64 ret = ceph_unarmor(payload, payload+sizeof(payload), secret, secret+secret_len);
65 if (ret < 0) {
66 char error_buf[80];
67 fprintf(stderr, "secret is not valid base64: %s.\n",
68 strerror_r(-ret, error_buf, sizeof(error_buf)));
69 return ret;
70 }
71
72 serial = add_key("ceph", key_name, payload, sizeof(payload), KEY_SPEC_PROCESS_KEYRING);
73 if (serial == -1) {
74 ret = -errno;
75 }
76
77 return ret;
78 }
79
80 int is_kernel_secret(const char *key_name)
81 {
82 key_serial_t serial;
83 serial = request_key("ceph", key_name, NULL, KEY_SPEC_USER_KEYRING);
84 return serial != -1;
85 }