1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2005 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 2, or (at your option)
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, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307, USA.
20 Written by Colin Plumb. */
23 - use consistent non-capitalization in error messages
24 - add standard GNU copyleft comment
26 - Add -r/-R/--recursive
27 - Add -i/--interactive
30 - Add an unlink-all option to emulate rm.
34 * Do a more secure overwrite of given files or devices, to make it harder
35 * for even very expensive hardware probing to recover the data.
37 * Although this process is also known as "wiping", I prefer the longer
38 * name both because I think it is more evocative of what is happening and
39 * because a longer name conveys a more appropriate sense of deliberateness.
41 * For the theory behind this, see "Secure Deletion of Data from Magnetic
42 * and Solid-State Memory", on line at
43 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
45 * Just for the record, reversing one or two passes of disk overwrite
46 * is not terribly difficult with hardware help. Hook up a good-quality
47 * digitizing oscilloscope to the output of the head preamplifier and copy
48 * the high-res digitized data to a computer for some off-line analysis.
49 * Read the "current" data and average all the pulses together to get an
50 * "average" pulse on the disk. Subtract this average pulse from all of
51 * the actual pulses and you can clearly see the "echo" of the previous
54 * Real hard drives have to balance the cost of the media, the head,
55 * and the read circuitry. They use better-quality media than absolutely
56 * necessary to limit the cost of the read circuitry. By throwing that
57 * assumption out, and the assumption that you want the data processed
58 * as fast as the hard drive can spin, you can do better.
60 * If asked to wipe a file, this also unlinks it, renaming it to in a
61 * clever way to try to leave no trace of the original filename.
63 * The ISAAC code still bears some resemblance to the code written
64 * by Bob Jenkins, but he permits pretty unlimited use.
66 * This was inspired by a desire to improve on some code titled:
67 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
68 * but I've rewritten everything here so completely that no trace of
69 * the original remains.
72 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
74 * Jim Meyering, for his work merging this into the GNU fileutils while
75 * still letting me feel a sense of ownership and pride. Getting me to
76 * tolerate the GNU brace style was quite a feat of diplomacy.
77 * Paul Eggert, for lots of useful discussion and code. I disagree with
78 * an awful lot of his suggestions, but they're disagreements worth having.
80 * Things to think about:
81 * - Security: Is there any risk to the race
82 * between overwriting and unlinking a file? Will it do anything
83 * drastically bad if told to attack a named pipe or socket?
86 /* The official name of this program (e.g., no `g' prefix). */
87 #define PROGRAM_NAME "shred"
89 #define AUTHORS "Colin Plumb"
99 #include <sys/types.h>
105 #include "gethrxtime.h"
106 #include "getpagesize.h"
108 #include "inttostr.h"
109 #include "quotearg.h" /* For quotearg_colon */
110 #include "quote.h" /* For quotearg_colon */
111 #include "unistd-safer.h"
113 #define DEFAULT_PASSES 25 /* Default */
115 /* How many seconds to wait before checking whether to output another
116 verbose output line. */
117 #define VERBOSE_UPDATE 5
121 bool force; /* -f flag: chmod files if necessary */
122 size_t n_iterations; /* -n flag: Number of iterations */
123 off_t size; /* -s flag: size of file */
124 bool remove_file; /* -u flag: remove file after shredding */
125 bool verbose; /* -v flag: Print progress */
126 bool exact; /* -x flag: Do not round up file size */
127 bool zero_fill; /* -z flag: Add a final zero pass */
130 static struct option const long_opts[] =
132 {"exact", no_argument, NULL, 'x'},
133 {"force", no_argument, NULL, 'f'},
134 {"iterations", required_argument, NULL, 'n'},
135 {"size", required_argument, NULL, 's'},
136 {"remove", no_argument, NULL, 'u'},
137 {"verbose", no_argument, NULL, 'v'},
138 {"zero", no_argument, NULL, 'z'},
139 {GETOPT_HELP_OPTION_DECL},
140 {GETOPT_VERSION_OPTION_DECL},
144 /* Global variable for error printing purposes */
145 char const *program_name; /* Initialized before any possible use */
150 if (status != EXIT_SUCCESS)
151 fprintf (stderr, _("Try `%s --help' for more information.\n"),
155 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
157 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
158 for even very expensive hardware probing to recover the data.\n\
162 Mandatory arguments to long options are mandatory for short options too.\n\
165 -f, --force change permissions to allow writing if necessary\n\
166 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
167 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
170 -u, --remove truncate and remove file after overwriting\n\
171 -v, --verbose show progress\n\
172 -x, --exact do not round file sizes up to the next full block;\n\
173 this is the default for non-regular files\n\
174 -z, --zero add a final overwrite with zeros to hide shredding\n\
176 fputs (HELP_OPTION_DESCRIPTION, stdout);
177 fputs (VERSION_OPTION_DESCRIPTION, stdout);
180 If FILE is -, shred standard output.\n\
182 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
183 the files because it is common to operate on device files like /dev/hda,\n\
184 and those files usually should not be removed. When operating on regular\n\
185 files, most people use the --remove option.\n\
189 CAUTION: Note that shred relies on a very important assumption:\n\
190 that the file system overwrites data in place. This is the traditional\n\
191 way to do things, but many modern file system designs do not satisfy this\n\
192 assumption. The following are examples of file systems on which shred is\n\
197 * log-structured or journaled file systems, such as those supplied with\n\
198 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
200 * file systems that write redundant data and carry on even if some writes\n\
201 fail, such as RAID-based file systems\n\
203 * file systems that make snapshots, such as Network Appliance's NFS server\n\
207 * file systems that cache in temporary locations, such as NFS\n\
210 * compressed file systems\n\
212 In addition, file system backups and remote mirrors may contain copies\n\
213 of the file that cannot be removed, and that will allow a shredded file\n\
214 to be recovered later.\n\
216 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
222 * --------------------------------------------------------------------
223 * Bob Jenkins' cryptographic random number generator, ISAAC.
224 * Hacked by Colin Plumb.
226 * We need a source of random numbers for some of the overwrite data.
227 * Cryptographically secure is desirable, but it's not life-or-death
228 * so I can be a little bit experimental in the choice of RNGs here.
230 * This generator is based somewhat on RC4, but has analysis
231 * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
232 * pointing to it actually being better. I like it because it's nice
233 * and fast, and because the author did good work analyzing it.
234 * --------------------------------------------------------------------
237 /* Size of the state tables to use. (You may change ISAAC_LOG) */
239 #define ISAAC_WORDS (1 << ISAAC_LOG)
240 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (uint32_t))
242 /* RNG state variables */
245 uint32_t mm[ISAAC_WORDS]; /* Main state array */
246 uint32_t iv[8]; /* Seeding initial vector */
247 uint32_t a, b, c; /* Extra index variables */
250 /* This index operation is more efficient on many processors */
252 (* (uint32_t *) ((char *) (mm) \
253 + ((x) & (ISAAC_WORDS - 1) * sizeof (uint32_t))))
256 * The central step. This uses two temporaries, x and y. mm is the
257 * whole state array, while m is a pointer to the current word. off is
258 * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
259 * i.e. +/- ISAAC_WORDS/2.
261 #define isaac_step(mix, a, b, mm, m, off, r) \
263 a = ((a) ^ (mix)) + (m)[off], \
265 *(m) = y = ind (mm, x) + (a) + (b), \
266 *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
270 * Refill the entire R array, and update S.
273 isaac_refill (struct isaac_state *s, uint32_t r[/* ISAAC_WORDS */])
275 uint32_t a, b; /* Caches of a and b */
276 uint32_t x, y; /* Temps needed by isaac_step macro */
277 uint32_t *m = s->mm; /* Pointer into state array */
284 isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
285 isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
286 isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
287 isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
290 while ((m += 4) < s->mm + ISAAC_WORDS / 2);
293 isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
294 isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
295 isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
296 isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
299 while ((m += 4) < s->mm + ISAAC_WORDS);
305 * The basic seed-scrambling step for initialization, based on Bob
306 * Jenkins' 256-bit hash.
308 #define mix(a,b,c,d,e,f,g,h) \
309 ( a ^= b << 11, d += a, \
310 b += c, b ^= c >> 2, e += b, \
311 c += d, c ^= d << 8, f += c, \
312 d += e, d ^= e >> 16, g += d, \
313 e += f, e ^= f << 10, h += e, \
314 f += g, f ^= g >> 4, a += f, \
315 g += h, g ^= h << 8, b += g, \
316 h += a, h ^= a >> 9, c += h, \
319 /* The basic ISAAC initialization pass. */
321 isaac_mix (struct isaac_state *s, uint32_t const seed[/* ISAAC_WORDS */])
324 uint32_t a = s->iv[0];
325 uint32_t b = s->iv[1];
326 uint32_t c = s->iv[2];
327 uint32_t d = s->iv[3];
328 uint32_t e = s->iv[4];
329 uint32_t f = s->iv[5];
330 uint32_t g = s->iv[6];
331 uint32_t h = s->iv[7];
333 for (i = 0; i < ISAAC_WORDS; i += 8)
344 mix (a, b, c, d, e, f, g, h);
366 #if 0 /* Provided for reference only; not used in this code */
368 * Initialize the ISAAC RNG with the given seed material.
369 * Its size MUST be a multiple of ISAAC_BYTES, and may be
370 * stored in the s->mm array.
372 * This is a generalization of the original ISAAC initialization code
373 * to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
377 isaac_init (struct isaac_state *s, uint32_t const *seed, size_t seedsize)
379 static uint32_t const iv[8] =
381 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
382 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
386 /* The initialization of iv is a precomputed form of: */
387 for (i = 0; i < 7; i++)
388 iv[i] = 0x9e3779b9; /* the golden ratio */
389 for (i = 0; i < 4; ++i) /* scramble it */
390 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
392 s->a = s->b = s->c = 0;
394 for (i = 0; i < 8; i++)
399 /* First pass (as in reference ISAAC code) */
401 /* Second and subsequent passes (extension to ISAAC) */
402 while (seedsize -= ISAAC_BYTES)
405 for (i = 0; i < ISAAC_WORDS; i++)
407 isaac_mix (s, s->mm);
412 /* The no seed case (as in reference ISAAC code) */
413 for (i = 0; i < ISAAC_WORDS; i++)
418 isaac_mix (s, s->mm);
422 /* Start seeding an ISAAC structire */
424 isaac_seed_start (struct isaac_state *s)
426 static uint32_t const iv[8] =
428 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
429 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
434 /* The initialization of iv is a precomputed form of: */
435 for (i = 0; i < 7; i++)
436 iv[i] = 0x9e3779b9; /* the golden ratio */
437 for (i = 0; i < 4; ++i) /* scramble it */
438 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
440 for (i = 0; i < 8; i++)
443 /* Enable the following memset if you're worried about used-uninitialized
444 warnings involving code in isaac_refill from tools like valgrind.
445 Since this buffer is used to accumulate pseudo-random data, there's
446 no harm, and maybe even some benefit, in using it uninitialized. */
447 #if AVOID_USED_UNINITIALIZED_WARNINGS
448 memset (s->mm, 0, sizeof s->mm);
451 /* s->c gets used for a data pointer during the seeding phase */
452 s->a = s->b = s->c = 0;
455 /* Add a buffer of seed material */
457 isaac_seed_data (struct isaac_state *s, void const *buffer, size_t size)
459 unsigned char const *buf = buffer;
464 avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
466 /* Do any full buffers that are necessary */
469 p = (unsigned char *) s->mm + s->c;
470 for (i = 0; i < avail; i++)
474 isaac_mix (s, s->mm);
476 avail = sizeof s->mm;
479 /* And the final partial block */
480 p = (unsigned char *) s->mm + s->c;
481 for (i = 0; i < size; i++)
487 /* End of seeding phase; get everything ready to produce output. */
489 isaac_seed_finish (struct isaac_state *s)
491 isaac_mix (s, s->mm);
492 isaac_mix (s, s->mm);
493 /* Now reinitialize c to start things off right */
496 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
499 * Get seed material. 16 bytes (128 bits) is plenty, but if we have
500 * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
503 isaac_seed (struct isaac_state *s)
505 isaac_seed_start (s);
507 { pid_t t = getpid (); ISAAC_SEED (s, t); }
508 { pid_t t = getppid (); ISAAC_SEED (s, t); }
509 { uid_t t = getuid (); ISAAC_SEED (s, t); }
510 { gid_t t = getgid (); ISAAC_SEED (s, t); }
513 xtime_t t = gethrxtime ();
519 int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
524 isaac_seed_data (s, buf, 32);
528 fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
531 /* /dev/random is more precious, so use less */
534 isaac_seed_data (s, buf, 16);
539 isaac_seed_finish (s);
542 /* Single-word RNG built on top of ISAAC */
545 uint32_t r[ISAAC_WORDS];
546 unsigned int numleft;
547 struct isaac_state *s;
551 irand_init (struct irand_state *r, struct isaac_state *s)
558 * We take from the end of the block deliberately, so if we need
559 * only a small number of values, we choose the final ones which are
560 * marginally better mixed than the initial ones.
563 irand32 (struct irand_state *r)
567 isaac_refill (r->s, r->r);
568 r->numleft = ISAAC_WORDS;
570 return r->r[--r->numleft];
574 * Return a uniformly distributed random number between 0 and n,
575 * inclusive. Thus, the result is modulo n+1.
577 * Theory of operation: as x steps through every possible 32-bit number,
578 * x % n takes each value at least 2^32 / n times (rounded down), but
579 * the values less than 2^32 % n are taken one additional time. Thus,
580 * x % n is not perfectly uniform. To fix this, the values of x less
581 * than 2^32 % n are disallowed, and if the RNG produces one, we ask
585 irand_mod (struct irand_state *r, uint32_t n)
593 lim = -n % n; /* == (2**32-n) % n == 2**32 % n */
603 * Fill a buffer with a fixed pattern.
605 * The buffer must be at least 3 bytes long, even if
606 * size is less. Larger sizes are filled exactly.
609 fillpattern (int type, unsigned char *r, size_t size)
612 unsigned int bits = type & 0xfff;
615 r[0] = (bits >> 4) & 255;
616 r[1] = (bits >> 8) & 255;
618 for (i = 3; i < size / 2; i *= 2)
619 memcpy ((char *) r + i, (char *) r, i);
621 memcpy ((char *) r + i, (char *) r, size - i);
623 /* Invert the first bit of every 512-byte sector. */
625 for (i = 0; i < size; i += 512)
630 * Fill a buffer, R (of size SIZE_MAX), with random data.
631 * SIZE is rounded UP to a multiple of ISAAC_BYTES.
634 fillrand (struct isaac_state *s, uint32_t *r, size_t size_max, size_t size)
636 size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
637 assert (size <= size_max);
647 * Generate a 6-character (+ nul) pass name string
648 * FIXME: allow translation of "random".
650 #define PASS_NAME_SIZE 7
652 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
655 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
657 memcpy (name, "random", PASS_NAME_SIZE);
660 /* Request that all data for FD be transferred to the corresponding
661 storage device. QNAME is the file name (quoted for colons).
662 Report any errors found. Return 0 on success, -1
663 (setting errno) on failure. It is not an error if fdatasync and/or
664 fsync is not supported for this file, or if the file is not a
665 writable file descriptor. */
667 dosync (int fd, char const *qname)
672 if (fdatasync (fd) == 0)
675 if (err != EINVAL && err != EBADF)
677 error (0, err, _("%s: fdatasync failed"), qname);
686 if (err != EINVAL && err != EBADF)
688 error (0, err, _("%s: fsync failed"), qname);
697 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
698 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
700 direct_mode (int fd, bool enable)
704 int fd_flags = fcntl (fd, F_GETFL);
707 int new_flags = (enable
708 ? (fd_flags | O_DIRECT)
709 : (fd_flags & ~O_DIRECT));
710 if (new_flags != fd_flags)
711 fcntl (fd, F_SETFL, new_flags);
715 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
716 /* This is Solaris-specific. See the following for details:
717 http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view */
718 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
723 * Do pass number k of n, writing "size" bytes of the given pattern "type"
724 * to the file descriptor fd. Qname, k and n are passed in only for verbose
725 * progress message purposes. If n == 0, no progress messages are printed.
727 * If *sizep == -1, the size is unknown, and it will be filled in as soon
730 * Return 1 on write error, -1 on other error, 0 on success.
733 dopass (int fd, char const *qname, off_t *sizep, int type,
734 struct isaac_state *s, unsigned long int k, unsigned long int n)
737 off_t offset; /* Current file posiiton */
738 time_t thresh IF_LINT (= 0); /* Time to maybe print next status update */
739 time_t now = 0; /* Current time */
740 size_t lim; /* Amount of data to try writing */
741 size_t soff; /* Offset into buffer for next write */
742 ssize_t ssize; /* Return value from write */
743 uint32_t *r; /* Fill pattern. */
744 size_t rsize = 3 * MAX (ISAAC_WORDS, 1024) * sizeof *r; /* Fill size. */
745 size_t ralign = lcm (getpagesize (), sizeof *r); /* Fill alignment. */
746 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
747 bool write_error = false;
748 bool first_write = true;
750 /* Printable previous offset into the file */
751 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
752 char const *previous_human_offset IF_LINT (= 0);
754 if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
756 error (0, errno, _("%s: cannot rewind"), qname);
760 r = alloca (rsize + ralign - 1);
761 r = ptr_align (r, ralign);
763 /* Constant fill patterns need only be set up once. */
767 if ((off_t) lim > size && size != -1)
771 fillpattern (type, (unsigned char *) r, lim);
772 passname ((unsigned char *) r, pass_string);
776 passname (0, pass_string);
779 /* Set position if first status update */
782 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
783 thresh = time (NULL) + VERBOSE_UPDATE;
784 previous_human_offset = "";
790 /* How much to write this time? */
792 if ((off_t) lim > size - offset && size != -1)
796 lim = (size_t) (size - offset);
801 fillrand (s, r, rsize, lim);
802 /* Loop to retry partial writes. */
803 for (soff = 0; soff < lim; soff += ssize, first_write = false)
805 ssize = write (fd, (char *) r + soff, lim - soff);
808 if ((ssize == 0 || errno == ENOSPC)
811 /* Ah, we have found the end of the file */
812 *sizep = size = offset + soff;
818 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
820 /* If the first write of the first pass for a given file
821 has just failed with EINVAL, turn off direct mode I/O
822 and try again. This works around a bug in linux-2.4
823 whereby opening with O_DIRECT would succeed for some
824 file system types (e.g., ext3), but any attempt to
825 access a file through the resulting descriptor would
827 if (k == 1 && first_write && errno == EINVAL)
829 direct_mode (fd, false);
833 error (0, errnum, _("%s: error writing at offset %s"),
834 qname, umaxtostr ((uintmax_t) offset + soff, buf));
836 * I sometimes use shred on bad media, before throwing it
837 * out. Thus, I don't want it to give up on bad blocks.
838 * This code assumes 512-byte blocks and tries to skip
839 * over them. It works because lim is always a multiple
840 * of 512, except at the end.
842 if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
845 if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
848 /* Arrange to skip this block. */
853 error (0, errno, _("%s: lseek failed"), qname);
860 /* Okay, we have written "soff" bytes. */
862 if (offset + soff < offset)
864 error (0, 0, _("%s: file too large"), qname);
870 /* Time to print progress? */
872 && ((offset == size && *previous_human_offset)
873 || thresh <= (now = time (NULL))))
875 char offset_buf[LONGEST_HUMAN_READABLE + 1];
876 char size_buf[LONGEST_HUMAN_READABLE + 1];
877 int human_progress_opts = (human_autoscale | human_SI
878 | human_base_1024 | human_B);
879 char const *human_offset
880 = human_readable (offset, offset_buf,
881 human_floor | human_progress_opts, 1, 1);
884 || !STREQ (previous_human_offset, human_offset))
887 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
888 qname, k, n, pass_string, human_offset);
891 uintmax_t off = offset;
892 int percent = (size == 0
894 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
896 : off / (size / 100)));
897 char const *human_size
898 = human_readable (size, size_buf,
899 human_ceiling | human_progress_opts,
902 human_offset = human_size;
903 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
904 qname, k, n, pass_string, human_offset, human_size,
908 strcpy (previous_offset_buf, human_offset);
909 previous_human_offset = previous_offset_buf;
910 thresh = now + VERBOSE_UPDATE;
913 * Force periodic syncs to keep displayed progress accurate
914 * FIXME: Should these be present even if -v is not enabled,
915 * to keep the buffer cache from filling with dirty pages?
916 * It's a common problem with programs that do lots of writes,
919 if (dosync (fd, qname) != 0)
929 /* Force what we just wrote to hit the media. */
930 if (dosync (fd, qname) != 0)
941 * The passes start and end with a random pass, and the passes in between
942 * are done in random order. The idea is to deprive someone trying to
943 * reverse the process of knowledge of the overwrite patterns, so they
944 * have the additional step of figuring out what was done to the disk
945 * before they can try to reverse or cancel it.
947 * First, all possible 1-bit patterns. There are two of them.
948 * Then, all possible 2-bit patterns. There are four, but the two
949 * which are also 1-bit patterns can be omitted.
950 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
951 * Then, all possible 4-bit patterns. 16-4 = 12.
953 * The basic passes are:
954 * 1-bit: 0x000, 0xFFF
955 * 2-bit: 0x555, 0xAAA
956 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
957 * 100100100100 110110110110
959 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
960 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
961 * Adding three random passes at the beginning, middle and end
962 * produces the default 25-pass structure.
964 * The next extension would be to 5-bit and 6-bit patterns.
965 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
966 * 6-bit patterns, so they would increase the time required
967 * significantly. 4-bit patterns are enough for most purposes.
969 * The main gotcha is that this would require a trickier encoding,
970 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
971 * lcm(2,3,4,5) = 60 bits is not.
973 * One extension that is included is to complement the first bit in each
974 * 512-byte block, to alter the phase of the encoded data in the more
975 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
976 * are considered part of the 3-bit ones and the 2-bit patterns are
977 * considered part of the 4-bit patterns.
980 * How does the generalization to variable numbers of passes work?
983 * Have an ordered list of groups of passes. Each group is a set.
984 * Take as many groups as will fit, plus a random subset of the
985 * last partial group, and place them into the passes list.
986 * Then shuffle the passes list into random order and use that.
988 * One extra detail: if we can't include a large enough fraction of the
989 * last group to be interesting, then just substitute random passes.
991 * If you want more passes than the entire list of groups can
992 * provide, just start repeating from the beginning of the list.
997 -2, /* 2 random passes */
998 2, 0x000, 0xFFF, /* 1-bit */
999 2, 0x555, 0xAAA, /* 2-bit */
1000 -1, /* 1 random pass */
1001 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
1002 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1003 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
1004 -1, /* 1 random pass */
1005 /* The following patterns have the frst bit per block flipped */
1006 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1007 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1008 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1009 -1, /* 1 random pass */
1014 * Generate a random wiping pass pattern with num passes.
1015 * This is a two-stage process. First, the passes to include
1016 * are chosen, and then they are shuffled into the desired
1020 genpattern (int *dest, size_t num, struct isaac_state *s)
1022 struct irand_state r;
1027 size_t accum, top, swap;
1035 /* Stage 1: choose the passes to use */
1038 d = dest; /* Destination for generated pass list */
1039 n = num; /* Passes remaining to fill */
1043 k = *p++; /* Block descriptor word */
1045 { /* Loop back to the beginning */
1049 { /* -k random passes */
1051 if ((size_t) k >= n)
1060 else if ((size_t) k <= n)
1061 { /* Full block of patterns */
1062 memcpy (d, p, k * sizeof (int));
1067 else if (n < 2 || 3 * n < (size_t) k)
1068 { /* Finish with random */
1073 { /* Pad out with k of the n available */
1076 if (n == (size_t) k-- || irand_mod (&r, k) < n)
1087 top = num - randpasses; /* Top of initialized data */
1088 /* assert (d == dest+top); */
1091 * We now have fixed patterns in the dest buffer up to
1092 * "top", and we need to scramble them, with "randpasses"
1093 * random passes evenly spaced among them.
1095 * We want one at the beginning, one at the end, and
1096 * evenly spaced in between. To do this, we basically
1097 * use Bresenham's line draw (a.k.a DDA) algorithm
1098 * to draw a line with slope (randpasses-1)/(num-1).
1099 * (We use a positive accumulator and count down to
1102 * So for each desired output value, we do the following:
1103 * - If it should be a random pass, copy the pass type
1104 * to top++, out of the way of the other passes, and
1105 * set the current pass to -1 (random).
1106 * - If it should be a normal pattern pass, choose an
1107 * entry at random between here and top-1 (inclusive)
1108 * and swap the current entry with that one.
1110 randpasses--; /* To speed up later math */
1111 accum = randpasses; /* Bresenham DDA accumulator */
1112 for (n = 0; n < num; n++)
1114 if (accum <= randpasses)
1117 dest[top++] = dest[n];
1122 swap = n + irand_mod (&r, top - n - 1);
1124 dest[n] = dest[swap];
1127 accum -= randpasses;
1129 /* assert (top == num); */
1131 memset (&r, 0, sizeof r); /* Wipe this on general principles */
1135 * The core routine to actually do the work. This overwrites the first
1136 * size bytes of the given fd. Return true if successful.
1139 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1140 struct Options const *flags)
1144 off_t size; /* Size to write, size to read */
1145 unsigned long int n; /* Number of passes for printing purposes */
1149 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
1151 n = flags->n_iterations + flags->zero_fill;
1153 if (fstat (fd, &st))
1155 error (0, errno, _("%s: fstat failed"), qname);
1159 /* If we know that we can't possibly shred the file, give up now.
1160 Otherwise, we may go into a infinite loop writing data before we
1161 find that we can't rewind the device. */
1162 if ((S_ISCHR (st.st_mode) && isatty (fd))
1163 || S_ISFIFO (st.st_mode)
1164 || S_ISSOCK (st.st_mode))
1166 error (0, 0, _("%s: invalid file type"), qname);
1170 direct_mode (fd, true);
1172 /* Allocate pass array */
1173 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
1178 /* Accept a length of zero only if it's a regular file.
1179 For any other type of file, try to get the size another way. */
1180 if (S_ISREG (st.st_mode))
1185 error (0, 0, _("%s: file has negative size"), qname);
1191 size = lseek (fd, (off_t) 0, SEEK_END);
1194 /* We are unable to determine the length, up front.
1195 Let dopass do that as part of its first iteration. */
1200 /* Allow `rounding up' only for regular files. */
1201 if (0 <= size && !(flags->exact) && S_ISREG (st.st_mode))
1203 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1205 /* If in rounding up, we've just overflowed, use the maximum. */
1207 size = TYPE_MAXIMUM (off_t);
1211 /* Schedule the passes in random order. */
1212 genpattern (passarray, flags->n_iterations, s);
1215 for (i = 0; i < flags->n_iterations; i++)
1217 int err = dopass (fd, qname, &size, passarray[i], s, i + 1, n);
1222 memset (passarray, 0, flags->n_iterations * sizeof (int));
1230 memset (passarray, 0, flags->n_iterations * sizeof (int));
1233 if (flags->zero_fill)
1235 int err = dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n);
1244 /* Okay, now deallocate the data. The effect of ftruncate on
1245 non-regular files is unspecified, so don't worry about any
1246 errors reported for them. */
1247 if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1248 && S_ISREG (st.st_mode))
1250 error (0, errno, _("%s: error truncating"), qname);
1257 /* A wrapper with a little more checking for fds on the command line */
1259 wipefd (int fd, char const *qname, struct isaac_state *s,
1260 struct Options const *flags)
1262 int fd_flags = fcntl (fd, F_GETFL);
1266 error (0, errno, _("%s: fcntl failed"), qname);
1269 if (fd_flags & O_APPEND)
1271 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1274 return do_wipefd (fd, qname, s, flags);
1277 /* --- Name-wiping code --- */
1279 /* Characters allowed in a file name - a safe universal set. */
1280 static char const nameset[] =
1281 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
1283 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
1284 number with the digits taken from nameset. Return true if
1285 successful if not (because NAME already has the greatest possible
1289 incname (char *name, size_t len)
1293 char const *p = strchr (nameset, name[len]);
1295 /* If this character has a successor, use it. */
1302 /* Otherwise, set this digit to 0 and increment the prefix. */
1303 name[len] = nameset[0];
1310 * Repeatedly rename a file with shorter and shorter names,
1311 * to obliterate all traces of the file name on any system that
1312 * adds a trailing delimiter to on-disk file names and reuses
1313 * the same directory slot. Finally, unlink it.
1314 * The passed-in filename is modified in place to the new filename.
1315 * (Which is unlinked if this function succeeds, but is still present if
1316 * it fails for some reason.)
1318 * The main loop is written carefully to not get stuck if all possible
1319 * names of a given length are occupied. It counts down the length from
1320 * the original to 0. While the length is non-zero, it tries to find an
1321 * unused file name of the given length. It continues until either the
1322 * name is available and the rename succeeds, or it runs out of names
1323 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1325 * The unlink is Unix-specific, as ANSI-standard remove has more
1326 * portability problems with C libraries making it "safe". rename
1329 * To force the directory data out, we try to open the directory and
1330 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
1331 * insist that it works: just fall back to a global sync in that case.
1332 * This is fairly significantly Unix-specific. Of course, on any
1333 * file system with synchronous metadata updates, this is unnecessary.
1336 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1338 char *newname = xstrdup (oldname);
1339 char *base = base_name (newname);
1340 size_t len = base_len (base);
1341 char *dir = dir_name (newname);
1342 char *qdir = xstrdup (quotearg_colon (dir));
1346 int dir_fd = open (dir, O_WRONLY | O_NOCTTY);
1348 dir_fd = open (dir, O_RDONLY | O_NOCTTY);
1349 dir_fd = fd_safer (dir_fd);
1352 error (0, 0, _("%s: removing"), qoldname);
1356 memset (base, nameset[0], len);
1361 if (lstat (newname, &st) < 0)
1363 if (rename (oldname, newname) == 0)
1365 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
1370 * People seem to understand this better than talking
1371 * about renaming oldname. newname doesn't need
1372 * quoting because we picked it. oldname needs to
1373 * be quoted only the first time.
1375 char const *old = (first ? qoldname : oldname);
1376 error (0, 0, _("%s: renamed to %s"), old, newname);
1379 memcpy (oldname + (base - newname), base, len + 1);
1384 /* The rename failed: give up on this length. */
1390 /* newname exists, so increment BASE so we use another */
1393 while (incname (base, len));
1396 if (unlink (oldname) != 0)
1398 error (0, errno, _("%s: failed to remove"), qoldname);
1401 else if (flags->verbose)
1402 error (0, 0, _("%s: removed"), qoldname);
1405 if (dosync (dir_fd, qdir) != 0)
1407 if (close (dir_fd) != 0)
1409 error (0, errno, _("%s: failed to close"), qdir);
1420 * Finally, the function that actually takes a filename and grinds
1421 * it into hamburger.
1424 * Detail to note: since we do not restore errno to EACCES after
1425 * a failed chmod, we end up printing the error code from the chmod.
1426 * This is actually the error that stopped us from proceeding, so
1427 * it's arguably the right one, and in practice it'll be either EACCES
1428 * again or EPERM, which both give similar error messages.
1429 * Does anyone disagree?
1432 wipefile (char *name, char const *qname,
1433 struct isaac_state *s, struct Options const *flags)
1438 fd = open (name, O_WRONLY | O_NOCTTY);
1440 && (errno == EACCES && flags->force)
1441 && chmod (name, S_IWUSR) == 0)
1442 fd = open (name, O_WRONLY | O_NOCTTY);
1446 error (0, errno, _("%s: failed to open for writing"), qname);
1450 ok = do_wipefd (fd, qname, s, flags);
1451 if (close (fd) != 0)
1453 error (0, errno, _("%s: failed to close"), qname);
1456 if (ok && flags->remove_file)
1457 ok = wipename (name, qname, flags);
1462 main (int argc, char **argv)
1464 struct isaac_state s;
1466 struct Options flags;
1472 initialize_main (&argc, &argv);
1473 program_name = argv[0];
1474 setlocale (LC_ALL, "");
1475 bindtextdomain (PACKAGE, LOCALEDIR);
1476 textdomain (PACKAGE);
1478 atexit (close_stdout);
1482 memset (&flags, 0, sizeof flags);
1484 flags.n_iterations = DEFAULT_PASSES;
1487 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1498 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1499 || (uint32_t) tmp != tmp
1500 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1502 error (EXIT_FAILURE, 0, _("%s: invalid number of passes"),
1503 quotearg_colon (optarg));
1505 flags.n_iterations = (size_t) tmp;
1510 flags.remove_file = true;
1516 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0")
1519 error (EXIT_FAILURE, 0, _("%s: invalid file size"),
1520 quotearg_colon (optarg));
1527 flags.verbose = true;
1535 flags.zero_fill = true;
1538 case_GETOPT_HELP_CHAR;
1540 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1543 usage (EXIT_FAILURE);
1547 file = argv + optind;
1548 n_files = argc - optind;
1552 error (0, 0, _("missing file operand"));
1553 usage (EXIT_FAILURE);
1556 for (i = 0; i < n_files; i++)
1558 char *qname = xstrdup (quotearg_colon (file[i]));
1559 if (STREQ (file[i], "-"))
1561 ok &= wipefd (STDOUT_FILENO, qname, &s, &flags);
1565 /* Plain filename - Note that this overwrites *argv! */
1566 ok &= wipefile (file[i], qname, &s, &flags);
1571 /* Just on general principles, wipe s. */
1572 memset (&s, 0, sizeof s);
1574 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);