2 - use consistent non-capitalization in error messages
3 - add standard GNU copyleft comment
5 - Add -r/-R/--recursive
9 - Deal with the amazing variety of gettimeofday() implementation bugs.
10 (Some systems use a one-arg form; still others insist that the timezone
11 either be NULL or be non-NULL. Whee.)
12 - Add an unlink-all option to emulate rm.
16 * shred.c - by Colin Plumb.
18 * Do a securer overwrite of given files or devices, to make it harder
19 * for even very expensive hardware probing to recover the data.
21 * Although this process is also known as "wiping", I prefer the longer
22 * name both because I think it is more evocative of what is happening and
23 * because a longer name conveys a more appropriate sense of deliberateness.
25 * For the theory behind this, see "Secure Deletion of Data from Magnetic
26 * and Solid-State Memory", on line at
27 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
29 * Just for the record, reversing one or two passes of disk overwrite
30 * is not terribly difficult with hardware help. Hook up a good-quality
31 * digitizing oscilloscope to the output of the head preamplifier and copy
32 * the high-res digitized data to a computer for some off-line analysis.
33 * Read the "current" data and average all the pulses together to get an
34 * "average" pulse on the disk. Subtract this average pulse from all of
35 * the actual pulses and you can clearly see the "echo" of the previous
38 * Real hard drives have to balance the cost of the media, the head,
39 * and the read circuitry. They use better-quality media than absolutely
40 * necessary to limit the cost of the read circuitry. By throwing that
41 * assumption out, and the assumption that you want the data processed
42 * as fast as the hard drive can spin, you can do better.
44 * If asked to wipe a file, this also unlinks it, renaming it to in a
45 * clever way to try to leave no trace of the original filename.
47 * Copyright 1997, 1998, 1999 Colin Plumb <colin@nyx.net>. This program
48 * may be freely distributed under the terms of the GNU GPL, the BSD license,
49 * or Larry Wall's "Artistic License" Even if you use the BSD license,
50 * which does not require it, I'd really like to get improvements back.
52 * The ISAAC code still bears some resemblance to the code written
53 * by Bob Jenkins, but he permits pretty unlimited use.
55 * This was inspired by a desire to improve on some code titled:
56 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
57 * but I've rewritten everything here so completely that no trace of
58 * the original remains.
61 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
63 * Jim Meyering, for his work merging this into the GNU fileutils while
64 * still letting me feel a sense of ownership and pride. Getting me to
65 * tolerate the GNU brace style was quite a feat of diplomacy.
66 * Paul Eggert, for lots of useful discussion and code. I disagree with
67 * an awful lot of his suggestions, but they're disagreements worth having.
69 * Things to think about:
70 * - Security: Is there any risk to the race
71 * between overwriting and unlinking a file? Will it do anything
72 * drastically bad if told to attack a named pipe or socket?
75 /* The official name of this program (e.g., no `g' prefix). */
76 #define PROGRAM_NAME "shred"
78 #define AUTHORS "Colin Plumb"
89 #include <sys/types.h>
92 /* Default fileutils build */
95 # include "closeout.h"
98 # include "quotearg.h" /* For quotearg_colon */
99 # include "quote.h" /* For quotearg_colon */
102 char *xstrdup PARAMS ((char const *));
104 #else /* !HAVE_CONFIG_H */
106 * Standalone build - this file compiles by itself without autoconf and
107 * the like. No i18n, and I still have to write a stub for getopt_long,
108 * but it's a lot less intertwingled than the usual GNU utilities.
111 # include <ctype.h> /* For isprint */
112 # include <string.h> /* For memcpy, strerror */
113 # include <limits.h> /* For ULONG_MAX etc. */
114 # include <stdlib.h> /* For strtoul, EXIT_FAILURE */
116 # include <fcntl.h> /* For O_RDONLY etc. */
117 # include <unistd.h> /* For getpid, etc. */
118 # include <sys/time.h> /* For struct timeval */
119 # include <sys/stat.h> /* For struct stat */
121 # define PACKAGE "standalone"
122 # define VERSION "2.0" /* Kind of arbitrary... */
124 # if __GNUC__ < 2 || __GNUC__ == 2 && __GNUC_MINOR__ < 5 || __STRICT_ANSI__
125 # define attribute(x)
127 # define attribute __attribute__
128 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
129 /* The __-protected forms were introduced in GCC 2.6.4 */
130 # define __format__ format
131 # define __printf__ printf
135 /* Reasonable default assumptions for time-getting */
136 # ifndef HAVE_GETTIMEOFDAY
137 # define HAVE_GETTIMEOFDAY 1 /* Most systems have it these days */
140 # ifdef CLOCK_REALTIME
141 # ifndef HAVE_CLOCK_GETTIME
142 # define HAVE_CLOCK_GETTIME 1
146 # ifndef STDOUT_FILENO
147 # define STDOUT_FILENO 1
150 # define RETSIGTYPE int
154 # define S_IWUSR S_IWRITE
156 # define S_IWUSR 0200
160 /* POSIX doesn't require st_blksize, and 65536 is a reasonable
161 upper bound for existing filesystem practice. */
162 # define ST_BLKSIZE(Stat) 65536
164 # define uintmax_t unsigned long
166 /* Variant human-readable function that ignores last two args */
167 # define human_readable(v, b, f, t) (sprintf (b, "%lu", (unsigned long) v), b)
168 # define LONGEST_HUMAN_READABLE (sizeof (uintmax_t) * CHAR_BIT / 3)
170 /* Variant convert-to-uintmax_t function that accepts metric suffixes */
173 LONGINT_OK, LONGINT_INVALID, LONGINT_INVALID_SUFFIX_CHAR, LONGINT_OVERFLOW
176 xstrtoumax (char const *ptr, char const **end, int base, uintmax_t *res,
177 char const *valid_suffixes)
181 static char const metric_suffixes[] = "kMGTPEZY";
187 *res = n = strtoul (ptr, &end_ptr, base);
191 return LONGINT_OVERFLOW;
193 return LONGINT_INVALID;
197 /* Now deal with metric-style suffixes */
198 if (valid_suffixes && !strchr (valid_suffixes, c))
199 return LONGINT_INVALID_SUFFIX_CHAR;
205 if (n > ULONG_MAX/512)
206 return LONGINT_OVERFLOW;
211 if (n > ULONG_MAX/102412)
212 return LONGINT_OVERFLOW;
227 p = strchr (metric_suffixes, c);
229 return LONGINT_INVALID_SUFFIX_CHAR;
231 * If valid_suffixes contains '0', then xD (decimal) and xB (binary)
232 * are allowed as "supersuffixes". Binary is the default.
234 if (strchr (valid_suffixes, '0'))
236 if (end_ptr[1] == 'B')
238 else if (end_ptr[1] == 'D')
244 /* Now do the scaling */
248 if (n > ULONG_MAX/1000)
249 return LONGINT_OVERFLOW;
251 } while (--p > metric_suffixes);
254 if (n > ULONG_MAX/1024)
255 return LONGINT_OVERFLOW;
257 } while (--p > metric_suffixes);
262 *end = end_ptr+1; /* Extra suffix is allowed if it's expected */
264 return LONGINT_INVALID_SUFFIX_CHAR;
269 /* Dummy i18n stubs */
272 # define setlocale(x,y) (void) 0
273 # define bindtextdomain(x,y) (void) 0
274 # define textdomain(x) (void) 0
277 * Print a message with `fprintf (stderr, FORMAT, ...)';
278 * if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
279 * If STATUS is nonzero, terminate the program with `exit (STATUS)'.
281 static void error (int status, int errnum, const char *format, ...)
282 attribute ((__format__ (__printf__, 3, 4)));
284 extern char const *program_name;
286 error (int status, int errnum, const char *format, ...)
292 fputs (program_name, stderr);
293 fputs (": ", stderr);
295 va_start (ap, format);
296 vfprintf (stderr, format, ap);
300 fputs (": ", stderr);
301 fputs (strerror (errnum), stderr);
310 * GNU programs actually check for failure closing standard output.
311 * This seems unnecessary, until your shell script starts hitting
312 * ENOSPC and doing bizarre things with zero-length files.
318 error (EXIT_FAILURE, 0, _("write error"));
319 if (fclose (stdout) != 0)
320 error (EXIT_FAILURE, errno, _("write error"));
324 * Quote the argument (including colon characters) into the buffer.
325 * Return the buffer size used (including trailing null byte.)
326 * If this is larger than the bufsize, it is an estimate of the space
330 quotearg_colon_buf (char const *arg, char *buf, size_t bufsize)
332 /* Some systems don't have \a or \e, so this is ASCII-dependent */
333 static char const escaped[] = "\7\b\33\f\n\r\t\v";
334 static char const escapes[] = "abefnrtv";
339 while ((c = (unsigned char) *arg++) != 0)
343 if (strchr ("\\:", c)) /* Anything else we should quote? */
344 if (pos++ < bufsize) *buf++ = '\\';
348 if (pos++ < bufsize) *buf++ = '\\';
349 p = strchr (escaped, c); /* c is never 0, so this is okay */
352 c = escapes[p-escaped];
356 if ('0' <= *arg && *arg <= '9')
357 c += 256; /* Force 3-digit form if followed by a digit */
359 if (pos++ < bufsize) *buf++ = "0123"[c>>6 & 3];
361 if (pos++ < bufsize) *buf++ = "01234567"[c>>3 & 7];
362 c = "01234567"[c & 7];
365 if (pos++ < bufsize) *buf++ = c;
367 if (pos++ < bufsize) *buf++ = 0;
371 /* Quote metacharacters in a filename */
373 quotearg_colon (char const *arg)
375 static char *buf = 0;
379 while ((newsize = quotearg_colon_buf (arg, buf, bufsize)) > bufsize)
381 buf = realloc (buf, newsize);
383 error (EXIT_FAILURE, 0, _("memory exhausted"));
392 void *p = malloc (n);
394 error (EXIT_FAILURE, 0, _("memory exhausted"));
399 xstrdup (char const *string)
401 return strcpy (xmalloc (strlen (string) + 1), string);
404 #endif /* ! HAVE_CONFIG_H */
407 # define O_NOCTTY 0 /* This is a very optional frill */
410 /* Some systems don't support some file types. */
412 # define S_ISFIFO(mode) 0
415 # define S_ISLNK(mode) 0
418 # define S_ISSOCK(mode) 0
421 #define DEFAULT_PASSES 25 /* Default */
423 /* How often to update wiping display */
424 #define VERBOSE_UPDATE 150*1024
426 /* If positive, the units to use when printing sizes;
427 if negative, the human-readable base. */
428 #define OUTPUT_BLOCK_SIZE (-1024)
432 int force; /* -f flag: chmod files if necessary */
433 size_t n_iterations; /* -n flag: Number of iterations */
434 off_t size; /* -s flag: size of file */
435 int remove_file; /* -u flag: remove file after shredding */
436 int verbose; /* -v flag: Print progress */
437 int exact; /* -x flag: Do not round up file size */
438 int zero_fill; /* -z flag: Add a final zero pass */
441 static struct option const long_opts[] =
443 {"exact", no_argument, NULL, 'x'},
444 {"force", no_argument, NULL, 'f'},
445 {"iterations", required_argument, NULL, 'n'},
446 {"size", required_argument, NULL, 's'},
447 {"remove", no_argument, NULL, 'u'},
448 {"verbose", no_argument, NULL, 'v'},
449 {"zero", required_argument, NULL, 'z'},
450 {GETOPT_HELP_OPTION_DECL},
451 {GETOPT_VERSION_OPTION_DECL},
455 /* Global variable for error printing purposes */
456 char const *program_name; /* Initialized before any possible use */
462 fprintf (stderr, _("Try `%s --help' for more information.\n"),
466 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
468 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
469 for even very expensive hardware probing to recover the data.\n\
473 Mandatory arguments to long options are mandatory for short options too.\n\
476 -f, --force change permissions to allow writing if necessary\n\
477 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
478 -s, --size=N shred this many bytes (suffixes like k, M, G accepted)\n\
481 -u, --remove truncate and remove file after overwriting\n\
482 -v, --verbose show progress\n\
483 -x, --exact do not round file sizes up to the next full block\n\
484 -z, --zero add a final overwrite with zeros to hide shredding\n\
485 - shred standard output\n\
488 --help display this help and exit\n\
489 --version output version information and exit\n\
493 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
494 the files because it is common to operate on device files like /dev/hda,\n\
495 and those files usually should not be removed. When operating on regular\n\
496 files, most people use the --remove option.\n\
500 CAUTION: Note that shred relies on a very important assumption:\n\
501 that the filesystem overwrites data in place. This is the traditional\n\
502 way to do things, but many modern filesystem designs do not satisfy this\n\
503 assumption. The following are examples of filesystems on which shred is\n\
508 * log-structured or journaled filesystems, such as those supplied with\n\
509 AIX and Solaris (and JFS, ReiserFS, XFS, etc.)\n\
511 * filesystems that write redundant data and carry on even if some writes\n\
512 fail, such as RAID-based filesystems\n\
514 * filesystems that make snapshots, such as Network Appliance's NFS server\n\
518 * filesystems that cache in temporary locations, such as NFS\n\
521 * compressed filesystems\n\
523 In addition, file system backups and remote mirrors may contain copies\n\
524 of the file that cannot be removed, and that will allow a shredded file\n\
525 to be recovered later.\n\
527 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
533 # define fdatasync(fd) -1
537 * --------------------------------------------------------------------
538 * Bob Jenkins' cryptographic random number generator, ISAAC.
539 * Hacked by Colin Plumb.
541 * We need a source of random numbers for some of the overwrite data.
542 * Cryptographically secure is desirable, but it's not life-or-death
543 * so I can be a little bit experimental in the choice of RNGs here.
545 * This generator is based somewhat on RC4, but has analysis
546 * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
547 * pointing to it actually being better. I like it because it's nice
548 * and fast, and because the author did good work analyzing it.
549 * --------------------------------------------------------------------
552 #if defined __STDC__ && __STDC__
553 # define UINT_MAX_32_BITS 4294967295U
555 # define UINT_MAX_32_BITS 0xFFFFFFFF
558 #if ULONG_MAX == UINT_MAX_32_BITS
559 typedef unsigned long word32;
561 # if UINT_MAX == UINT_MAX_32_BITS
562 typedef unsigned word32;
564 # if USHRT_MAX == UINT_MAX_32_BITS
565 typedef unsigned short word32;
567 # if UCHAR_MAX == UINT_MAX_32_BITS
568 typedef unsigned char word32;
570 "No 32-bit type available!"
576 /* Size of the state tables to use. (You may change ISAAC_LOG) */
578 #define ISAAC_WORDS (1 << ISAAC_LOG)
579 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (word32))
581 /* RNG state variables */
584 word32 mm[ISAAC_WORDS]; /* Main state array */
585 word32 iv[8]; /* Seeding initial vector */
586 word32 a, b, c; /* Extra index variables */
589 /* This index operation is more efficient on many processors */
591 (* (word32 *) ((char *) (mm) + ((x) & (ISAAC_WORDS - 1) * sizeof (word32))))
594 * The central step. This uses two temporaries, x and y. mm is the
595 * whole state array, while m is a pointer to the current word. off is
596 * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
597 * i.e. +/- ISAAC_WORDS/2.
599 #define isaac_step(mix, a, b, mm, m, off, r) \
601 a = ((a) ^ (mix)) + (m)[off], \
603 *(m) = y = ind (mm, x) + (a) + (b), \
604 *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
608 * Refill the entire R array, and update S.
611 isaac_refill (struct isaac_state *s, word32 r[/* ISAAC_WORDS */])
613 register word32 a, b; /* Caches of a and b */
614 register word32 x, y; /* Temps needed by isaac_step macro */
615 register word32 *m = s->mm; /* Pointer into state array */
622 isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
623 isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
624 isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
625 isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
628 while ((m += 4) < s->mm + ISAAC_WORDS / 2);
631 isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
632 isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
633 isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
634 isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
637 while ((m += 4) < s->mm + ISAAC_WORDS);
643 * The basic seed-scrambling step for initialization, based on Bob
644 * Jenkins' 256-bit hash.
646 #define mix(a,b,c,d,e,f,g,h) \
647 ( a ^= b << 11, d += a, \
648 b += c, b ^= c >> 2, e += b, \
649 c += d, c ^= d << 8, f += c, \
650 d += e, d ^= e >> 16, g += d, \
651 e += f, e ^= f << 10, h += e, \
652 f += g, f ^= g >> 4, a += f, \
653 g += h, g ^= h << 8, b += g, \
654 h += a, h ^= a >> 9, c += h, \
657 /* The basic ISAAC initialization pass. */
659 isaac_mix (struct isaac_state *s, word32 const seed[/* ISAAC_WORDS */])
671 for (i = 0; i < ISAAC_WORDS; i += 8)
682 mix (a, b, c, d, e, f, g, h);
704 #if 0 /* Provided for reference only; not used in this code */
706 * Initialize the ISAAC RNG with the given seed material.
707 * Its size MUST be a multiple of ISAAC_BYTES, and may be
708 * stored in the s->mm array.
710 * This is a generalization of the original ISAAC initialization code
711 * to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
715 isaac_init (struct isaac_state *s, word32 const *seed, size_t seedsize)
717 static word32 const iv[8] =
719 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
720 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
724 /* The initialization of iv is a precomputed form of: */
725 for (i = 0; i < 7; i++)
726 iv[i] = 0x9e3779b9; /* the golden ratio */
727 for (i = 0; i < 4; ++i) /* scramble it */
728 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
730 s->a = s->b = s->c = 0;
732 for (i = 0; i < 8; i++)
737 /* First pass (as in reference ISAAC code) */
739 /* Second and subsequent passes (extension to ISAAC) */
740 while (seedsize -= ISAAC_BYTES)
743 for (i = 0; i < ISAAC_WORDS; i++)
745 isaac_mix (s, s->mm);
750 /* The no seed case (as in reference ISAAC code) */
751 for (i = 0; i < ISAAC_WORDS; i++)
756 isaac_mix (s, s->mm);
760 /* Start seeding an ISAAC structire */
762 isaac_seed_start (struct isaac_state *s)
764 static word32 const iv[8] =
766 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
767 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
772 /* The initialization of iv is a precomputed form of: */
773 for (i = 0; i < 7; i++)
774 iv[i] = 0x9e3779b9; /* the golden ratio */
775 for (i = 0; i < 4; ++i) /* scramble it */
776 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
778 for (i = 0; i < 8; i++)
780 /* We could initialize s->mm to zero, but why bother? */
782 /* s->c gets used for a data pointer during the seeding phase */
783 s->a = s->b = s->c = 0;
786 /* Add a buffer of seed material */
788 isaac_seed_data (struct isaac_state *s, void const *buf, size_t size)
794 avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
796 /* Do any full buffers that are necessary */
799 p = (unsigned char *) s->mm + s->c;
800 for (i = 0; i < avail; i++)
801 p[i] ^= ((unsigned char const *) buf)[i];
802 buf = (char const *) buf + avail;
804 isaac_mix (s, s->mm);
806 avail = sizeof s->mm;
809 /* And the final partial block */
810 p = (unsigned char *) s->mm + s->c;
811 for (i = 0; i < size; i++)
812 p[i] ^= ((unsigned char const *) buf)[i];
813 s->c = (word32) size;
817 /* End of seeding phase; get everything ready to produce output. */
819 isaac_seed_finish (struct isaac_state *s)
821 isaac_mix (s, s->mm);
822 isaac_mix (s, s->mm);
823 /* Now reinitialize c to start things off right */
826 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
829 #if __GNUC__ >= 2 && (__i386__ || __alpha__)
831 * Many processors have very-high-resolution timer registers,
832 * The timer registers can be made inaccessible, so we have to deal with the
833 * possibility of SIGILL while we're working.
837 sigill_handler (int signum)
840 longjmp (env, 1); /* Trivial, just return an indication that it happened */
843 /* FIXME: find a better way.
844 This signal-handling code may well end up being ripped out eventually.
845 An example of how fragile it is, on an i586-sco-sysv5uw7.0.1 system, with
846 gcc-2.95.3pl1, the "rdtsc" instruction causes a segmentation violation.
847 So now, the code catches SIGSEGV. It'd probably be better to remove all
848 of that mess and find a better source of random data. Patches welcome. */
851 isaac_seed_machdep (struct isaac_state *s)
853 RETSIGTYPE (*old_handler[2]) (int);
855 /* This is how one does try/except in C */
856 old_handler[0] = signal (SIGILL, sigill_handler);
857 old_handler[1] = signal (SIGSEGV, sigill_handler);
858 if (setjmp (env)) /* ANSI: Must be entire controlling expression */
860 signal (SIGILL, old_handler[0]);
861 signal (SIGSEGV, old_handler[1]);
867 __asm__ __volatile__ ("rdtsc" : "=a" (t[0]), "=d" (t[1]));
871 __asm__ __volatile__ ("rpcc %0" : "=r" (t));
874 /* Code not used because this instruction is available only on first-
875 generation PPCs and evokes a SIGBUS on some Linux 2.4 kernels. */
877 __asm__ __volatile__ ("mfspr %0,22" : "=r" (t));
880 /* Code not used because this is not accessible from userland */
882 __asm__ __volatile__ ("mfc0\t%0,$9" : "=r" (t));
885 /* This doesn't compile on all platforms yet. How to fix? */
887 __asm__ __volatile__ ("rd %%tick, %0" : "=r" (t));
889 signal (SIGILL, old_handler[0]);
890 signal (SIGSEGV, old_handler[1]);
891 isaac_seed_data (s, &t, sizeof t);
895 #else /* !(__i386__ || __alpha__) */
897 /* Do-nothing stub */
898 # define isaac_seed_machdep(s) (void) 0
900 #endif /* !(__i386__ || __alpha__) */
904 * Get seed material. 16 bytes (128 bits) is plenty, but if we have
905 * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
908 isaac_seed (struct isaac_state *s)
910 isaac_seed_start (s);
912 { pid_t t = getpid (); ISAAC_SEED (s, t); }
913 { pid_t t = getppid (); ISAAC_SEED (s, t); }
914 { uid_t t = getuid (); ISAAC_SEED (s, t); }
915 { gid_t t = getgid (); ISAAC_SEED (s, t); }
919 hrtime_t t = gethrtime ();
922 # if HAVE_CLOCK_GETTIME /* POSIX ns-resolution */
924 clock_gettime (CLOCK_REALTIME, &t);
926 # if HAVE_GETTIMEOFDAY
928 gettimeofday (&t, (struct timezone *) 0);
931 t = time ((time_t *) 0);
938 isaac_seed_machdep (s);
942 int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
947 isaac_seed_data (s, buf, 32);
951 fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
954 /* /dev/random is more precious, so use less */
957 isaac_seed_data (s, buf, 16);
962 isaac_seed_finish (s);
965 /* Single-word RNG built on top of ISAAC */
968 word32 r[ISAAC_WORDS];
970 struct isaac_state *s;
974 irand_init (struct irand_state *r, struct isaac_state *s)
981 * We take from the end of the block deliberately, so if we need
982 * only a small number of values, we choose the final ones which are
983 * marginally better mixed than the initial ones.
986 irand32 (struct irand_state *r)
990 isaac_refill (r->s, r->r);
991 r->numleft = ISAAC_WORDS;
993 return r->r[--r->numleft];
997 * Return a uniformly distributed random number between 0 and n,
998 * inclusive. Thus, the result is modulo n+1.
1000 * Theory of operation: as x steps through every possible 32-bit number,
1001 * x % n takes each value at least 2^32 / n times (rounded down), but
1002 * the values less than 2^32 % n are taken one additional time. Thus,
1003 * x % n is not perfectly uniform. To fix this, the values of x less
1004 * than 2^32 % n are disallowed, and if the RNG produces one, we ask
1008 irand_mod (struct irand_state *r, word32 n)
1016 lim = -n % n; /* == (2**32-n) % n == 2**32 % n */
1026 * Fill a buffer with a fixed pattern.
1028 * The buffer must be at least 3 bytes long, even if
1029 * size is less. Larger sizes are filled exactly.
1032 fillpattern (int type, unsigned char *r, size_t size)
1035 unsigned bits = type & 0xfff;
1038 ((unsigned char *) r)[0] = (bits >> 4) & 255;
1039 ((unsigned char *) r)[1] = (bits >> 8) & 255;
1040 ((unsigned char *) r)[2] = bits & 255;
1041 for (i = 3; i < size / 2; i *= 2)
1042 memcpy ((char *) r + i, (char *) r, i);
1044 memcpy ((char *) r + i, (char *) r, size - i);
1046 /* Invert the first bit of every 512-byte sector. */
1048 for (i = 0; i < size; i += 512)
1053 * Fill a buffer, R (of size SIZE_MAX), with random data.
1054 * SIZE is rounded UP to a multiple of ISAAC_BYTES.
1057 fillrand (struct isaac_state *s, word32 *r, size_t size_max, size_t size)
1059 size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
1060 assert (size <= size_max);
1064 isaac_refill (s, r);
1070 * Generate a 6-character (+ nul) pass name string
1071 * FIXME: allow translation of "random".
1073 #define PASS_NAME_SIZE 7
1075 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
1078 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
1080 memcpy (name, "random", PASS_NAME_SIZE);
1084 * Do pass number k of n, writing "size" bytes of the given pattern "type"
1085 * to the file descriptor fd. Qname, k and n are passed in only for verbose
1086 * progress message purposes. If n == 0, no progress messages are printed.
1088 * If *sizep == -1, the size is unknown, and it will be filled in as soon
1092 dopass (int fd, char const *qname, off_t *sizep, int type,
1093 struct isaac_state *s, unsigned long k, unsigned long n)
1095 off_t size = *sizep;
1096 off_t offset; /* Current file posiiton */
1097 off_t thresh; /* Offset to print next status update */
1098 size_t lim; /* Amount of data to try writing */
1099 size_t soff; /* Offset into buffer for next write */
1100 ssize_t ssize; /* Return value from write */
1101 #if ISAAC_WORDS > 1024
1102 word32 r[ISAAC_WORDS * 3]; /* Multiple of 4K and of pattern size */
1104 word32 r[1024 * 3]; /* Multiple of 4K and of pattern size */
1106 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
1108 if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
1110 error (0, errno, _("%s: cannot rewind"), qname);
1114 /* Constant fill patterns need only be set up once. */
1118 if ((off_t) lim > size && size != -1)
1120 lim = (size_t) size;
1122 fillpattern (type, (unsigned char *) r, lim);
1123 passname ((unsigned char *) r, pass_string);
1127 passname (0, pass_string);
1130 /* Set position if first status update */
1134 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
1135 thresh = VERBOSE_UPDATE;
1136 if (thresh > size && size != -1)
1143 /* How much to write this time? */
1145 if ((off_t) lim > size - offset && size != -1)
1149 lim = (size_t) (size - offset);
1154 fillrand (s, r, sizeof r, lim);
1155 /* Loop to retry partial writes. */
1156 for (soff = 0; soff < lim; soff += ssize)
1158 ssize = write (fd, (char *) r + soff, lim - soff);
1161 if ((ssize == 0 || errno == ENOSPC)
1164 /* Ah, we have found the end of the file */
1165 *sizep = thresh = size = offset + soff;
1171 char buf[LONGEST_HUMAN_READABLE + 1];
1172 error (0, errnum, _("%s: error writing at offset %s"),
1174 human_readable ((uintmax_t) (offset + soff),
1177 * I sometimes use shred on bad media, before throwing it
1178 * out. Thus, I don't want it to give up on bad blocks.
1179 * This code assumes 512-byte blocks and tries to skip
1180 * over them. It works because lim is always a multiple
1181 * of 512, except at the end.
1183 if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
1186 if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
1192 error (0, errno, "%s: lseek", qname);
1199 /* Okay, we have written "lim" bytes. */
1201 if (offset + lim < offset)
1203 error (0, 0, _("%s: file too large"), qname);
1209 /* Time to print progress? */
1210 if (offset >= thresh && n)
1212 char offset_buf[LONGEST_HUMAN_READABLE + 1];
1213 char size_buf[LONGEST_HUMAN_READABLE + 1];
1214 char const *human_offset
1215 = human_readable ((uintmax_t) offset, offset_buf, 1,
1218 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s"), qname, k, n,
1219 pass_string, human_offset,
1220 human_readable ((uintmax_t) size, size_buf, 1,
1221 OUTPUT_BLOCK_SIZE));
1223 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), qname, k, n,
1224 pass_string, human_offset);
1226 thresh += VERBOSE_UPDATE;
1227 if (thresh > size && size != -1)
1230 * Force periodic syncs to keep displayed progress accurate
1231 * FIXME: Should these be present even if -v is not enabled,
1232 * to keep the buffer cache from filling with dirty pages?
1233 * It's a common problem with programs that do lots of writes,
1236 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1238 error (0, errno, "%s: fsync", qname);
1244 /* Force what we just wrote to hit the media. */
1245 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1247 error (0, errno, "%s: fsync", qname);
1254 * The passes start and end with a random pass, and the passes in between
1255 * are done in random order. The idea is to deprive someone trying to
1256 * reverse the process of knowledge of the overwrite patterns, so they
1257 * have the additional step of figuring out what was done to the disk
1258 * before they can try to reverse or cancel it.
1260 * First, all possible 1-bit patterns. There are two of them.
1261 * Then, all possible 2-bit patterns. There are four, but the two
1262 * which are also 1-bit patterns can be omitted.
1263 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
1264 * Then, all possible 4-bit patterns. 16-4 = 12.
1266 * The basic passes are:
1267 * 1-bit: 0x000, 0xFFF
1268 * 2-bit: 0x555, 0xAAA
1269 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
1270 * 100100100100 110110110110
1272 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1273 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
1274 * Adding three random passes at the beginning, middle and end
1275 * produces the default 25-pass structure.
1277 * The next extension would be to 5-bit and 6-bit patterns.
1278 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
1279 * 6-bit patterns, so they would increase the time required
1280 * significantly. 4-bit patterns are enough for most purposes.
1282 * The main gotcha is that this would require a trickier encoding,
1283 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
1284 * lcm(2,3,4,5) = 60 bits is not.
1286 * One extension that is included is to complement the first bit in each
1287 * 512-byte block, to alter the phase of the encoded data in the more
1288 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
1289 * are considered part of the 3-bit ones and the 2-bit patterns are
1290 * considered part of the 4-bit patterns.
1293 * How does the generalization to variable numbers of passes work?
1296 * Have an ordered list of groups of passes. Each group is a set.
1297 * Take as many groups as will fit, plus a random subset of the
1298 * last partial group, and place them into the passes list.
1299 * Then shuffle the passes list into random order and use that.
1301 * One extra detail: if we can't include a large enough fraction of the
1302 * last group to be interesting, then just substitute random passes.
1304 * If you want more passes than the entire list of groups can
1305 * provide, just start repeating from the beginning of the list.
1310 -2, /* 2 random passes */
1311 2, 0x000, 0xFFF, /* 1-bit */
1312 2, 0x555, 0xAAA, /* 2-bit */
1313 -1, /* 1 random pass */
1314 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
1315 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1316 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
1317 -1, /* 1 random pass */
1318 /* The following patterns have the frst bit per block flipped */
1319 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1320 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1321 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1322 -1, /* 1 random pass */
1327 * Generate a random wiping pass pattern with num passes.
1328 * This is a two-stage process. First, the passes to include
1329 * are chosen, and then they are shuffled into the desired
1333 genpattern (int *dest, size_t num, struct isaac_state *s)
1335 struct irand_state r;
1340 size_t accum, top, swap;
1348 /* Stage 1: choose the passes to use */
1351 d = dest; /* Destination for generated pass list */
1352 n = num; /* Passes remaining to fill */
1356 k = *p++; /* Block descriptor word */
1358 { /* Loop back to the beginning */
1362 { /* -k random passes */
1364 if ((size_t) k >= n)
1373 else if ((size_t) k <= n)
1374 { /* Full block of patterns */
1375 memcpy (d, p, k * sizeof (int));
1380 else if (n < 2 || 3 * n < (size_t) k)
1381 { /* Finish with random */
1386 { /* Pad out with k of the n available */
1389 if (n == (size_t) k-- || irand_mod (&r, k) < n)
1400 top = num - randpasses; /* Top of initialized data */
1401 /* assert (d == dest+top); */
1404 * We now have fixed patterns in the dest buffer up to
1405 * "top", and we need to scramble them, with "randpasses"
1406 * random passes evenly spaced among them.
1408 * We want one at the beginning, one at the end, and
1409 * evenly spaced in between. To do this, we basically
1410 * use Bresenham's line draw (a.k.a DDA) algorithm
1411 * to draw a line with slope (randpasses-1)/(num-1).
1412 * (We use a positive accumulator and count down to
1415 * So for each desired output value, we do the following:
1416 * - If it should be a random pass, copy the pass type
1417 * to top++, out of the way of the other passes, and
1418 * set the current pass to -1 (random).
1419 * - If it should be a normal pattern pass, choose an
1420 * entry at random between here and top-1 (inclusive)
1421 * and swap the current entry with that one.
1423 randpasses--; /* To speed up later math */
1424 accum = randpasses; /* Bresenham DDA accumulator */
1425 for (n = 0; n < num; n++)
1427 if (accum <= randpasses)
1430 dest[top++] = dest[n];
1435 swap = n + irand_mod (&r, top - n - 1);
1437 dest[n] = dest[swap];
1440 accum -= randpasses;
1442 /* assert (top == num); */
1444 memset (&r, 0, sizeof r); /* Wipe this on general principles */
1448 * The core routine to actually do the work. This overwrites the first
1449 * size bytes of the given fd. Returns -1 on error, 0 on success.
1452 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1453 struct Options const *flags)
1457 off_t size; /* Size to write, size to read */
1458 unsigned long n; /* Number of passes for printing purposes */
1461 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
1463 n = flags->n_iterations + ((flags->zero_fill) != 0);
1465 if (fstat (fd, &st))
1467 error (0, errno, "%s: fstat", qname);
1471 /* If we know that we can't possibly shred the file, give up now.
1472 Otherwise, we may go into a infinite loop writing data before we
1473 find that we can't rewind the device. */
1474 if ((S_ISCHR (st.st_mode) && isatty (fd))
1475 || S_ISFIFO (st.st_mode)
1476 || S_ISSOCK (st.st_mode))
1478 error (0, 0, _("%s: invalid file type"), qname);
1482 /* Allocate pass array */
1483 passarray = xmalloc (flags->n_iterations * sizeof (int));
1488 /* Accept a length of zero only if it's a regular file.
1489 For any other type of file, try to get the size another way. */
1490 if (S_ISREG (st.st_mode))
1495 error (0, 0, _("%s: file has negative size"), qname);
1501 size = lseek (fd, (off_t) 0, SEEK_END);
1504 /* We are unable to determine the length, up front.
1505 Let dopass do that as part of its first iteration. */
1510 if (0 <= size && !(flags->exact))
1512 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1514 /* If in rounding up, we've just overflowed, use the maximum. */
1516 size = TYPE_MAXIMUM (off_t);
1520 /* Schedule the passes in random order. */
1521 genpattern (passarray, flags->n_iterations, s);
1524 for (i = 0; i < flags->n_iterations; i++)
1526 if (dopass (fd, qname, &size, passarray[i], s, i + 1, n) < 0)
1528 memset (passarray, 0, flags->n_iterations * sizeof (int));
1534 memset (passarray, 0, flags->n_iterations * sizeof (int));
1537 if (flags->zero_fill)
1538 if (dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n) < 0)
1541 /* Okay, now deallocate the data. The effect of ftruncate on
1542 non-regular files is unspecified, so don't worry about any
1543 errors reported for them. */
1544 if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1545 && S_ISREG (st.st_mode))
1547 error (0, errno, _("%s: error truncating"), qname);
1554 /* A wrapper with a little more checking for fds on the command line */
1556 wipefd (int fd, char const *qname, struct isaac_state *s,
1557 struct Options const *flags)
1559 int fd_flags = fcntl (fd, F_GETFL);
1563 error (0, errno, "%s: fcntl", qname);
1566 if (fd_flags & O_APPEND)
1568 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1571 return do_wipefd (fd, qname, s, flags);
1574 /* --- Name-wiping code --- */
1576 /* Characters allowed in a file name - a safe universal set. */
1577 static char const nameset[] =
1578 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+=%@#.";
1581 * This increments the name, considering it as a big-endian base-N number
1582 * with the digits taken from nameset. Characters not in the nameset
1583 * are considered to come before nameset[0].
1585 * It's not obvious, but this will explode if name[0..len-1] contains
1588 * This returns the carry (1 on overflow).
1591 incname (char *name, unsigned len)
1598 p = strchr (nameset, name[--len]);
1599 /* If the character is not found, replace it with a 0 digit */
1602 name[len] = nameset[0];
1605 /* If this character has a successor, use it */
1611 /* Otherwise, set this digit to 0 and increment the prefix */
1612 name[len] = nameset[0];
1613 return incname (name, len);
1617 * Repeatedly rename a file with shorter and shorter names,
1618 * to obliterate all traces of the file name on any system that
1619 * adds a trailing delimiter to on-disk file names and reuses
1620 * the same directory slot. Finally, unlink it.
1621 * The passed-in filename is modified in place to the new filename.
1622 * (Which is unlinked if this function succeeds, but is still present if
1623 * it fails for some reason.)
1625 * The main loop is written carefully to not get stuck if all possible
1626 * names of a given length are occupied. It counts down the length from
1627 * the original to 0. While the length is non-zero, it tries to find an
1628 * unused file name of the given length. It continues until either the
1629 * name is available and the rename succeeds, or it runs out of names
1630 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1632 * The unlink is Unix-specific, as ANSI-standard remove has more
1633 * portability problems with C libraries making it "safe". rename
1636 * To force the directory data out, we try to open the directory and
1637 * invoke fdatasync on it. This is rather non-standard, so we don't
1638 * insist that it works, just fall back to a global sync in that case.
1639 * This is fairly significantly Unix-specific. Of course, on any
1640 * filesystem with synchronous metadata updates, this is unnecessary.
1643 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1645 char *newname, *base; /* Base points to filename part of newname */
1648 int dir_fd; /* Try to open directory to sync *it* */
1650 newname = xstrdup (oldname);
1652 error (0, 0, _("%s: removing"), qoldname);
1654 /* Find the file name portion */
1655 base = strrchr (newname, '/');
1656 /* Temporary hackery to get a directory fd */
1660 dir_fd = open (newname, O_RDONLY | O_NOCTTY);
1665 dir_fd = open (".", O_RDONLY | O_NOCTTY);
1667 base = base ? base + 1 : newname;
1668 len = strlen (base);
1672 memset (base, nameset[0], len);
1677 if (lstat (newname, &st) < 0)
1679 if (rename (oldname, newname) == 0)
1682 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1683 sync (); /* Force directory out */
1687 * People seem to understand this better than talking
1688 * about renaming oldname. newname doesn't need
1689 * quoting because we picked it.
1691 error (0, 0, _("%s: renamed to %s"), qoldname,
1694 memcpy (oldname + (base - newname), base, len + 1);
1699 /* The rename failed: give up on this length. */
1705 /* newname exists, so increment BASE so we use another */
1708 while (!incname (base, len));
1712 err = unlink (oldname);
1713 if (dir_fd < 0 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1716 if (!err && flags->verbose)
1717 error (0, 0, _("%s: removed"), qoldname);
1722 * Finally, the function that actually takes a filename and grinds
1723 * it into hamburger.
1726 * Detail to note: since we do not restore errno to EACCES after
1727 * a failed chmod, we end up printing the error code from the chmod.
1728 * This is actually the error that stopped us from proceeding, so
1729 * it's arguably the right one, and in practice it'll be either EACCES
1730 * again or EPERM, which both give similar error messages.
1731 * Does anyone disagree?
1734 wipefile (char *name, char const *qname,
1735 struct isaac_state *s, struct Options const *flags)
1739 fd = open (name, O_WRONLY | O_NOCTTY);
1742 if (errno == EACCES && flags->force)
1744 if (chmod (name, S_IWUSR) >= 0) /* 0200, user-write-only */
1745 fd = open (name, O_WRONLY | O_NOCTTY);
1747 else if ((errno == ENOENT || errno == ENOTDIR)
1748 && strncmp (name, "/dev/fd/", 8) == 0)
1750 /* We accept /dev/fd/# even if the OS doesn't support it */
1755 num = strtoul (name + 8, &p, 10);
1756 /* If it's completely decimal with no leading zeros... */
1757 if (errno == 0 && !*p && num <= INT_MAX &&
1758 (('1' <= name[8] && name[8] <= '9')
1759 || (name[8] == '0' && !name[9])))
1761 return wipefd ((int) num, qname, s, flags);
1768 error (0, errno, "%s", qname);
1772 err = do_wipefd (fd, qname, s, flags);
1773 if (close (fd) != 0)
1775 error (0, 0, "%s: close", qname);
1778 if (err == 0 && flags->remove_file)
1780 err = wipename (name, qname, flags);
1782 error (0, 0, _("%s: cannot remove"), qname);
1788 main (int argc, char **argv)
1790 struct isaac_state s;
1792 struct Options flags;
1798 program_name = argv[0];
1799 setlocale (LC_ALL, "");
1800 bindtextdomain (PACKAGE, LOCALEDIR);
1801 textdomain (PACKAGE);
1803 atexit (close_stdout);
1805 GETTIMEOFDAY_INIT ();
1809 memset (&flags, 0, sizeof flags);
1811 flags.n_iterations = DEFAULT_PASSES;
1814 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1828 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1829 || (word32) tmp != tmp
1830 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1832 error (1, 0, _("%s: invalid number of passes"),
1833 quotearg_colon (optarg));
1835 flags.n_iterations = (size_t) tmp;
1840 flags.remove_file = 1;
1846 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkMGTPEZY0")
1849 error (1, 0, _("%s: invalid file size"),
1850 quotearg_colon (optarg));
1865 flags.zero_fill = 1;
1868 case_GETOPT_HELP_CHAR;
1870 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1877 file = argv + optind;
1878 n_files = argc - optind;
1882 error (0, 0, _("missing file argument"));
1886 for (i = 0; i < n_files; i++)
1888 char const *qname = quotearg_colon (file[i]);
1889 if (strcmp (file[i], "-") == 0)
1891 if (wipefd (STDOUT_FILENO, qname, &s, &flags) < 0)
1896 /* Plain filename - Note that this overwrites *argv! */
1897 if (wipefile (file[i], qname, &s, &flags) < 0)
1902 /* Just on general principles, wipe s. */
1903 memset (&s, 0, sizeof s);