]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/secret.c
import 15.2.0 Octopus source
[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 "include/compat.h"
23 #include "common/armor.h"
24 #include "common/safe_io.h"
25
26 int read_secret_from_file(const char *filename, char *secret, size_t max_len)
27 {
28 char *end;
29 int fd;
30 int len;
31
32 fd = open(filename, O_RDONLY);
33 if (fd < 0) {
34 perror("unable to read secretfile");
35 return -errno;
36 }
37 len = safe_read(fd, secret, max_len);
38 if (len <= 0) {
39 perror("unable to read secret from file");
40 close(fd);
41 return len ? len : -ENODATA;
42 }
43 end = secret;
44 while (end < secret + len && *end && *end != '\n' && *end != '\r')
45 end++;
46 *end = '\0';
47 close(fd);
48
49 return 0;
50 }
51
52 int set_kernel_secret(const char *secret, const char *key_name)
53 {
54 /* try to submit key to kernel via the keys api */
55 key_serial_t serial;
56 int ret;
57 int secret_len = strlen(secret);
58 char payload[((secret_len * 3) / 4) + 4];
59
60 if (!secret_len) {
61 fprintf(stderr, "secret is empty.\n");
62 return -EINVAL;
63 }
64
65 ret = ceph_unarmor(payload, payload+sizeof(payload), secret, secret+secret_len);
66 if (ret < 0) {
67 char error_buf[80];
68 fprintf(stderr, "secret is not valid base64: %s.\n",
69 ceph_strerror_r(-ret, error_buf, sizeof(error_buf)));
70 return ret;
71 }
72
73 serial = add_key("ceph", key_name, payload, ret, KEY_SPEC_PROCESS_KEYRING);
74 if (serial == -1) {
75 ret = -errno;
76 }
77
78 return ret;
79 }
80
81 int is_kernel_secret(const char *key_name)
82 {
83 key_serial_t serial;
84 serial = request_key("ceph", key_name, NULL, KEY_SPEC_USER_KEYRING);
85 return serial != -1;
86 }