test: use consistent quoting
[coreutils.git] / src / shred.c
blob08e212a23dfa5b7d037b1cef8bfdab4117e3185e
1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2015 Free Software Foundation, Inc.
4 Copyright (C) 1997, 1998, 1999 Colin Plumb.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 Written by Colin Plumb. */
22 * Do a more secure overwrite of given files or devices, to make it harder
23 * for even very expensive hardware probing to recover the data.
25 * Although this process is also known as "wiping", I prefer the longer
26 * name both because I think it is more evocative of what is happening and
27 * because a longer name conveys a more appropriate sense of deliberateness.
29 * For the theory behind this, see "Secure Deletion of Data from Magnetic
30 * and Solid-State Memory", on line at
31 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
33 * Just for the record, reversing one or two passes of disk overwrite
34 * is not terribly difficult with hardware help. Hook up a good-quality
35 * digitizing oscilloscope to the output of the head preamplifier and copy
36 * the high-res digitized data to a computer for some off-line analysis.
37 * Read the "current" data and average all the pulses together to get an
38 * "average" pulse on the disk. Subtract this average pulse from all of
39 * the actual pulses and you can clearly see the "echo" of the previous
40 * data on the disk.
42 * Real hard drives have to balance the cost of the media, the head,
43 * and the read circuitry. They use better-quality media than absolutely
44 * necessary to limit the cost of the read circuitry. By throwing that
45 * assumption out, and the assumption that you want the data processed
46 * as fast as the hard drive can spin, you can do better.
48 * If asked to wipe a file, this also unlinks it, renaming it to in a
49 * clever way to try to leave no trace of the original filename.
51 * This was inspired by a desire to improve on some code titled:
52 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
53 * but I've rewritten everything here so completely that no trace of
54 * the original remains.
56 * Thanks to:
57 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
58 * paperwork.
59 * Jim Meyering, for his work merging this into the GNU fileutils while
60 * still letting me feel a sense of ownership and pride. Getting me to
61 * tolerate the GNU brace style was quite a feat of diplomacy.
62 * Paul Eggert, for lots of useful discussion and code. I disagree with
63 * an awful lot of his suggestions, but they're disagreements worth having.
65 * Things to think about:
66 * - Security: Is there any risk to the race
67 * between overwriting and unlinking a file? Will it do anything
68 * drastically bad if told to attack a named pipe or socket?
71 /* The official name of this program (e.g., no 'g' prefix). */
72 #define PROGRAM_NAME "shred"
74 #define AUTHORS proper_name ("Colin Plumb")
76 #include <config.h>
78 #include <getopt.h>
79 #include <stdio.h>
80 #include <assert.h>
81 #include <setjmp.h>
82 #include <sys/types.h>
83 #ifdef __linux__
84 # include <sys/mtio.h>
85 #endif
87 #include "system.h"
88 #include "argmatch.h"
89 #include "xdectoint.h"
90 #include "error.h"
91 #include "fcntl--.h"
92 #include "human.h"
93 #include "randint.h"
94 #include "randread.h"
95 #include "stat-size.h"
97 /* Default number of times to overwrite. */
98 enum { DEFAULT_PASSES = 3 };
100 /* How many seconds to wait before checking whether to output another
101 verbose output line. */
102 enum { VERBOSE_UPDATE = 5 };
104 /* Sector size and corresponding mask, for recovering after write failures.
105 The size must be a power of 2. */
106 enum { SECTOR_SIZE = 512 };
107 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
108 verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
110 enum remove_method
112 remove_none = 0, /* the default: only wipe data. */
113 remove_unlink, /* don't obfuscate name, just unlink. */
114 remove_wipe, /* obfuscate name before unlink. */
115 remove_wipesync /* obfuscate name, syncing each byte, before unlink. */
118 static char const *const remove_args[] =
120 "unlink", "wipe", "wipesync", NULL
123 static enum remove_method const remove_methods[] =
125 remove_unlink, remove_wipe, remove_wipesync
128 struct Options
130 bool force; /* -f flag: chmod files if necessary */
131 size_t n_iterations; /* -n flag: Number of iterations */
132 off_t size; /* -s flag: size of file */
133 enum remove_method remove_file; /* -u flag: remove file after shredding */
134 bool verbose; /* -v flag: Print progress */
135 bool exact; /* -x flag: Do not round up file size */
136 bool zero_fill; /* -z flag: Add a final zero pass */
139 /* For long options that have no equivalent short option, use a
140 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
141 enum
143 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
146 static struct option const long_opts[] =
148 {"exact", no_argument, NULL, 'x'},
149 {"force", no_argument, NULL, 'f'},
150 {"iterations", required_argument, NULL, 'n'},
151 {"size", required_argument, NULL, 's'},
152 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
153 {"remove", optional_argument, NULL, 'u'},
154 {"verbose", no_argument, NULL, 'v'},
155 {"zero", no_argument, NULL, 'z'},
156 {GETOPT_HELP_OPTION_DECL},
157 {GETOPT_VERSION_OPTION_DECL},
158 {NULL, 0, NULL, 0}
161 void
162 usage (int status)
164 if (status != EXIT_SUCCESS)
165 emit_try_help ();
166 else
168 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
169 fputs (_("\
170 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
171 for even very expensive hardware probing to recover the data.\n\
172 "), stdout);
173 fputs (_("\
175 If FILE is -, shred standard output.\n\
176 "), stdout);
178 emit_mandatory_arg_note ();
180 printf (_("\
181 -f, --force change permissions to allow writing if necessary\n\
182 -n, --iterations=N overwrite N times instead of the default (%d)\n\
183 --random-source=FILE get random bytes from FILE\n\
184 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
185 "), DEFAULT_PASSES);
186 fputs (_("\
187 -u truncate and remove file after overwriting\n\
188 --remove[=HOW] like -u but give control on HOW to delete; See below\n\
189 -v, --verbose show progress\n\
190 -x, --exact do not round file sizes up to the next full block;\n\
191 this is the default for non-regular files\n\
192 -z, --zero add a final overwrite with zeros to hide shredding\n\
193 "), stdout);
194 fputs (HELP_OPTION_DESCRIPTION, stdout);
195 fputs (VERSION_OPTION_DESCRIPTION, stdout);
196 fputs (_("\
198 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
199 the files because it is common to operate on device files like /dev/hda,\n\
200 and those files usually should not be removed.\n\
201 The optional HOW parameter indicates how to remove a directory entry:\n\
202 'unlink' => use a standard unlink call.\n\
203 'wipe' => also first obfuscate bytes in the name.\n\
204 'wipesync' => also sync each obfuscated byte to disk.\n\
205 The default mode is 'wipesync', but note it can be expensive.\n\
207 "), stdout);
208 fputs (_("\
209 CAUTION: Note that shred relies on a very important assumption:\n\
210 that the file system overwrites data in place. This is the traditional\n\
211 way to do things, but many modern file system designs do not satisfy this\n\
212 assumption. The following are examples of file systems on which shred is\n\
213 not effective, or is not guaranteed to be effective in all file system modes:\n\
215 "), stdout);
216 fputs (_("\
217 * log-structured or journaled file systems, such as those supplied with\n\
218 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
220 * file systems that write redundant data and carry on even if some writes\n\
221 fail, such as RAID-based file systems\n\
223 * file systems that make snapshots, such as Network Appliance's NFS server\n\
225 "), stdout);
226 fputs (_("\
227 * file systems that cache in temporary locations, such as NFS\n\
228 version 3 clients\n\
230 * compressed file systems\n\
232 "), stdout);
233 fputs (_("\
234 In the case of ext3 file systems, the above disclaimer applies\n\
235 (and shred is thus of limited effectiveness) only in data=journal mode,\n\
236 which journals file data in addition to just metadata. In both the\n\
237 data=ordered (default) and data=writeback modes, shred works as usual.\n\
238 Ext3 journaling modes can be changed by adding the data=something option\n\
239 to the mount options for a particular file system in the /etc/fstab file,\n\
240 as documented in the mount man page (man mount).\n\
242 "), stdout);
243 fputs (_("\
244 In addition, file system backups and remote mirrors may contain copies\n\
245 of the file that cannot be removed, and that will allow a shredded file\n\
246 to be recovered later.\n\
247 "), stdout);
248 emit_ancillary_info (PROGRAM_NAME);
250 exit (status);
254 * Determine if pattern type is periodic or not.
256 static bool
257 periodic_pattern (int type)
259 if (type <= 0)
260 return false;
262 unsigned char r[3];
263 unsigned int bits = type & 0xfff;
265 bits |= bits << 12;
266 r[0] = (bits >> 4) & 255;
267 r[1] = (bits >> 8) & 255;
268 r[2] = bits & 255;
270 return (r[0] != r[1]) || (r[0] != r[2]);
274 * Fill a buffer with a fixed pattern.
276 * The buffer must be at least 3 bytes long, even if
277 * size is less. Larger sizes are filled exactly.
279 static void
280 fillpattern (int type, unsigned char *r, size_t size)
282 size_t i;
283 unsigned int bits = type & 0xfff;
285 bits |= bits << 12;
286 r[0] = (bits >> 4) & 255;
287 r[1] = (bits >> 8) & 255;
288 r[2] = bits & 255;
289 for (i = 3; i < size / 2; i *= 2)
290 memcpy (r + i, r, i);
291 if (i < size)
292 memcpy (r + i, r, size - i);
294 /* Invert the first bit of every sector. */
295 if (type & 0x1000)
296 for (i = 0; i < size; i += SECTOR_SIZE)
297 r[i] ^= 0x80;
301 * Generate a 6-character (+ nul) pass name string
302 * FIXME: allow translation of "random".
304 #define PASS_NAME_SIZE 7
305 static void
306 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
308 if (data)
309 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
310 else
311 memcpy (name, "random", PASS_NAME_SIZE);
314 /* Return true when it's ok to ignore an fsync or fdatasync
315 failure that set errno to ERRNO_VAL. */
316 static bool
317 ignorable_sync_errno (int errno_val)
319 return (errno_val == EINVAL
320 || errno_val == EBADF
321 /* HP-UX does this */
322 || errno_val == EISDIR);
325 /* Request that all data for FD be transferred to the corresponding
326 storage device. QNAME is the file name (quoted for colons).
327 Report any errors found. Return 0 on success, -1
328 (setting errno) on failure. It is not an error if fdatasync and/or
329 fsync is not supported for this file, or if the file is not a
330 writable file descriptor. */
331 static int
332 dosync (int fd, char const *qname)
334 int err;
336 #if HAVE_FDATASYNC
337 if (fdatasync (fd) == 0)
338 return 0;
339 err = errno;
340 if ( ! ignorable_sync_errno (err))
342 error (0, err, _("%s: fdatasync failed"), qname);
343 errno = err;
344 return -1;
346 #endif
348 if (fsync (fd) == 0)
349 return 0;
350 err = errno;
351 if ( ! ignorable_sync_errno (err))
353 error (0, err, _("%s: fsync failed"), qname);
354 errno = err;
355 return -1;
358 sync ();
359 return 0;
362 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
363 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
364 static void
365 direct_mode (int fd, bool enable)
367 if (O_DIRECT)
369 int fd_flags = fcntl (fd, F_GETFL);
370 if (0 < fd_flags)
372 int new_flags = (enable
373 ? (fd_flags | O_DIRECT)
374 : (fd_flags & ~O_DIRECT));
375 if (new_flags != fd_flags)
376 fcntl (fd, F_SETFL, new_flags);
380 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
381 /* This is Solaris-specific. See the following for details:
382 http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view */
383 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
384 #endif
387 /* Rewind FD; its status is ST. */
388 static bool
389 dorewind (int fd, struct stat const *st)
391 if (S_ISCHR (st->st_mode))
393 #ifdef __linux__
394 /* In the Linux kernel, lseek does not work on tape devices; it
395 returns a randomish value instead. Try the low-level tape
396 rewind operation first. */
397 struct mtop op;
398 op.mt_op = MTREW;
399 op.mt_count = 1;
400 if (ioctl (fd, MTIOCTOP, &op) == 0)
401 return true;
402 #endif
404 off_t offset = lseek (fd, 0, SEEK_SET);
405 if (0 < offset)
406 errno = EINVAL;
407 return offset == 0;
410 /* By convention, negative sizes represent unknown values. */
412 static bool
413 known (off_t size)
415 return 0 <= size;
419 * Do pass number K of N, writing *SIZEP bytes of the given pattern TYPE
420 * to the file descriptor FD. K and N are passed in only for verbose
421 * progress message purposes. If N == 0, no progress messages are printed.
423 * If *SIZEP == -1, the size is unknown, and it will be filled in as soon
424 * as writing fails with ENOSPC.
426 * Return 1 on write error, -1 on other error, 0 on success.
428 static int
429 dopass (int fd, struct stat const *st, char const *qname, off_t *sizep,
430 int type, struct randread_source *s,
431 unsigned long int k, unsigned long int n)
433 off_t size = *sizep;
434 off_t offset; /* Current file posiiton */
435 time_t thresh IF_LINT ( = 0); /* Time to maybe print next status update */
436 time_t now = 0; /* Current time */
437 size_t lim; /* Amount of data to try writing */
438 size_t soff; /* Offset into buffer for next write */
439 ssize_t ssize; /* Return value from write */
441 /* Fill pattern buffer. Aligning it to a page so we can do direct I/O. */
442 size_t page_size = getpagesize ();
443 #define PERIODIC_OUTPUT_SIZE (60 * 1024)
444 #define NONPERIODIC_OUTPUT_SIZE (64 * 1024)
445 verify (PERIODIC_OUTPUT_SIZE % 3 == 0);
446 size_t output_size = periodic_pattern (type)
447 ? PERIODIC_OUTPUT_SIZE : NONPERIODIC_OUTPUT_SIZE;
448 #define PAGE_ALIGN_SLOP (page_size - 1) /* So directio works */
449 #define FILLPATTERN_SIZE (((output_size + 2) / 3) * 3) /* Multiple of 3 */
450 #define PATTERNBUF_SIZE (PAGE_ALIGN_SLOP + FILLPATTERN_SIZE)
451 void *fill_pattern_mem = xmalloc (PATTERNBUF_SIZE);
452 unsigned char *pbuf = ptr_align (fill_pattern_mem, page_size);
454 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
455 bool write_error = false;
456 bool other_error = false;
458 /* Printable previous offset into the file */
459 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
460 char const *previous_human_offset IF_LINT ( = 0);
462 /* As a performance tweak, avoid direct I/O for small sizes,
463 as it's just a performance rather then security consideration,
464 and direct I/O can often be unsupported for small non aligned sizes. */
465 bool try_without_directio = 0 < size && size < output_size;
466 if (! try_without_directio)
467 direct_mode (fd, true);
469 if (! dorewind (fd, st))
471 error (0, errno, _("%s: cannot rewind"), qname);
472 other_error = true;
473 goto free_pattern_mem;
476 /* Constant fill patterns need only be set up once. */
477 if (type >= 0)
479 lim = known (size) && size < FILLPATTERN_SIZE ? size : FILLPATTERN_SIZE;
480 fillpattern (type, pbuf, lim);
481 passname (pbuf, pass_string);
483 else
485 passname (0, pass_string);
488 /* Set position if first status update */
489 if (n)
491 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
492 thresh = time (NULL) + VERBOSE_UPDATE;
493 previous_human_offset = "";
496 offset = 0;
497 while (true)
499 /* How much to write this time? */
500 lim = output_size;
501 if (known (size) && size - offset < output_size)
503 if (size < offset)
504 break;
505 lim = size - offset;
506 if (!lim)
507 break;
509 if (type < 0)
510 randread (s, pbuf, lim);
511 /* Loop to retry partial writes. */
512 for (soff = 0; soff < lim; soff += ssize)
514 ssize = write (fd, pbuf + soff, lim - soff);
515 if (0 < ssize)
516 assume (ssize <= lim - soff);
517 else
519 if (! known (size) && (ssize == 0 || errno == ENOSPC))
521 /* We have found the end of the file. */
522 if (soff <= OFF_T_MAX - offset)
523 *sizep = size = offset + soff;
524 break;
526 else
528 int errnum = errno;
529 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
531 /* Retry without direct I/O since this may not be supported
532 at all on some (file) systems, or with the current size.
533 I.e., a specified --size that is not aligned, or when
534 dealing with slop at the end of a file with --exact. */
535 if (! try_without_directio && errno == EINVAL)
537 direct_mode (fd, false);
538 ssize = 0;
539 try_without_directio = true;
540 continue;
542 error (0, errnum, _("%s: error writing at offset %s"),
543 qname, umaxtostr (offset + soff, buf));
545 /* 'shred' is often used on bad media, before throwing it
546 out. Thus, it shouldn't give up on bad blocks. This
547 code works because lim is always a multiple of
548 SECTOR_SIZE, except at the end. This size constraint
549 also enables direct I/O on some (file) systems. */
550 verify (PERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
551 verify (NONPERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
552 if (errnum == EIO && known (size)
553 && (soff | SECTOR_MASK) < lim)
555 size_t soff1 = (soff | SECTOR_MASK) + 1;
556 if (lseek (fd, offset + soff1, SEEK_SET) != -1)
558 /* Arrange to skip this block. */
559 ssize = soff1 - soff;
560 write_error = true;
561 continue;
563 error (0, errno, _("%s: lseek failed"), qname);
565 other_error = true;
566 goto free_pattern_mem;
571 /* Okay, we have written "soff" bytes. */
573 if (OFF_T_MAX - offset < soff)
575 error (0, 0, _("%s: file too large"), qname);
576 other_error = true;
577 goto free_pattern_mem;
580 offset += soff;
582 bool done = offset == size;
584 /* Time to print progress? */
585 if (n && ((done && *previous_human_offset)
586 || thresh <= (now = time (NULL))))
588 char offset_buf[LONGEST_HUMAN_READABLE + 1];
589 char size_buf[LONGEST_HUMAN_READABLE + 1];
590 int human_progress_opts = (human_autoscale | human_SI
591 | human_base_1024 | human_B);
592 char const *human_offset
593 = human_readable (offset, offset_buf,
594 human_floor | human_progress_opts, 1, 1);
596 if (done || !STREQ (previous_human_offset, human_offset))
598 if (! known (size))
599 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
600 qname, k, n, pass_string, human_offset);
601 else
603 uintmax_t off = offset;
604 int percent = (size == 0
605 ? 100
606 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
607 ? off * 100 / size
608 : off / (size / 100)));
609 char const *human_size
610 = human_readable (size, size_buf,
611 human_ceiling | human_progress_opts,
612 1, 1);
613 if (done)
614 human_offset = human_size;
615 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
616 qname, k, n, pass_string, human_offset, human_size,
617 percent);
620 strcpy (previous_offset_buf, human_offset);
621 previous_human_offset = previous_offset_buf;
622 thresh = now + VERBOSE_UPDATE;
625 * Force periodic syncs to keep displayed progress accurate
626 * FIXME: Should these be present even if -v is not enabled,
627 * to keep the buffer cache from filling with dirty pages?
628 * It's a common problem with programs that do lots of writes,
629 * like mkfs.
631 if (dosync (fd, qname) != 0)
633 if (errno != EIO)
635 other_error = true;
636 goto free_pattern_mem;
638 write_error = true;
644 /* Force what we just wrote to hit the media. */
645 if (dosync (fd, qname) != 0)
647 if (errno != EIO)
649 other_error = true;
650 goto free_pattern_mem;
652 write_error = true;
655 free_pattern_mem:
656 memset (pbuf, 0, FILLPATTERN_SIZE);
657 free (fill_pattern_mem);
659 return other_error ? -1 : write_error;
663 * The passes start and end with a random pass, and the passes in between
664 * are done in random order. The idea is to deprive someone trying to
665 * reverse the process of knowledge of the overwrite patterns, so they
666 * have the additional step of figuring out what was done to the disk
667 * before they can try to reverse or cancel it.
669 * First, all possible 1-bit patterns. There are two of them.
670 * Then, all possible 2-bit patterns. There are four, but the two
671 * which are also 1-bit patterns can be omitted.
672 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
673 * Then, all possible 4-bit patterns. 16-4 = 12.
675 * The basic passes are:
676 * 1-bit: 0x000, 0xFFF
677 * 2-bit: 0x555, 0xAAA
678 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
679 * 100100100100 110110110110
680 * 9 2 4 D B 6
681 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
682 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
683 * Adding three random passes at the beginning, middle and end
684 * produces the default 25-pass structure.
686 * The next extension would be to 5-bit and 6-bit patterns.
687 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
688 * 6-bit patterns, so they would increase the time required
689 * significantly. 4-bit patterns are enough for most purposes.
691 * The main gotcha is that this would require a trickier encoding,
692 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
693 * lcm(2,3,4,5) = 60 bits is not.
695 * One extension that is included is to complement the first bit in each
696 * 512-byte block, to alter the phase of the encoded data in the more
697 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
698 * are considered part of the 3-bit ones and the 2-bit patterns are
699 * considered part of the 4-bit patterns.
702 * How does the generalization to variable numbers of passes work?
704 * Here's how...
705 * Have an ordered list of groups of passes. Each group is a set.
706 * Take as many groups as will fit, plus a random subset of the
707 * last partial group, and place them into the passes list.
708 * Then shuffle the passes list into random order and use that.
710 * One extra detail: if we can't include a large enough fraction of the
711 * last group to be interesting, then just substitute random passes.
713 * If you want more passes than the entire list of groups can
714 * provide, just start repeating from the beginning of the list.
716 static int const
717 patterns[] =
719 -2, /* 2 random passes */
720 2, 0x000, 0xFFF, /* 1-bit */
721 2, 0x555, 0xAAA, /* 2-bit */
722 -1, /* 1 random pass */
723 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
724 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
725 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
726 -1, /* 1 random pass */
727 /* The following patterns have the first bit per block flipped */
728 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
729 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
730 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
731 -1, /* 1 random pass */
732 0 /* End */
736 * Generate a random wiping pass pattern with num passes.
737 * This is a two-stage process. First, the passes to include
738 * are chosen, and then they are shuffled into the desired
739 * order.
741 static void
742 genpattern (int *dest, size_t num, struct randint_source *s)
744 size_t randpasses;
745 int const *p;
746 int *d;
747 size_t n;
748 size_t accum, top, swap;
749 int k;
751 if (!num)
752 return;
754 /* Stage 1: choose the passes to use */
755 p = patterns;
756 randpasses = 0;
757 d = dest; /* Destination for generated pass list */
758 n = num; /* Passes remaining to fill */
760 while (true)
762 k = *p++; /* Block descriptor word */
763 if (!k)
764 { /* Loop back to the beginning */
765 p = patterns;
767 else if (k < 0)
768 { /* -k random passes */
769 k = -k;
770 if ((size_t) k >= n)
772 randpasses += n;
773 break;
775 randpasses += k;
776 n -= k;
778 else if ((size_t) k <= n)
779 { /* Full block of patterns */
780 memcpy (d, p, k * sizeof (int));
781 p += k;
782 d += k;
783 n -= k;
785 else if (n < 2 || 3 * n < (size_t) k)
786 { /* Finish with random */
787 randpasses += n;
788 break;
790 else
791 { /* Pad out with n of the k available */
794 if (n == (size_t) k || randint_choose (s, k) < n)
796 *d++ = *p;
797 n--;
799 p++;
800 k--;
802 while (n);
803 break;
806 top = num - randpasses; /* Top of initialized data */
807 /* assert (d == dest+top); */
810 * We now have fixed patterns in the dest buffer up to
811 * "top", and we need to scramble them, with "randpasses"
812 * random passes evenly spaced among them.
814 * We want one at the beginning, one at the end, and
815 * evenly spaced in between. To do this, we basically
816 * use Bresenham's line draw (a.k.a DDA) algorithm
817 * to draw a line with slope (randpasses-1)/(num-1).
818 * (We use a positive accumulator and count down to
819 * do this.)
821 * So for each desired output value, we do the following:
822 * - If it should be a random pass, copy the pass type
823 * to top++, out of the way of the other passes, and
824 * set the current pass to -1 (random).
825 * - If it should be a normal pattern pass, choose an
826 * entry at random between here and top-1 (inclusive)
827 * and swap the current entry with that one.
829 randpasses--; /* To speed up later math */
830 accum = randpasses; /* Bresenham DDA accumulator */
831 for (n = 0; n < num; n++)
833 if (accum <= randpasses)
835 accum += num - 1;
836 dest[top++] = dest[n];
837 dest[n] = -1;
839 else
841 swap = n + randint_choose (s, top - n);
842 k = dest[n];
843 dest[n] = dest[swap];
844 dest[swap] = k;
846 accum -= randpasses;
848 /* assert (top == num); */
852 * The core routine to actually do the work. This overwrites the first
853 * size bytes of the given fd. Return true if successful.
855 static bool
856 do_wipefd (int fd, char const *qname, struct randint_source *s,
857 struct Options const *flags)
859 size_t i;
860 struct stat st;
861 off_t size; /* Size to write, size to read */
862 off_t i_size = 0; /* For small files, initial size to overwrite inode */
863 unsigned long int n; /* Number of passes for printing purposes */
864 int *passarray;
865 bool ok = true;
866 struct randread_source *rs;
868 n = 0; /* dopass takes n == 0 to mean "don't print progress" */
869 if (flags->verbose)
870 n = flags->n_iterations + flags->zero_fill;
872 if (fstat (fd, &st))
874 error (0, errno, _("%s: fstat failed"), qname);
875 return false;
878 /* If we know that we can't possibly shred the file, give up now.
879 Otherwise, we may go into an infinite loop writing data before we
880 find that we can't rewind the device. */
881 if ((S_ISCHR (st.st_mode) && isatty (fd))
882 || S_ISFIFO (st.st_mode)
883 || S_ISSOCK (st.st_mode))
885 error (0, 0, _("%s: invalid file type"), qname);
886 return false;
888 else if (S_ISREG (st.st_mode) && st.st_size < 0)
890 error (0, 0, _("%s: file has negative size"), qname);
891 return false;
894 /* Allocate pass array */
895 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
897 size = flags->size;
898 if (size == -1)
900 if (S_ISREG (st.st_mode))
902 size = st.st_size;
904 if (! flags->exact)
906 /* Round up to the nearest block size to clear slack space. */
907 off_t remainder = size % ST_BLKSIZE (st);
908 if (size && size < ST_BLKSIZE (st))
909 i_size = size;
910 if (remainder != 0)
912 off_t size_incr = ST_BLKSIZE (st) - remainder;
913 size += MIN (size_incr, OFF_T_MAX - size);
917 else
919 /* The behavior of lseek is unspecified, but in practice if
920 it returns a positive number that's the size of this
921 device. */
922 size = lseek (fd, 0, SEEK_END);
923 if (size <= 0)
925 /* We are unable to determine the length, up front.
926 Let dopass do that as part of its first iteration. */
927 size = -1;
931 else if (S_ISREG (st.st_mode)
932 && st.st_size < MIN (ST_BLKSIZE (st), size))
933 i_size = st.st_size;
935 /* Schedule the passes in random order. */
936 genpattern (passarray, flags->n_iterations, s);
938 rs = randint_get_source (s);
940 while (true)
942 off_t pass_size;
943 unsigned long int pn = n;
945 if (i_size)
947 pass_size = i_size;
948 i_size = 0;
949 pn = 0;
951 else if (size)
953 pass_size = size;
954 size = 0;
956 /* TODO: consider handling tail packing by
957 writing the tail padding as a separate pass,
958 (that would not rewind). */
959 else
960 break;
962 for (i = 0; i < flags->n_iterations + flags->zero_fill; i++)
964 int err = 0;
965 int type = i < flags->n_iterations ? passarray[i] : 0;
967 err = dopass (fd, &st, qname, &pass_size, type, rs, i + 1, pn);
969 if (err)
971 ok = false;
972 if (err < 0)
973 goto wipefd_out;
978 /* Now deallocate the data. The effect of ftruncate on
979 non-regular files is unspecified, so don't worry about any
980 errors reported for them. */
981 if (flags->remove_file && ftruncate (fd, 0) != 0
982 && S_ISREG (st.st_mode))
984 error (0, errno, _("%s: error truncating"), qname);
985 ok = false;
986 goto wipefd_out;
989 wipefd_out:
990 memset (passarray, 0, flags->n_iterations * sizeof (int));
991 free (passarray);
992 return ok;
995 /* A wrapper with a little more checking for fds on the command line */
996 static bool
997 wipefd (int fd, char const *qname, struct randint_source *s,
998 struct Options const *flags)
1000 int fd_flags = fcntl (fd, F_GETFL);
1002 if (fd_flags < 0)
1004 error (0, errno, _("%s: fcntl failed"), qname);
1005 return false;
1007 if (fd_flags & O_APPEND)
1009 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1010 return false;
1012 return do_wipefd (fd, qname, s, flags);
1015 /* --- Name-wiping code --- */
1017 /* Characters allowed in a file name - a safe universal set. */
1018 static char const nameset[] =
1019 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
1021 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
1022 number with the digits taken from nameset. Return true if successful.
1023 Otherwise, (because NAME already has the greatest possible value)
1024 return false. */
1026 static bool
1027 incname (char *name, size_t len)
1029 while (len--)
1031 char const *p = strchr (nameset, name[len]);
1033 /* Given that NAME is composed of bytes from NAMESET,
1034 P will never be NULL here. */
1035 assert (p);
1037 /* If this character has a successor, use it. */
1038 if (p[1])
1040 name[len] = p[1];
1041 return true;
1044 /* Otherwise, set this digit to 0 and increment the prefix. */
1045 name[len] = nameset[0];
1048 return false;
1052 * Repeatedly rename a file with shorter and shorter names,
1053 * to obliterate all traces of the file name (and length) on any system
1054 * that adds a trailing delimiter to on-disk file names and reuses
1055 * the same directory slot. Finally, unlink it.
1056 * The passed-in filename is modified in place to the new filename.
1057 * (Which is unlinked if this function succeeds, but is still present if
1058 * it fails for some reason.)
1060 * The main loop is written carefully to not get stuck if all possible
1061 * names of a given length are occupied. It counts down the length from
1062 * the original to 0. While the length is non-zero, it tries to find an
1063 * unused file name of the given length. It continues until either the
1064 * name is available and the rename succeeds, or it runs out of names
1065 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1067 * The unlink is Unix-specific, as ANSI-standard remove has more
1068 * portability problems with C libraries making it "safe". rename
1069 * is ANSI-standard.
1071 * To force the directory data out, we try to open the directory and
1072 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
1073 * insist that it works: just fall back to a global sync in that case.
1074 * This is fairly significantly Unix-specific. Of course, on any
1075 * file system with synchronous metadata updates, this is unnecessary.
1077 static bool
1078 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1080 char *newname = xstrdup (oldname);
1081 char *base = last_component (newname);
1082 size_t len = base_len (base);
1083 char *dir = dir_name (newname);
1084 char *qdir = xstrdup (quotef (dir));
1085 bool first = true;
1086 bool ok = true;
1087 int dir_fd = -1;
1089 if (flags->remove_file == remove_wipesync)
1090 dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
1092 if (flags->verbose)
1093 error (0, 0, _("%s: removing"), qoldname);
1095 while ((flags->remove_file != remove_unlink) && len)
1097 memset (base, nameset[0], len);
1098 base[len] = 0;
1101 struct stat st;
1102 if (lstat (newname, &st) < 0)
1104 if (rename (oldname, newname) == 0)
1106 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
1107 ok = false;
1108 if (flags->verbose)
1111 * People seem to understand this better than talking
1112 * about renaming oldname. newname doesn't need
1113 * quoting because we picked it. oldname needs to
1114 * be quoted only the first time.
1116 char const *old = (first ? qoldname : oldname);
1117 error (0, 0, _("%s: renamed to %s"),
1118 old, newname);
1119 first = false;
1121 memcpy (oldname + (base - newname), base, len + 1);
1122 break;
1124 else
1126 /* The rename failed: give up on this length. */
1127 break;
1130 else
1132 /* newname exists, so increment BASE so we use another */
1135 while (incname (base, len));
1136 len--;
1138 if (unlink (oldname) != 0)
1140 error (0, errno, _("%s: failed to remove"), qoldname);
1141 ok = false;
1143 else if (flags->verbose)
1144 error (0, 0, _("%s: removed"), qoldname);
1145 if (0 <= dir_fd)
1147 if (dosync (dir_fd, qdir) != 0)
1148 ok = false;
1149 if (close (dir_fd) != 0)
1151 error (0, errno, _("%s: failed to close"), qdir);
1152 ok = false;
1155 free (newname);
1156 free (dir);
1157 free (qdir);
1158 return ok;
1162 * Finally, the function that actually takes a filename and grinds
1163 * it into hamburger.
1165 * FIXME
1166 * Detail to note: since we do not restore errno to EACCES after
1167 * a failed chmod, we end up printing the error code from the chmod.
1168 * This is actually the error that stopped us from proceeding, so
1169 * it's arguably the right one, and in practice it'll be either EACCES
1170 * again or EPERM, which both give similar error messages.
1171 * Does anyone disagree?
1173 static bool
1174 wipefile (char *name, char const *qname,
1175 struct randint_source *s, struct Options const *flags)
1177 bool ok;
1178 int fd;
1180 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1181 if (fd < 0
1182 && (errno == EACCES && flags->force)
1183 && chmod (name, S_IWUSR) == 0)
1184 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1185 if (fd < 0)
1187 error (0, errno, _("%s: failed to open for writing"), qname);
1188 return false;
1191 ok = do_wipefd (fd, qname, s, flags);
1192 if (close (fd) != 0)
1194 error (0, errno, _("%s: failed to close"), qname);
1195 ok = false;
1197 if (ok && flags->remove_file)
1198 ok = wipename (name, qname, flags);
1199 return ok;
1203 /* Buffers for random data. */
1204 static struct randint_source *randint_source;
1206 /* Just on general principles, wipe buffers containing information
1207 that may be related to the possibly-pseudorandom values used during
1208 shredding. */
1209 static void
1210 clear_random_data (void)
1212 randint_all_free (randint_source);
1217 main (int argc, char **argv)
1219 bool ok = true;
1220 struct Options flags = { 0, };
1221 char **file;
1222 int n_files;
1223 int c;
1224 int i;
1225 char const *random_source = NULL;
1227 initialize_main (&argc, &argv);
1228 set_program_name (argv[0]);
1229 setlocale (LC_ALL, "");
1230 bindtextdomain (PACKAGE, LOCALEDIR);
1231 textdomain (PACKAGE);
1233 atexit (close_stdout);
1235 flags.n_iterations = DEFAULT_PASSES;
1236 flags.size = -1;
1238 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1240 switch (c)
1242 case 'f':
1243 flags.force = true;
1244 break;
1246 case 'n':
1247 flags.n_iterations = xdectoumax (optarg, 0,
1248 MIN (ULONG_MAX,
1249 SIZE_MAX / sizeof (int)), "",
1250 _("invalid number of passes"), 0);
1251 break;
1253 case RANDOM_SOURCE_OPTION:
1254 if (random_source && !STREQ (random_source, optarg))
1255 error (EXIT_FAILURE, 0, _("multiple random sources specified"));
1256 random_source = optarg;
1257 break;
1259 case 'u':
1260 if (optarg == NULL)
1261 flags.remove_file = remove_wipesync;
1262 else
1263 flags.remove_file = XARGMATCH ("--remove", optarg,
1264 remove_args, remove_methods);
1265 break;
1267 case 's':
1268 flags.size = xnumtoumax (optarg, 0, 0, OFF_T_MAX, "cbBkKMGTPEZY0",
1269 _("invalid file size"), 0);
1270 break;
1272 case 'v':
1273 flags.verbose = true;
1274 break;
1276 case 'x':
1277 flags.exact = true;
1278 break;
1280 case 'z':
1281 flags.zero_fill = true;
1282 break;
1284 case_GETOPT_HELP_CHAR;
1286 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1288 default:
1289 usage (EXIT_FAILURE);
1293 file = argv + optind;
1294 n_files = argc - optind;
1296 if (n_files == 0)
1298 error (0, 0, _("missing file operand"));
1299 usage (EXIT_FAILURE);
1302 randint_source = randint_all_new (random_source, SIZE_MAX);
1303 if (! randint_source)
1304 error (EXIT_FAILURE, errno, "%s", quotef (random_source));
1305 atexit (clear_random_data);
1307 for (i = 0; i < n_files; i++)
1309 char *qname = xstrdup (quotef (file[i]));
1310 if (STREQ (file[i], "-"))
1312 ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1314 else
1316 /* Plain filename - Note that this overwrites *argv! */
1317 ok &= wipefile (file[i], qname, randint_source, &flags);
1319 free (qname);
1322 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
1325 * vim:sw=2:sts=2: