1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <fcntl.h>
4 #include <sched.h>
5 #include <sys/mount.h>
6 #include <unistd.h>
7 
8 #include "sd-id128.h"
9 
10 #include "alloc-util.h"
11 #include "fd-util.h"
12 #include "id128-util.h"
13 #include "io-util.h"
14 #include "log.h"
15 #include "machine-id-setup.h"
16 #include "macro.h"
17 #include "mkdir.h"
18 #include "mount-util.h"
19 #include "mountpoint-util.h"
20 #include "namespace-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
23 #include "stat-util.h"
24 #include "string-util.h"
25 #include "sync-util.h"
26 #include "umask-util.h"
27 #include "util.h"
28 #include "virt.h"
29 
generate_machine_id(const char * root,sd_id128_t * ret)30 static int generate_machine_id(const char *root, sd_id128_t *ret) {
31         const char *dbus_machine_id;
32         _cleanup_close_ int fd = -1;
33         int r;
34 
35         assert(ret);
36 
37         /* First, try reading the D-Bus machine id, unless it is a symlink */
38         dbus_machine_id = prefix_roota(root, "/var/lib/dbus/machine-id");
39         fd = open(dbus_machine_id, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
40         if (fd >= 0) {
41                 if (id128_read_fd(fd, ID128_PLAIN, ret) >= 0) {
42                         log_info("Initializing machine ID from D-Bus machine ID.");
43                         return 0;
44                 }
45 
46                 fd = safe_close(fd);
47         }
48 
49         if (isempty(root) && running_in_chroot() <= 0) {
50                 /* If that didn't work, see if we are running in a container,
51                  * and a machine ID was passed in via $container_uuid the way
52                  * libvirt/LXC does it */
53 
54                 if (detect_container() > 0) {
55                         _cleanup_free_ char *e = NULL;
56 
57                         if (getenv_for_pid(1, "container_uuid", &e) > 0 &&
58                             sd_id128_from_string(e, ret) >= 0) {
59                                 log_info("Initializing machine ID from container UUID.");
60                                 return 0;
61                         }
62 
63                 } else if (IN_SET(detect_vm(), VIRTUALIZATION_KVM, VIRTUALIZATION_AMAZON, VIRTUALIZATION_QEMU)) {
64 
65                         /* If we are not running in a container, see if we are running in a VM that provides
66                          * a system UUID via the SMBIOS/DMI interfaces.  Such environments include QEMU/KVM
67                          * with the -uuid on the qemu command line or the Amazon EC2 Nitro hypervisor. */
68 
69                         if (id128_get_product(ret) >= 0) {
70                                 log_info("Initializing machine ID from VM UUID.");
71                                 return 0;
72                         }
73                 }
74         }
75 
76         /* If that didn't work, generate a random machine id */
77         r = sd_id128_randomize(ret);
78         if (r < 0)
79                 return log_error_errno(r, "Failed to generate randomized machine ID: %m");
80 
81         log_info("Initializing machine ID from random generator.");
82         return 0;
83 }
84 
machine_id_setup(const char * root,bool force_transient,sd_id128_t machine_id,sd_id128_t * ret)85 int machine_id_setup(const char *root, bool force_transient, sd_id128_t machine_id, sd_id128_t *ret) {
86         const char *etc_machine_id, *run_machine_id;
87         _cleanup_close_ int fd = -1;
88         bool writable;
89         int r;
90 
91         etc_machine_id = prefix_roota(root, "/etc/machine-id");
92 
93         RUN_WITH_UMASK(0000) {
94                 /* We create this 0444, to indicate that this isn't really
95                  * something you should ever modify. Of course, since the file
96                  * will be owned by root it doesn't matter much, but maybe
97                  * people look. */
98 
99                 (void) mkdir_parents(etc_machine_id, 0755);
100                 fd = open(etc_machine_id, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0444);
101                 if (fd < 0) {
102                         int old_errno = errno;
103 
104                         fd = open(etc_machine_id, O_RDONLY|O_CLOEXEC|O_NOCTTY);
105                         if (fd < 0) {
106                                 if (old_errno == EROFS && errno == ENOENT)
107                                         return log_error_errno(errno,
108                                                   "System cannot boot: Missing /etc/machine-id and /etc is mounted read-only.\n"
109                                                   "Booting up is supported only when:\n"
110                                                   "1) /etc/machine-id exists and is populated.\n"
111                                                   "2) /etc/machine-id exists and is empty.\n"
112                                                   "3) /etc/machine-id is missing and /etc is writable.\n");
113                                 else
114                                         return log_error_errno(errno, "Cannot open %s: %m", etc_machine_id);
115                         }
116 
117                         writable = false;
118                 } else
119                         writable = true;
120         }
121 
122         /* A we got a valid machine ID argument, that's what counts */
123         if (sd_id128_is_null(machine_id)) {
124 
125                 /* Try to read any existing machine ID */
126                 if (id128_read_fd(fd, ID128_PLAIN, ret) >= 0)
127                         return 0;
128 
129                 /* Hmm, so, the id currently stored is not useful, then let's generate one */
130                 r = generate_machine_id(root, &machine_id);
131                 if (r < 0)
132                         return r;
133         }
134 
135         if (writable) {
136                 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
137                         return log_error_errno(errno, "Failed to seek %s: %m", etc_machine_id);
138 
139                 if (ftruncate(fd, 0) < 0)
140                         return log_error_errno(errno, "Failed to truncate %s: %m", etc_machine_id);
141 
142                 /* If the caller requested a transient machine-id, write the string "uninitialized\n" to
143                  * disk and overmount it with a transient file.
144                  *
145                  * Otherwise write the machine-id directly to disk. */
146                 if (force_transient) {
147                         r = loop_write(fd, "uninitialized\n", strlen("uninitialized\n"), false);
148                         if (r < 0)
149                                 return log_error_errno(r, "Failed to write uninitialized %s: %m", etc_machine_id);
150 
151                         r = fsync_full(fd);
152                         if (r < 0)
153                                 return log_error_errno(r, "Failed to sync %s: %m", etc_machine_id);
154                 } else {
155                         r = id128_write_fd(fd, ID128_PLAIN, machine_id, true);
156                         if (r < 0)
157                                 return log_error_errno(r, "Failed to write %s: %m", etc_machine_id);
158                         else
159                                 goto finish;
160                 }
161         }
162 
163         fd = safe_close(fd);
164 
165         /* Hmm, we couldn't or shouldn't write the machine-id to /etc?
166          * So let's write it to /run/machine-id as a replacement */
167 
168         run_machine_id = prefix_roota(root, "/run/machine-id");
169 
170         RUN_WITH_UMASK(0022)
171                 r = id128_write(run_machine_id, ID128_PLAIN, machine_id, false);
172         if (r < 0) {
173                 (void) unlink(run_machine_id);
174                 return log_error_errno(r, "Cannot write %s: %m", run_machine_id);
175         }
176 
177         /* And now, let's mount it over */
178         r = mount_follow_verbose(LOG_ERR, run_machine_id, etc_machine_id, NULL, MS_BIND, NULL);
179         if (r < 0) {
180                 (void) unlink(run_machine_id);
181                 return r;
182         }
183 
184         log_full(force_transient ? LOG_DEBUG : LOG_INFO, "Installed transient %s file.", etc_machine_id);
185 
186         /* Mark the mount read-only */
187         r = mount_follow_verbose(LOG_WARNING, NULL, etc_machine_id, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
188         if (r < 0)
189                 return r;
190 
191 finish:
192         if (ret)
193                 *ret = machine_id;
194 
195         return 0;
196 }
197 
machine_id_commit(const char * root)198 int machine_id_commit(const char *root) {
199         _cleanup_close_ int fd = -1, initial_mntns_fd = -1;
200         const char *etc_machine_id;
201         sd_id128_t id;
202         int r;
203 
204         /* Before doing anything, sync everything to ensure any changes by first-boot units are persisted.
205          *
206          * First, explicitly sync the file systems we care about and check if it worked. */
207         FOREACH_STRING(sync_path, "/etc/", "/var/") {
208                 r = syncfs_path(AT_FDCWD, sync_path);
209                 if (r < 0)
210                         return log_error_errno(r, "Cannot sync %s: %m", sync_path);
211         }
212 
213         /* Afterwards, sync() the rest too, but we can't check the return value for these. */
214         sync();
215 
216         /* Replaces a tmpfs bind mount of /etc/machine-id by a proper file, atomically. For this, the umount is removed
217          * in a mount namespace, a new file is created at the right place. Afterwards the mount is also removed in the
218          * original mount namespace, thus revealing the file that was just created. */
219 
220         etc_machine_id = prefix_roota(root, "/etc/machine-id");
221 
222         r = path_is_mount_point(etc_machine_id, NULL, 0);
223         if (r < 0)
224                 return log_error_errno(r, "Failed to determine whether %s is a mount point: %m", etc_machine_id);
225         if (r == 0) {
226                 log_debug("%s is not a mount point. Nothing to do.", etc_machine_id);
227                 return 0;
228         }
229 
230         /* Read existing machine-id */
231         fd = open(etc_machine_id, O_RDONLY|O_CLOEXEC|O_NOCTTY);
232         if (fd < 0)
233                 return log_error_errno(errno, "Cannot open %s: %m", etc_machine_id);
234 
235         r = fd_is_temporary_fs(fd);
236         if (r < 0)
237                 return log_error_errno(r, "Failed to determine whether %s is on a temporary file system: %m", etc_machine_id);
238         if (r == 0)
239                 return log_error_errno(SYNTHETIC_ERRNO(EROFS),
240                                        "%s is not on a temporary file system.",
241                                        etc_machine_id);
242 
243         r = id128_read_fd(fd, ID128_PLAIN, &id);
244         if (r < 0)
245                 return log_error_errno(r, "We didn't find a valid machine ID in %s: %m", etc_machine_id);
246 
247         fd = safe_close(fd);
248 
249         /* Store current mount namespace */
250         r = namespace_open(0, NULL, &initial_mntns_fd, NULL, NULL, NULL);
251         if (r < 0)
252                 return log_error_errno(r, "Can't fetch current mount namespace: %m");
253 
254         /* Switch to a new mount namespace, isolate ourself and unmount etc_machine_id in our new namespace */
255         r = detach_mount_namespace();
256         if (r < 0)
257                 return log_error_errno(r, "Failed to set up new mount namespace: %m");
258 
259         r = umount_verbose(LOG_ERR, etc_machine_id, 0);
260         if (r < 0)
261                 return r;
262 
263         /* Update a persistent version of etc_machine_id */
264         r = id128_write(etc_machine_id, ID128_PLAIN, id, true);
265         if (r < 0)
266                 return log_error_errno(r, "Cannot write %s. This is mandatory to get a persistent machine ID: %m", etc_machine_id);
267 
268         /* Return to initial namespace and proceed a lazy tmpfs unmount */
269         r = namespace_enter(-1, initial_mntns_fd, -1, -1, -1);
270         if (r < 0)
271                 return log_warning_errno(r, "Failed to switch back to initial mount namespace: %m.\nWe'll keep transient %s file until next reboot.", etc_machine_id);
272 
273         if (umount2(etc_machine_id, MNT_DETACH) < 0)
274                 return log_warning_errno(errno, "Failed to unmount transient %s file: %m.\nWe keep that mount until next reboot.", etc_machine_id);
275 
276         return 0;
277 }
278