1 /* $NetBSD: rm.c,v 1.58 2026/04/26 01:49:28 jschauma Exp $ */ 2 3 /*- 4 * Copyright (c) 1990, 1993, 1994, 2003 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 #ifndef lint 34 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\ 35 The Regents of the University of California. All rights reserved."); 36 #endif /* not lint */ 37 38 #ifndef lint 39 #if 0 40 static char sccsid[] = "@(#)rm.c 8.8 (Berkeley) 4/27/95"; 41 #else 42 __RCSID("$NetBSD: rm.c,v 1.58 2026/04/26 01:49:28 jschauma Exp $"); 43 #endif 44 #endif /* not lint */ 45 46 #include <sys/param.h> 47 #include <sys/stat.h> 48 #include <sys/types.h> 49 50 #include <err.h> 51 #include <errno.h> 52 #include <fcntl.h> 53 #include <fts.h> 54 #include <grp.h> 55 #include <locale.h> 56 #include <pwd.h> 57 #include <signal.h> 58 #include <stdio.h> 59 #include <stdlib.h> 60 #include <string.h> 61 #include <unistd.h> 62 63 static int dflag, eval, fflag, iflag, Pflag, stdin_ok, vflag, Wflag; 64 static int xflag; 65 static sig_atomic_t pinfo; 66 67 static int check(char *, char *, struct stat *, const char *); 68 static void checkdot(char **); 69 static void progress(int); 70 static void rm_file(char **); 71 static int rm_overwrite(char *, struct stat *); 72 static void rm_tree(char **); 73 __dead static void usage(void); 74 75 /* 76 * For the sake of the `-f' flag, check whether an error number indicates the 77 * failure of an operation due to an non-existent file, either per se (ENOENT) 78 * or because its filename argument was illegal (ENAMETOOLONG, ENOTDIR). 79 */ 80 #define NONEXISTENT(x) \ 81 ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR) 82 83 /* 84 * rm -- 85 * This rm is different from historic rm's, but is expected to match 86 * POSIX 1003.2 behavior. The most visible difference is that -f 87 * has two specific effects now, ignore non-existent files and force 88 * file removal. 89 */ 90 int 91 main(int argc, char *argv[]) 92 { 93 int ch, rflag; 94 95 setprogname(argv[0]); 96 (void)setlocale(LC_ALL, ""); 97 98 rflag = 0; 99 while ((ch = getopt(argc, argv, "dfiPRrvWx")) != -1) 100 switch (ch) { 101 case 'd': 102 dflag = 1; 103 break; 104 case 'f': 105 fflag = 1; 106 iflag = 0; 107 break; 108 case 'i': 109 fflag = 0; 110 iflag = 1; 111 break; 112 case 'P': 113 Pflag = 1; 114 break; 115 case 'R': 116 case 'r': /* Compatibility. */ 117 rflag = 1; 118 break; 119 case 'v': 120 vflag = 1; 121 break; 122 case 'x': 123 xflag = 1; 124 break; 125 case 'W': 126 Wflag = 1; 127 break; 128 case '?': 129 default: 130 usage(); 131 } 132 argc -= optind; 133 argv += optind; 134 135 if (argc < 1) { 136 if (fflag) 137 return 0; 138 usage(); 139 } 140 141 (void)signal(SIGINFO, progress); 142 143 checkdot(argv); 144 145 if (*argv) { 146 stdin_ok = isatty(STDIN_FILENO); 147 148 if (rflag) 149 rm_tree(argv); 150 else 151 rm_file(argv); 152 } 153 154 exit(eval); 155 /* NOTREACHED */ 156 } 157 158 static void 159 rm_tree(char **argv) 160 { 161 FTS *fts; 162 FTSENT *p; 163 int flags, needstat, rval; 164 165 /* 166 * Remove a file hierarchy. If forcing removal (-f), or interactive 167 * (-i) or can't ask anyway (stdin_ok), don't stat the file. 168 */ 169 needstat = !fflag && !iflag && stdin_ok; 170 171 /* 172 * If the -i option is specified, the user can skip on the pre-order 173 * visit. The fts_number field flags skipped directories. 174 */ 175 #define SKIPPED 1 176 177 flags = FTS_PHYSICAL; 178 if (!needstat) 179 flags |= FTS_NOSTAT; 180 if (Wflag) 181 flags |= FTS_WHITEOUT; 182 if (xflag) 183 flags |= FTS_XDEV; 184 if ((fts = fts_open(argv, flags, NULL)) == NULL) 185 err(1, "fts_open failed"); 186 while ((p = fts_read(fts)) != NULL) { 187 188 switch (p->fts_info) { 189 case FTS_DNR: 190 if (!fflag || p->fts_errno != ENOENT) { 191 warnx("%s: %s", p->fts_path, 192 strerror(p->fts_errno)); 193 eval = 1; 194 } 195 continue; 196 case FTS_ERR: 197 errx(EXIT_FAILURE, "%s: %s", p->fts_path, 198 strerror(p->fts_errno)); 199 /* NOTREACHED */ 200 case FTS_NS: 201 /* 202 * FTS_NS: assume that if can't stat the file, it 203 * can't be unlinked. 204 */ 205 if (fflag && NONEXISTENT(p->fts_errno)) 206 continue; 207 if (needstat) { 208 warnx("%s: %s", p->fts_path, 209 strerror(p->fts_errno)); 210 eval = 1; 211 continue; 212 } 213 break; 214 case FTS_D: 215 /* Pre-order: give user chance to skip. */ 216 if (!fflag && !check(p->fts_path, p->fts_accpath, 217 p->fts_statp, "examine files in")) { 218 (void)fts_set(fts, p, FTS_SKIP); 219 p->fts_number = SKIPPED; 220 } 221 continue; 222 case FTS_DP: 223 /* Post-order: see if user skipped. */ 224 if (p->fts_number == SKIPPED) 225 continue; 226 break; 227 default: 228 if (!fflag && 229 !check(p->fts_path, p->fts_accpath, p->fts_statp, "remove")) 230 continue; 231 } 232 233 rval = 0; 234 /* 235 * If we can't read or search the directory, may still be 236 * able to remove it. Don't print out the un{read,search}able 237 * message unless the remove fails. 238 */ 239 switch (p->fts_info) { 240 case FTS_DP: 241 case FTS_DNR: 242 if (!fflag && !check(p->fts_path, p->fts_accpath, p->fts_statp, 243 "remove")) 244 continue; 245 rval = rmdir(p->fts_accpath); 246 if (rval != 0 && fflag && errno == ENOENT) 247 continue; 248 break; 249 250 case FTS_W: 251 rval = undelete(p->fts_accpath); 252 if (rval != 0 && fflag && errno == ENOENT) 253 continue; 254 break; 255 256 default: 257 if (Pflag) { 258 if (rm_overwrite(p->fts_accpath, NULL)) 259 continue; 260 } 261 rval = unlink(p->fts_accpath); 262 if (rval != 0 && fflag && NONEXISTENT(errno)) 263 continue; 264 break; 265 } 266 if (rval != 0) { 267 warn("%s", p->fts_path); 268 eval = 1; 269 } else if (vflag || pinfo) { 270 pinfo = 0; 271 (void)printf("%s\n", p->fts_path); 272 } 273 } 274 if (errno) 275 err(1, "fts_read"); 276 fts_close(fts); 277 } 278 279 static void 280 rm_file(char **argv) 281 { 282 struct stat sb; 283 int rval; 284 char *f; 285 286 /* 287 * Remove a file. POSIX 1003.2 states that, by default, attempting 288 * to remove a directory is an error, so must always stat the file. 289 */ 290 while ((f = *argv++) != NULL) { 291 /* Assume if can't stat the file, can't unlink it. */ 292 if (lstat(f, &sb)) { 293 if (Wflag) { 294 sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR; 295 } else { 296 if (!fflag || !NONEXISTENT(errno)) { 297 warn("%s", f); 298 eval = 1; 299 } 300 continue; 301 } 302 } else if (Wflag) { 303 warnx("%s: %s", f, strerror(EEXIST)); 304 eval = 1; 305 continue; 306 } 307 308 if (S_ISDIR(sb.st_mode) && !dflag) { 309 warnx("%s: is a directory", f); 310 eval = 1; 311 continue; 312 } 313 if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb, "remove")) 314 continue; 315 if (S_ISWHT(sb.st_mode)) 316 rval = undelete(f); 317 else if (S_ISDIR(sb.st_mode)) 318 rval = rmdir(f); 319 else { 320 if (Pflag) { 321 if (rm_overwrite(f, &sb)) 322 continue; 323 } 324 rval = unlink(f); 325 } 326 if (rval && (!fflag || !NONEXISTENT(errno))) { 327 warn("%s", f); 328 eval = 1; 329 } 330 if (vflag && rval == 0) 331 (void)printf("%s\n", f); 332 } 333 } 334 335 /* 336 * rm_overwrite -- 337 * Overwrite the file 3 times with varying bit patterns. 338 * 339 * This is an expensive way to keep people from recovering files from your 340 * non-snapshotted FFS filesystems using fsdb(8). Really. No more. Only 341 * regular files are deleted, directories (and therefore names) will remain. 342 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a 343 * System V file system). In a logging file system, you'll have to have 344 * kernel support. 345 * 346 * A note on standards: U.S. DoD 5220.22-M "National Industrial Security 347 * Program Operating Manual" ("NISPOM") is often cited as a reference 348 * for clearing and sanitizing magnetic media. In fact, a matrix of 349 * "clearing" and "sanitization" methods for various media was given in 350 * Chapter 8 of the original 1995 version of NISPOM. However, that 351 * matrix was *removed from the document* when Chapter 8 was rewritten 352 * in Change 2 to the document in 2001. Recently, the Defense Security 353 * Service has made a revised clearing and sanitization matrix available 354 * in Microsoft Word format on the DSS web site. The standardization 355 * status of this matrix is unclear. Furthermore, one must be very 356 * careful when referring to this matrix: it is intended for the "clearing" 357 * prior to reuse or "sanitization" prior to disposal of *entire media*, 358 * not individual files and the only non-physically-destructive method of 359 * "sanitization" that is permitted for magnetic disks of any kind is 360 * specifically noted to be prohibited for media that have contained 361 * Top Secret data. 362 * 363 * It is impossible to actually conform to the exact procedure given in 364 * the matrix if one is overwriting a file, not an entire disk, because 365 * the procedure requires examination and comparison of the disk's defect 366 * lists. Any program that claims to securely erase *files* while 367 * conforming to the standard, then, is not correct. We do as much of 368 * what the standard requires as can actually be done when erasing a 369 * file, rather than an entire disk; but that does not make us conformant. 370 * 371 * Furthermore, the presence of track caches, disk and controller write 372 * caches, and so forth make it extremely difficult to ensure that data 373 * have actually been written to the disk, particularly when one tries 374 * to repeatedly overwrite the same sectors in quick succession. We call 375 * fsync(), but controllers with nonvolatile cache, as well as IDE disks 376 * that just plain lie about the stable storage of data, will defeat this. 377 * 378 * Finally, widely respected research suggests that the given procedure 379 * is nowhere near sufficient to prevent the recovery of data using special 380 * forensic equipment and techniques that are well-known. This is 381 * presumably one reason that the matrix requires physical media destruction, 382 * rather than any technique of the sort attempted here, for secret data. 383 * 384 * Caveat Emptor. 385 * 386 * rm_overwrite will return 0 on success. 387 */ 388 389 static int 390 rm_overwrite(char *file, struct stat *sbp) 391 { 392 struct stat sb, sb2; 393 int fd, randint; 394 char randchar; 395 396 fd = -1; 397 if (sbp == NULL) { 398 if (lstat(file, &sb)) 399 goto err; 400 sbp = &sb; 401 } 402 if (!S_ISREG(sbp->st_mode)) 403 return 0; 404 405 /* flags to try to defeat hidden caching by forcing seeks */ 406 if ((fd = open(file, O_RDWR|O_SYNC|O_RSYNC|O_NOFOLLOW, 0)) == -1) 407 goto err; 408 409 if (fstat(fd, &sb2)) { 410 goto err; 411 } 412 413 if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino || 414 !S_ISREG(sb2.st_mode)) { 415 errno = EPERM; 416 goto err; 417 } 418 419 #define RAND_BYTES 1 420 #define THIS_BYTE 0 421 422 #define WRITE_PASS(mode, byte) do { \ 423 off_t len; \ 424 size_t wlen, i; \ 425 char buf[8 * 1024]; \ 426 \ 427 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET)) \ 428 goto err; \ 429 \ 430 if (mode == THIS_BYTE) \ 431 memset(buf, byte, sizeof(buf)); \ 432 for (len = sbp->st_size; len > 0; len -= wlen) { \ 433 if (mode == RAND_BYTES) { \ 434 for (i = 0; i < sizeof(buf); \ 435 i+= sizeof(u_int32_t)) \ 436 *(int *)(buf + i) = arc4random(); \ 437 } \ 438 wlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \ 439 if ((size_t)write(fd, buf, wlen) != wlen) \ 440 goto err; \ 441 } \ 442 sync(); /* another poke at hidden caches */ \ 443 } while (0) 444 445 #define READ_PASS(byte) do { \ 446 off_t len; \ 447 size_t rlen; \ 448 char pattern[8 * 1024]; \ 449 char buf[8 * 1024]; \ 450 \ 451 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET)) \ 452 goto err; \ 453 \ 454 memset(pattern, byte, sizeof(pattern)); \ 455 for(len = sbp->st_size; len > 0; len -= rlen) { \ 456 rlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \ 457 if((size_t)read(fd, buf, rlen) != rlen) \ 458 goto err; \ 459 if(memcmp(buf, pattern, rlen)) \ 460 goto err; \ 461 } \ 462 sync(); /* another poke at hidden caches */ \ 463 } while (0) 464 465 /* 466 * DSS sanitization matrix "clear" for magnetic disks: 467 * option 'c' "Overwrite all addressable locations with a single 468 * character." 469 */ 470 randint = arc4random(); 471 randchar = *(char *)&randint; 472 WRITE_PASS(THIS_BYTE, randchar); 473 474 /* 475 * DSS sanitization matrix "sanitize" for magnetic disks: 476 * option 'd', sub 2 "Overwrite all addressable locations with a 477 * character, then its complement. Verify "complement" character 478 * was written successfully to all addressable locations, then 479 * overwrite all addressable locations with random characters; or 480 * verify third overwrite of random characters." The rest of the 481 * text in d-sub-2 specifies requirements for overwriting spared 482 * sectors; we cannot conform to it when erasing only a file, thus 483 * we do not conform to the standard. 484 */ 485 486 /* 1. "a character" */ 487 WRITE_PASS(THIS_BYTE, 0xff); 488 489 /* 2. "its complement" */ 490 WRITE_PASS(THIS_BYTE, 0x00); 491 492 /* 3. "Verify 'complement' character" */ 493 READ_PASS(0x00); 494 495 /* 4. "overwrite all addressable locations with random characters" */ 496 497 WRITE_PASS(RAND_BYTES, 0x00); 498 499 /* 500 * As the file might be huge, and we note that this revision of 501 * the matrix says "random characters", not "a random character" 502 * as the original did, we do not verify the random-character 503 * write; the "or" in the standard allows this. 504 */ 505 506 if (close(fd) == -1) { 507 fd = -1; 508 goto err; 509 } 510 511 return 0; 512 513 err: eval = 1; 514 warn("%s", file); 515 if (fd != -1) 516 close(fd); 517 return 1; 518 } 519 520 static int 521 check(char *path, char *name, struct stat *sp, const char *dowhat) 522 { 523 int ch, first; 524 char modep[15]; 525 526 /* Check -i first. */ 527 if (iflag) 528 (void)fprintf(stderr, "%s '%s'? ", dowhat, path); 529 else { 530 /* 531 * If it's not a symbolic link and it's unwritable and we're 532 * talking to a terminal, ask. Symbolic links are excluded 533 * because their permissions are meaningless. Check stdin_ok 534 * first because we may not have stat'ed the file. 535 */ 536 if (!stdin_ok || S_ISLNK(sp->st_mode) || 537 !(access(name, W_OK) && (errno != ETXTBSY))) 538 return (1); 539 strmode(sp->st_mode, modep); 540 if (Pflag) { 541 warnx( 542 "%s: -P was specified but file could not" 543 " be overwritten", path); 544 return 0; 545 } 546 (void)fprintf(stderr, "override %s%s%s:%s for '%s'? ", 547 modep + 1, modep[9] == ' ' ? "" : " ", 548 user_from_uid(sp->st_uid, 0), 549 group_from_gid(sp->st_gid, 0), path); 550 } 551 (void)fflush(stderr); 552 553 first = ch = getchar(); 554 while (ch != '\n' && ch != EOF) 555 ch = getchar(); 556 return (first == 'y' || first == 'Y'); 557 } 558 559 /* 560 * POSIX.2 requires that if "." or ".." are specified as the basename 561 * portion of an operand, a diagnostic message be written to standard 562 * error and nothing more be done with such operands. 563 * 564 * Since POSIX.2 defines basename as the final portion of a path after 565 * trailing slashes have been removed, we'll remove them here. 566 */ 567 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2]))) 568 static void 569 checkdot(char **argv) 570 { 571 char *p, **save, **t; 572 int complained; 573 574 complained = 0; 575 for (t = argv; *t;) { 576 /* strip trailing slashes */ 577 p = strrchr(*t, '\0'); 578 while (--p > *t && *p == '/') 579 *p = '\0'; 580 581 /* extract basename */ 582 if ((p = strrchr(*t, '/')) != NULL) 583 ++p; 584 else 585 p = *t; 586 587 if (ISDOT(p)) { 588 if (!complained++) 589 warnx("\".\" and \"..\" may not be removed"); 590 eval = 1; 591 for (save = t; (t[0] = t[1]) != NULL; ++t) 592 continue; 593 t = save; 594 } else 595 ++t; 596 } 597 } 598 599 static void 600 usage(void) 601 { 602 603 (void)fprintf(stderr, "usage: %s [-f|-i] [-dPRrvWx] file ...\n", 604 getprogname()); 605 exit(1); 606 /* NOTREACHED */ 607 } 608 609 static void 610 progress(int sig __unused) 611 { 612 613 pinfo++; 614 } 615