1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999, 2000, 2001 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., 59 Temple Place - Suite 330, 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 - Deal with the amazing variety of gettimeofday() implementation bugs.
31 (Some systems use a one-arg form; still others insist that the timezone
32 either be NULL or be non-NULL. Whee.)
33 - Add an unlink-all option to emulate rm.
37 * Do a securer overwrite of given files or devices, to make it harder
38 * for even very expensive hardware probing to recover the data.
40 * Although this process is also known as "wiping", I prefer the longer
41 * name both because I think it is more evocative of what is happening and
42 * because a longer name conveys a more appropriate sense of deliberateness.
44 * For the theory behind this, see "Secure Deletion of Data from Magnetic
45 * and Solid-State Memory", on line at
46 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
48 * Just for the record, reversing one or two passes of disk overwrite
49 * is not terribly difficult with hardware help. Hook up a good-quality
50 * digitizing oscilloscope to the output of the head preamplifier and copy
51 * the high-res digitized data to a computer for some off-line analysis.
52 * Read the "current" data and average all the pulses together to get an
53 * "average" pulse on the disk. Subtract this average pulse from all of
54 * the actual pulses and you can clearly see the "echo" of the previous
57 * Real hard drives have to balance the cost of the media, the head,
58 * and the read circuitry. They use better-quality media than absolutely
59 * necessary to limit the cost of the read circuitry. By throwing that
60 * assumption out, and the assumption that you want the data processed
61 * as fast as the hard drive can spin, you can do better.
63 * If asked to wipe a file, this also unlinks it, renaming it to in a
64 * clever way to try to leave no trace of the original filename.
66 * The ISAAC code still bears some resemblance to the code written
67 * by Bob Jenkins, but he permits pretty unlimited use.
69 * This was inspired by a desire to improve on some code titled:
70 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
71 * but I've rewritten everything here so completely that no trace of
72 * the original remains.
75 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
77 * Jim Meyering, for his work merging this into the GNU fileutils while
78 * still letting me feel a sense of ownership and pride. Getting me to
79 * tolerate the GNU brace style was quite a feat of diplomacy.
80 * Paul Eggert, for lots of useful discussion and code. I disagree with
81 * an awful lot of his suggestions, but they're disagreements worth having.
83 * Things to think about:
84 * - Security: Is there any risk to the race
85 * between overwriting and unlinking a file? Will it do anything
86 * drastically bad if told to attack a named pipe or socket?
89 /* The official name of this program (e.g., no `g' prefix). */
90 #define PROGRAM_NAME "shred"
92 #define AUTHORS "Colin Plumb"
103 #include <sys/types.h>
106 /* Default fileutils build */
108 # include "xstrtol.h"
109 # include "closeout.h"
112 # include "quotearg.h" /* For quotearg_colon */
113 # include "quote.h" /* For quotearg_colon */
115 char *xstrdup PARAMS ((char const *));
117 #else /* !HAVE_CONFIG_H */
119 * Standalone build - this file compiles by itself without autoconf and
120 * the like. No i18n, and I still have to write a stub for getopt_long,
121 * but it's a lot less intertwingled than the usual GNU utilities.
124 # include <ctype.h> /* For isprint */
125 # include <string.h> /* For memcpy, strerror */
126 # include <limits.h> /* For ULONG_MAX etc. */
127 # include <stdlib.h> /* For strtoul, EXIT_FAILURE */
129 # include <fcntl.h> /* For O_RDONLY etc. */
130 # include <unistd.h> /* For getpid, etc. */
131 # include <sys/time.h> /* For struct timeval */
132 # include <sys/stat.h> /* For struct stat */
134 # define PACKAGE "standalone"
135 # define VERSION "2.0" /* Kind of arbitrary... */
137 # if __GNUC__ < 2 || __GNUC__ == 2 && __GNUC_MINOR__ < 5 || __STRICT_ANSI__
138 # define attribute(x)
140 # define attribute __attribute__
141 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
142 /* The __-protected forms were introduced in GCC 2.6.4 */
143 # define __format__ format
144 # define __printf__ printf
148 /* Reasonable default assumptions for time-getting */
149 # ifndef HAVE_GETTIMEOFDAY
150 # define HAVE_GETTIMEOFDAY 1 /* Most systems have it these days */
153 # ifdef CLOCK_REALTIME
154 # ifndef HAVE_CLOCK_GETTIME
155 # define HAVE_CLOCK_GETTIME 1
159 # ifndef STDOUT_FILENO
160 # define STDOUT_FILENO 1
163 # define RETSIGTYPE int
167 # define S_IWUSR S_IWRITE
169 # define S_IWUSR 0200
173 /* POSIX doesn't require st_blksize, and 65536 is a reasonable
174 upper bound for existing filesystem practice. */
175 # define ST_BLKSIZE(Stat) 65536
177 # define uintmax_t unsigned long
179 /* Variant human-readable function that ignores last two args */
180 # define human_readable(v, b, f, t) (sprintf (b, "%lu", (unsigned long) v), b)
181 # define LONGEST_HUMAN_READABLE (sizeof (uintmax_t) * CHAR_BIT / 3)
183 /* Variant convert-to-uintmax_t function that accepts metric suffixes */
186 LONGINT_OK, LONGINT_INVALID, LONGINT_INVALID_SUFFIX_CHAR, LONGINT_OVERFLOW
189 xstrtoumax (char const *ptr, char const **end, int base, uintmax_t *res,
190 char const *valid_suffixes)
194 static char const metric_suffixes[] = "kMGTPEZY";
200 *res = n = strtoul (ptr, &end_ptr, base);
204 return LONGINT_OVERFLOW;
208 if (valid_suffixes && c && strchr (valid_suffixes, c))
211 return LONGINT_INVALID;
215 /* Now deal with metric-style suffixes */
216 if (valid_suffixes && !strchr (valid_suffixes, c))
217 return LONGINT_INVALID_SUFFIX_CHAR;
223 if (n > ULONG_MAX/512)
224 return LONGINT_OVERFLOW;
229 if (n > ULONG_MAX/102412)
230 return LONGINT_OVERFLOW;
245 p = strchr (metric_suffixes, c);
247 return LONGINT_INVALID_SUFFIX_CHAR;
249 * If valid_suffixes contains '0', then B (decimal) and iB (binary)
250 * are allowed as "supersuffixes". Binary is the default.
252 if (strchr (valid_suffixes, '0'))
254 /* 'D' is obsolescent */
255 if (end_ptr[1] == 'B' || end_ptr[1] == 'D')
260 else if (end_ptr[1] == 'i' && end_ptr[2] == 'B')
263 /* Now do the scaling */
267 if (n > ULONG_MAX/1000)
268 return LONGINT_OVERFLOW;
270 } while (--p > metric_suffixes);
273 if (n > ULONG_MAX/1024)
274 return LONGINT_OVERFLOW;
276 } while (--p > metric_suffixes);
281 *end = end_ptr+1; /* Extra suffix is allowed if it's expected */
283 return LONGINT_INVALID_SUFFIX_CHAR;
288 /* Dummy i18n stubs */
291 # define setlocale(x,y) (void) 0
292 # define bindtextdomain(x,y) (void) 0
293 # define textdomain(x) (void) 0
296 * Print a message with `fprintf (stderr, FORMAT, ...)';
297 * if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
298 * If STATUS is nonzero, terminate the program with `exit (STATUS)'.
300 static void error (int status, int errnum, const char *format, ...)
301 attribute ((__format__ (__printf__, 3, 4)));
303 extern char const *program_name;
305 error (int status, int errnum, const char *format, ...)
311 fputs (program_name, stderr);
312 fputs (": ", stderr);
314 va_start (ap, format);
315 vfprintf (stderr, format, ap);
319 fputs (": ", stderr);
320 fputs (strerror (errnum), stderr);
329 * GNU programs actually check for failure closing standard output.
330 * This seems unnecessary, until your shell script starts hitting
331 * ENOSPC and doing bizarre things with zero-length files.
337 error (EXIT_FAILURE, 0, _("write error"));
338 if (fclose (stdout) != 0)
339 error (EXIT_FAILURE, errno, _("write error"));
343 * Quote the argument (including colon characters) into the buffer.
344 * Return the buffer size used (including trailing null byte.)
345 * If this is larger than the bufsize, it is an estimate of the space
349 quotearg_colon_buf (char const *arg, char *buf, size_t bufsize)
351 /* Some systems don't have \a or \e, so this is ASCII-dependent */
352 static char const escaped[] = "\7\b\33\f\n\r\t\v";
353 static char const escapes[] = "abefnrtv";
358 while ((c = (unsigned char) *arg++) != 0)
362 if (strchr ("\\:", c)) /* Anything else we should quote? */
363 if (pos++ < bufsize) *buf++ = '\\';
367 if (pos++ < bufsize) *buf++ = '\\';
368 p = strchr (escaped, c); /* c is never 0, so this is okay */
371 c = escapes[p-escaped];
375 if ('0' <= *arg && *arg <= '9')
376 c += 256; /* Force 3-digit form if followed by a digit */
378 if (pos++ < bufsize) *buf++ = "0123"[c>>6 & 3];
380 if (pos++ < bufsize) *buf++ = "01234567"[c>>3 & 7];
381 c = "01234567"[c & 7];
384 if (pos++ < bufsize) *buf++ = c;
386 if (pos++ < bufsize) *buf++ = 0;
390 /* Quote metacharacters in a filename */
392 quotearg_colon (char const *arg)
394 static char *buf = 0;
398 while ((newsize = quotearg_colon_buf (arg, buf, bufsize)) > bufsize)
400 buf = realloc (buf, newsize);
402 error (EXIT_FAILURE, 0, _("memory exhausted"));
411 void *p = malloc (n);
413 error (EXIT_FAILURE, 0, _("memory exhausted"));
418 xstrdup (char const *string)
420 return strcpy (xmalloc (strlen (string) + 1), string);
423 #endif /* ! HAVE_CONFIG_H */
426 # define O_NOCTTY 0 /* This is a very optional frill */
429 /* Some systems don't support some file types. */
431 # define S_ISFIFO(mode) 0
434 # define S_ISLNK(mode) 0
437 # define S_ISSOCK(mode) 0
440 #define DEFAULT_PASSES 25 /* Default */
442 /* How often to update wiping display */
443 #define VERBOSE_UPDATE 150*1024
445 /* If positive, the units to use when printing sizes;
446 if negative, the human-readable base. */
447 #define OUTPUT_BLOCK_SIZE (-1024)
451 int force; /* -f flag: chmod files if necessary */
452 size_t n_iterations; /* -n flag: Number of iterations */
453 off_t size; /* -s flag: size of file */
454 int remove_file; /* -u flag: remove file after shredding */
455 int verbose; /* -v flag: Print progress */
456 int exact; /* -x flag: Do not round up file size */
457 int zero_fill; /* -z flag: Add a final zero pass */
460 static struct option const long_opts[] =
462 {"exact", no_argument, NULL, 'x'},
463 {"force", no_argument, NULL, 'f'},
464 {"iterations", required_argument, NULL, 'n'},
465 {"size", required_argument, NULL, 's'},
466 {"remove", no_argument, NULL, 'u'},
467 {"verbose", no_argument, NULL, 'v'},
468 {"zero", required_argument, NULL, 'z'},
469 {GETOPT_HELP_OPTION_DECL},
470 {GETOPT_VERSION_OPTION_DECL},
474 /* Global variable for error printing purposes */
475 char const *program_name; /* Initialized before any possible use */
481 fprintf (stderr, _("Try `%s --help' for more information.\n"),
485 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
487 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
488 for even very expensive hardware probing to recover the data.\n\
492 Mandatory arguments to long options are mandatory for short options too.\n\
495 -f, --force change permissions to allow writing if necessary\n\
496 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
497 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
500 -u, --remove truncate and remove file after overwriting\n\
501 -v, --verbose show progress\n\
502 -x, --exact do not round file sizes up to the next full block\n\
503 -z, --zero add a final overwrite with zeros to hide shredding\n\
504 - shred standard output\n\
506 fputs (HELP_OPTION_DESCRIPTION, stdout);
507 fputs (VERSION_OPTION_DESCRIPTION, stdout);
510 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
511 the files because it is common to operate on device files like /dev/hda,\n\
512 and those files usually should not be removed. When operating on regular\n\
513 files, most people use the --remove option.\n\
517 CAUTION: Note that shred relies on a very important assumption:\n\
518 that the filesystem overwrites data in place. This is the traditional\n\
519 way to do things, but many modern filesystem designs do not satisfy this\n\
520 assumption. The following are examples of filesystems on which shred is\n\
525 * log-structured or journaled filesystems, such as those supplied with\n\
526 AIX and Solaris (and JFS, ReiserFS, XFS, etc.)\n\
528 * filesystems that write redundant data and carry on even if some writes\n\
529 fail, such as RAID-based filesystems\n\
531 * filesystems that make snapshots, such as Network Appliance's NFS server\n\
535 * filesystems that cache in temporary locations, such as NFS\n\
538 * compressed filesystems\n\
540 In addition, file system backups and remote mirrors may contain copies\n\
541 of the file that cannot be removed, and that will allow a shredded file\n\
542 to be recovered later.\n\
544 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
550 # define fdatasync(fd) -1
554 * --------------------------------------------------------------------
555 * Bob Jenkins' cryptographic random number generator, ISAAC.
556 * Hacked by Colin Plumb.
558 * We need a source of random numbers for some of the overwrite data.
559 * Cryptographically secure is desirable, but it's not life-or-death
560 * so I can be a little bit experimental in the choice of RNGs here.
562 * This generator is based somewhat on RC4, but has analysis
563 * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
564 * pointing to it actually being better. I like it because it's nice
565 * and fast, and because the author did good work analyzing it.
566 * --------------------------------------------------------------------
569 #if defined __STDC__ && __STDC__
570 # define UINT_MAX_32_BITS 4294967295U
572 # define UINT_MAX_32_BITS 0xFFFFFFFF
575 #if ULONG_MAX == UINT_MAX_32_BITS
576 typedef unsigned long word32;
578 # if UINT_MAX == UINT_MAX_32_BITS
579 typedef unsigned word32;
581 # if USHRT_MAX == UINT_MAX_32_BITS
582 typedef unsigned short word32;
584 # if UCHAR_MAX == UINT_MAX_32_BITS
585 typedef unsigned char word32;
587 "No 32-bit type available!"
593 /* Size of the state tables to use. (You may change ISAAC_LOG) */
595 #define ISAAC_WORDS (1 << ISAAC_LOG)
596 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (word32))
598 /* RNG state variables */
601 word32 mm[ISAAC_WORDS]; /* Main state array */
602 word32 iv[8]; /* Seeding initial vector */
603 word32 a, b, c; /* Extra index variables */
606 /* This index operation is more efficient on many processors */
608 (* (word32 *) ((char *) (mm) + ((x) & (ISAAC_WORDS - 1) * sizeof (word32))))
611 * The central step. This uses two temporaries, x and y. mm is the
612 * whole state array, while m is a pointer to the current word. off is
613 * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
614 * i.e. +/- ISAAC_WORDS/2.
616 #define isaac_step(mix, a, b, mm, m, off, r) \
618 a = ((a) ^ (mix)) + (m)[off], \
620 *(m) = y = ind (mm, x) + (a) + (b), \
621 *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
625 * Refill the entire R array, and update S.
628 isaac_refill (struct isaac_state *s, word32 r[/* ISAAC_WORDS */])
630 register word32 a, b; /* Caches of a and b */
631 register word32 x, y; /* Temps needed by isaac_step macro */
632 register word32 *m = s->mm; /* Pointer into state array */
639 isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
640 isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
641 isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
642 isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
645 while ((m += 4) < s->mm + ISAAC_WORDS / 2);
648 isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
649 isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
650 isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
651 isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
654 while ((m += 4) < s->mm + ISAAC_WORDS);
660 * The basic seed-scrambling step for initialization, based on Bob
661 * Jenkins' 256-bit hash.
663 #define mix(a,b,c,d,e,f,g,h) \
664 ( a ^= b << 11, d += a, \
665 b += c, b ^= c >> 2, e += b, \
666 c += d, c ^= d << 8, f += c, \
667 d += e, d ^= e >> 16, g += d, \
668 e += f, e ^= f << 10, h += e, \
669 f += g, f ^= g >> 4, a += f, \
670 g += h, g ^= h << 8, b += g, \
671 h += a, h ^= a >> 9, c += h, \
674 /* The basic ISAAC initialization pass. */
676 isaac_mix (struct isaac_state *s, word32 const seed[/* ISAAC_WORDS */])
688 for (i = 0; i < ISAAC_WORDS; i += 8)
699 mix (a, b, c, d, e, f, g, h);
721 #if 0 /* Provided for reference only; not used in this code */
723 * Initialize the ISAAC RNG with the given seed material.
724 * Its size MUST be a multiple of ISAAC_BYTES, and may be
725 * stored in the s->mm array.
727 * This is a generalization of the original ISAAC initialization code
728 * to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
732 isaac_init (struct isaac_state *s, word32 const *seed, size_t seedsize)
734 static word32 const iv[8] =
736 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
737 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
741 /* The initialization of iv is a precomputed form of: */
742 for (i = 0; i < 7; i++)
743 iv[i] = 0x9e3779b9; /* the golden ratio */
744 for (i = 0; i < 4; ++i) /* scramble it */
745 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
747 s->a = s->b = s->c = 0;
749 for (i = 0; i < 8; i++)
754 /* First pass (as in reference ISAAC code) */
756 /* Second and subsequent passes (extension to ISAAC) */
757 while (seedsize -= ISAAC_BYTES)
760 for (i = 0; i < ISAAC_WORDS; i++)
762 isaac_mix (s, s->mm);
767 /* The no seed case (as in reference ISAAC code) */
768 for (i = 0; i < ISAAC_WORDS; i++)
773 isaac_mix (s, s->mm);
777 /* Start seeding an ISAAC structire */
779 isaac_seed_start (struct isaac_state *s)
781 static word32 const iv[8] =
783 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
784 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
789 /* The initialization of iv is a precomputed form of: */
790 for (i = 0; i < 7; i++)
791 iv[i] = 0x9e3779b9; /* the golden ratio */
792 for (i = 0; i < 4; ++i) /* scramble it */
793 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
795 for (i = 0; i < 8; i++)
797 /* We could initialize s->mm to zero, but why bother? */
799 /* s->c gets used for a data pointer during the seeding phase */
800 s->a = s->b = s->c = 0;
803 /* Add a buffer of seed material */
805 isaac_seed_data (struct isaac_state *s, void const *buf, size_t size)
811 avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
813 /* Do any full buffers that are necessary */
816 p = (unsigned char *) s->mm + s->c;
817 for (i = 0; i < avail; i++)
818 p[i] ^= ((unsigned char const *) buf)[i];
819 buf = (char const *) buf + avail;
821 isaac_mix (s, s->mm);
823 avail = sizeof s->mm;
826 /* And the final partial block */
827 p = (unsigned char *) s->mm + s->c;
828 for (i = 0; i < size; i++)
829 p[i] ^= ((unsigned char const *) buf)[i];
830 s->c = (word32) size;
834 /* End of seeding phase; get everything ready to produce output. */
836 isaac_seed_finish (struct isaac_state *s)
838 isaac_mix (s, s->mm);
839 isaac_mix (s, s->mm);
840 /* Now reinitialize c to start things off right */
843 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
846 #if __GNUC__ >= 2 && (__i386__ || __alpha__)
848 * Many processors have very-high-resolution timer registers,
849 * The timer registers can be made inaccessible, so we have to deal with the
850 * possibility of SIGILL while we're working.
854 sigill_handler (int signum)
857 longjmp (env, 1); /* Trivial, just return an indication that it happened */
860 /* FIXME: find a better way.
861 This signal-handling code may well end up being ripped out eventually.
862 An example of how fragile it is, on an i586-sco-sysv5uw7.0.1 system, with
863 gcc-2.95.3pl1, the "rdtsc" instruction causes a segmentation violation.
864 So now, the code catches SIGSEGV. It'd probably be better to remove all
865 of that mess and find a better source of random data. Patches welcome. */
868 isaac_seed_machdep (struct isaac_state *s)
870 RETSIGTYPE (*old_handler[2]) (int);
872 /* This is how one does try/except in C */
873 old_handler[0] = signal (SIGILL, sigill_handler);
874 old_handler[1] = signal (SIGSEGV, sigill_handler);
875 if (setjmp (env)) /* ANSI: Must be entire controlling expression */
877 signal (SIGILL, old_handler[0]);
878 signal (SIGSEGV, old_handler[1]);
884 __asm__ __volatile__ ("rdtsc" : "=a" (t[0]), "=d" (t[1]));
888 __asm__ __volatile__ ("rpcc %0" : "=r" (t));
891 /* Code not used because this instruction is available only on first-
892 generation PPCs and evokes a SIGBUS on some Linux 2.4 kernels. */
894 __asm__ __volatile__ ("mfspr %0,22" : "=r" (t));
897 /* Code not used because this is not accessible from userland */
899 __asm__ __volatile__ ("mfc0\t%0,$9" : "=r" (t));
902 /* This doesn't compile on all platforms yet. How to fix? */
904 __asm__ __volatile__ ("rd %%tick, %0" : "=r" (t));
906 signal (SIGILL, old_handler[0]);
907 signal (SIGSEGV, old_handler[1]);
908 isaac_seed_data (s, &t, sizeof t);
912 #else /* !(__i386__ || __alpha__) */
914 /* Do-nothing stub */
915 # define isaac_seed_machdep(s) (void) 0
917 #endif /* !(__i386__ || __alpha__) */
921 * Get seed material. 16 bytes (128 bits) is plenty, but if we have
922 * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
925 isaac_seed (struct isaac_state *s)
927 isaac_seed_start (s);
929 { pid_t t = getpid (); ISAAC_SEED (s, t); }
930 { pid_t t = getppid (); ISAAC_SEED (s, t); }
931 { uid_t t = getuid (); ISAAC_SEED (s, t); }
932 { gid_t t = getgid (); ISAAC_SEED (s, t); }
936 hrtime_t t = gethrtime ();
939 # if HAVE_CLOCK_GETTIME /* POSIX ns-resolution */
941 clock_gettime (CLOCK_REALTIME, &t);
943 # if HAVE_GETTIMEOFDAY
945 gettimeofday (&t, (struct timezone *) 0);
948 t = time ((time_t *) 0);
955 isaac_seed_machdep (s);
959 int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
964 isaac_seed_data (s, buf, 32);
968 fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
971 /* /dev/random is more precious, so use less */
974 isaac_seed_data (s, buf, 16);
979 isaac_seed_finish (s);
982 /* Single-word RNG built on top of ISAAC */
985 word32 r[ISAAC_WORDS];
987 struct isaac_state *s;
991 irand_init (struct irand_state *r, struct isaac_state *s)
998 * We take from the end of the block deliberately, so if we need
999 * only a small number of values, we choose the final ones which are
1000 * marginally better mixed than the initial ones.
1003 irand32 (struct irand_state *r)
1007 isaac_refill (r->s, r->r);
1008 r->numleft = ISAAC_WORDS;
1010 return r->r[--r->numleft];
1014 * Return a uniformly distributed random number between 0 and n,
1015 * inclusive. Thus, the result is modulo n+1.
1017 * Theory of operation: as x steps through every possible 32-bit number,
1018 * x % n takes each value at least 2^32 / n times (rounded down), but
1019 * the values less than 2^32 % n are taken one additional time. Thus,
1020 * x % n is not perfectly uniform. To fix this, the values of x less
1021 * than 2^32 % n are disallowed, and if the RNG produces one, we ask
1025 irand_mod (struct irand_state *r, word32 n)
1033 lim = -n % n; /* == (2**32-n) % n == 2**32 % n */
1043 * Fill a buffer with a fixed pattern.
1045 * The buffer must be at least 3 bytes long, even if
1046 * size is less. Larger sizes are filled exactly.
1049 fillpattern (int type, unsigned char *r, size_t size)
1052 unsigned bits = type & 0xfff;
1055 ((unsigned char *) r)[0] = (bits >> 4) & 255;
1056 ((unsigned char *) r)[1] = (bits >> 8) & 255;
1057 ((unsigned char *) r)[2] = bits & 255;
1058 for (i = 3; i < size / 2; i *= 2)
1059 memcpy ((char *) r + i, (char *) r, i);
1061 memcpy ((char *) r + i, (char *) r, size - i);
1063 /* Invert the first bit of every 512-byte sector. */
1065 for (i = 0; i < size; i += 512)
1070 * Fill a buffer, R (of size SIZE_MAX), with random data.
1071 * SIZE is rounded UP to a multiple of ISAAC_BYTES.
1074 fillrand (struct isaac_state *s, word32 *r, size_t size_max, size_t size)
1076 size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
1077 assert (size <= size_max);
1081 isaac_refill (s, r);
1087 * Generate a 6-character (+ nul) pass name string
1088 * FIXME: allow translation of "random".
1090 #define PASS_NAME_SIZE 7
1092 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
1095 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
1097 memcpy (name, "random", PASS_NAME_SIZE);
1101 * Do pass number k of n, writing "size" bytes of the given pattern "type"
1102 * to the file descriptor fd. Qname, k and n are passed in only for verbose
1103 * progress message purposes. If n == 0, no progress messages are printed.
1105 * If *sizep == -1, the size is unknown, and it will be filled in as soon
1109 dopass (int fd, char const *qname, off_t *sizep, int type,
1110 struct isaac_state *s, unsigned long k, unsigned long n)
1112 off_t size = *sizep;
1113 off_t offset; /* Current file posiiton */
1114 off_t thresh; /* Offset to print next status update */
1115 size_t lim; /* Amount of data to try writing */
1116 size_t soff; /* Offset into buffer for next write */
1117 ssize_t ssize; /* Return value from write */
1118 #if ISAAC_WORDS > 1024
1119 word32 r[ISAAC_WORDS * 3]; /* Multiple of 4K and of pattern size */
1121 word32 r[1024 * 3]; /* Multiple of 4K and of pattern size */
1123 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
1125 if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
1127 error (0, errno, _("%s: cannot rewind"), qname);
1131 /* Constant fill patterns need only be set up once. */
1135 if ((off_t) lim > size && size != -1)
1137 lim = (size_t) size;
1139 fillpattern (type, (unsigned char *) r, lim);
1140 passname ((unsigned char *) r, pass_string);
1144 passname (0, pass_string);
1147 /* Set position if first status update */
1151 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
1152 thresh = VERBOSE_UPDATE;
1153 if (thresh > size && size != -1)
1160 /* How much to write this time? */
1162 if ((off_t) lim > size - offset && size != -1)
1166 lim = (size_t) (size - offset);
1171 fillrand (s, r, sizeof r, lim);
1172 /* Loop to retry partial writes. */
1173 for (soff = 0; soff < lim; soff += ssize)
1175 ssize = write (fd, (char *) r + soff, lim - soff);
1178 if ((ssize == 0 || errno == ENOSPC)
1181 /* Ah, we have found the end of the file */
1182 *sizep = thresh = size = offset + soff;
1188 char buf[LONGEST_HUMAN_READABLE + 1];
1189 error (0, errnum, _("%s: error writing at offset %s"),
1191 human_readable ((uintmax_t) (offset + soff),
1194 * I sometimes use shred on bad media, before throwing it
1195 * out. Thus, I don't want it to give up on bad blocks.
1196 * This code assumes 512-byte blocks and tries to skip
1197 * over them. It works because lim is always a multiple
1198 * of 512, except at the end.
1200 if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
1203 if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
1209 error (0, errno, "%s: lseek", qname);
1216 /* Okay, we have written "lim" bytes. */
1218 if (offset + lim < offset)
1220 error (0, 0, _("%s: file too large"), qname);
1226 /* Time to print progress? */
1227 if (offset >= thresh && n)
1229 char offset_buf[LONGEST_HUMAN_READABLE + 1];
1230 char size_buf[LONGEST_HUMAN_READABLE + 1];
1231 char const *human_offset
1232 = human_readable ((uintmax_t) offset, offset_buf, 1,
1235 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s"), qname, k, n,
1236 pass_string, human_offset,
1237 human_readable ((uintmax_t) size, size_buf, 1,
1238 OUTPUT_BLOCK_SIZE));
1240 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), qname, k, n,
1241 pass_string, human_offset);
1243 thresh += VERBOSE_UPDATE;
1244 if (thresh > size && size != -1)
1247 * Force periodic syncs to keep displayed progress accurate
1248 * FIXME: Should these be present even if -v is not enabled,
1249 * to keep the buffer cache from filling with dirty pages?
1250 * It's a common problem with programs that do lots of writes,
1253 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1255 error (0, errno, "%s: fsync", qname);
1261 /* Force what we just wrote to hit the media. */
1262 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1264 error (0, errno, "%s: fsync", qname);
1271 * The passes start and end with a random pass, and the passes in between
1272 * are done in random order. The idea is to deprive someone trying to
1273 * reverse the process of knowledge of the overwrite patterns, so they
1274 * have the additional step of figuring out what was done to the disk
1275 * before they can try to reverse or cancel it.
1277 * First, all possible 1-bit patterns. There are two of them.
1278 * Then, all possible 2-bit patterns. There are four, but the two
1279 * which are also 1-bit patterns can be omitted.
1280 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
1281 * Then, all possible 4-bit patterns. 16-4 = 12.
1283 * The basic passes are:
1284 * 1-bit: 0x000, 0xFFF
1285 * 2-bit: 0x555, 0xAAA
1286 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
1287 * 100100100100 110110110110
1289 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1290 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
1291 * Adding three random passes at the beginning, middle and end
1292 * produces the default 25-pass structure.
1294 * The next extension would be to 5-bit and 6-bit patterns.
1295 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
1296 * 6-bit patterns, so they would increase the time required
1297 * significantly. 4-bit patterns are enough for most purposes.
1299 * The main gotcha is that this would require a trickier encoding,
1300 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
1301 * lcm(2,3,4,5) = 60 bits is not.
1303 * One extension that is included is to complement the first bit in each
1304 * 512-byte block, to alter the phase of the encoded data in the more
1305 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
1306 * are considered part of the 3-bit ones and the 2-bit patterns are
1307 * considered part of the 4-bit patterns.
1310 * How does the generalization to variable numbers of passes work?
1313 * Have an ordered list of groups of passes. Each group is a set.
1314 * Take as many groups as will fit, plus a random subset of the
1315 * last partial group, and place them into the passes list.
1316 * Then shuffle the passes list into random order and use that.
1318 * One extra detail: if we can't include a large enough fraction of the
1319 * last group to be interesting, then just substitute random passes.
1321 * If you want more passes than the entire list of groups can
1322 * provide, just start repeating from the beginning of the list.
1327 -2, /* 2 random passes */
1328 2, 0x000, 0xFFF, /* 1-bit */
1329 2, 0x555, 0xAAA, /* 2-bit */
1330 -1, /* 1 random pass */
1331 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
1332 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1333 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
1334 -1, /* 1 random pass */
1335 /* The following patterns have the frst bit per block flipped */
1336 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1337 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1338 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1339 -1, /* 1 random pass */
1344 * Generate a random wiping pass pattern with num passes.
1345 * This is a two-stage process. First, the passes to include
1346 * are chosen, and then they are shuffled into the desired
1350 genpattern (int *dest, size_t num, struct isaac_state *s)
1352 struct irand_state r;
1357 size_t accum, top, swap;
1365 /* Stage 1: choose the passes to use */
1368 d = dest; /* Destination for generated pass list */
1369 n = num; /* Passes remaining to fill */
1373 k = *p++; /* Block descriptor word */
1375 { /* Loop back to the beginning */
1379 { /* -k random passes */
1381 if ((size_t) k >= n)
1390 else if ((size_t) k <= n)
1391 { /* Full block of patterns */
1392 memcpy (d, p, k * sizeof (int));
1397 else if (n < 2 || 3 * n < (size_t) k)
1398 { /* Finish with random */
1403 { /* Pad out with k of the n available */
1406 if (n == (size_t) k-- || irand_mod (&r, k) < n)
1417 top = num - randpasses; /* Top of initialized data */
1418 /* assert (d == dest+top); */
1421 * We now have fixed patterns in the dest buffer up to
1422 * "top", and we need to scramble them, with "randpasses"
1423 * random passes evenly spaced among them.
1425 * We want one at the beginning, one at the end, and
1426 * evenly spaced in between. To do this, we basically
1427 * use Bresenham's line draw (a.k.a DDA) algorithm
1428 * to draw a line with slope (randpasses-1)/(num-1).
1429 * (We use a positive accumulator and count down to
1432 * So for each desired output value, we do the following:
1433 * - If it should be a random pass, copy the pass type
1434 * to top++, out of the way of the other passes, and
1435 * set the current pass to -1 (random).
1436 * - If it should be a normal pattern pass, choose an
1437 * entry at random between here and top-1 (inclusive)
1438 * and swap the current entry with that one.
1440 randpasses--; /* To speed up later math */
1441 accum = randpasses; /* Bresenham DDA accumulator */
1442 for (n = 0; n < num; n++)
1444 if (accum <= randpasses)
1447 dest[top++] = dest[n];
1452 swap = n + irand_mod (&r, top - n - 1);
1454 dest[n] = dest[swap];
1457 accum -= randpasses;
1459 /* assert (top == num); */
1461 memset (&r, 0, sizeof r); /* Wipe this on general principles */
1465 * The core routine to actually do the work. This overwrites the first
1466 * size bytes of the given fd. Returns -1 on error, 0 on success.
1469 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1470 struct Options const *flags)
1474 off_t size; /* Size to write, size to read */
1475 unsigned long n; /* Number of passes for printing purposes */
1478 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
1480 n = flags->n_iterations + ((flags->zero_fill) != 0);
1482 if (fstat (fd, &st))
1484 error (0, errno, "%s: fstat", qname);
1488 /* If we know that we can't possibly shred the file, give up now.
1489 Otherwise, we may go into a infinite loop writing data before we
1490 find that we can't rewind the device. */
1491 if ((S_ISCHR (st.st_mode) && isatty (fd))
1492 || S_ISFIFO (st.st_mode)
1493 || S_ISSOCK (st.st_mode))
1495 error (0, 0, _("%s: invalid file type"), qname);
1499 /* Allocate pass array */
1500 passarray = xmalloc (flags->n_iterations * sizeof (int));
1505 /* Accept a length of zero only if it's a regular file.
1506 For any other type of file, try to get the size another way. */
1507 if (S_ISREG (st.st_mode))
1512 error (0, 0, _("%s: file has negative size"), qname);
1518 size = lseek (fd, (off_t) 0, SEEK_END);
1521 /* We are unable to determine the length, up front.
1522 Let dopass do that as part of its first iteration. */
1527 if (0 <= size && !(flags->exact))
1529 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1531 /* If in rounding up, we've just overflowed, use the maximum. */
1533 size = TYPE_MAXIMUM (off_t);
1537 /* Schedule the passes in random order. */
1538 genpattern (passarray, flags->n_iterations, s);
1541 for (i = 0; i < flags->n_iterations; i++)
1543 if (dopass (fd, qname, &size, passarray[i], s, i + 1, n) < 0)
1545 memset (passarray, 0, flags->n_iterations * sizeof (int));
1551 memset (passarray, 0, flags->n_iterations * sizeof (int));
1554 if (flags->zero_fill)
1555 if (dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n) < 0)
1558 /* Okay, now deallocate the data. The effect of ftruncate on
1559 non-regular files is unspecified, so don't worry about any
1560 errors reported for them. */
1561 if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1562 && S_ISREG (st.st_mode))
1564 error (0, errno, _("%s: error truncating"), qname);
1571 /* A wrapper with a little more checking for fds on the command line */
1573 wipefd (int fd, char const *qname, struct isaac_state *s,
1574 struct Options const *flags)
1576 int fd_flags = fcntl (fd, F_GETFL);
1580 error (0, errno, "%s: fcntl", qname);
1583 if (fd_flags & O_APPEND)
1585 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1588 return do_wipefd (fd, qname, s, flags);
1591 /* --- Name-wiping code --- */
1593 /* Characters allowed in a file name - a safe universal set. */
1594 static char const nameset[] =
1595 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+=%@#.";
1598 * This increments the name, considering it as a big-endian base-N number
1599 * with the digits taken from nameset. Characters not in the nameset
1600 * are considered to come before nameset[0].
1602 * It's not obvious, but this will explode if name[0..len-1] contains
1605 * This returns the carry (1 on overflow).
1608 incname (char *name, unsigned len)
1615 p = strchr (nameset, name[--len]);
1616 /* If the character is not found, replace it with a 0 digit */
1619 name[len] = nameset[0];
1622 /* If this character has a successor, use it */
1628 /* Otherwise, set this digit to 0 and increment the prefix */
1629 name[len] = nameset[0];
1630 return incname (name, len);
1634 * Repeatedly rename a file with shorter and shorter names,
1635 * to obliterate all traces of the file name on any system that
1636 * adds a trailing delimiter to on-disk file names and reuses
1637 * the same directory slot. Finally, unlink it.
1638 * The passed-in filename is modified in place to the new filename.
1639 * (Which is unlinked if this function succeeds, but is still present if
1640 * it fails for some reason.)
1642 * The main loop is written carefully to not get stuck if all possible
1643 * names of a given length are occupied. It counts down the length from
1644 * the original to 0. While the length is non-zero, it tries to find an
1645 * unused file name of the given length. It continues until either the
1646 * name is available and the rename succeeds, or it runs out of names
1647 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1649 * The unlink is Unix-specific, as ANSI-standard remove has more
1650 * portability problems with C libraries making it "safe". rename
1653 * To force the directory data out, we try to open the directory and
1654 * invoke fdatasync on it. This is rather non-standard, so we don't
1655 * insist that it works, just fall back to a global sync in that case.
1656 * This is fairly significantly Unix-specific. Of course, on any
1657 * filesystem with synchronous metadata updates, this is unnecessary.
1660 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1662 char *newname, *base; /* Base points to filename part of newname */
1665 int dir_fd; /* Try to open directory to sync *it* */
1667 newname = xstrdup (oldname);
1669 error (0, 0, _("%s: removing"), qoldname);
1671 /* Find the file name portion */
1672 base = strrchr (newname, '/');
1673 /* Temporary hackery to get a directory fd */
1677 dir_fd = open (newname, O_RDONLY | O_NOCTTY);
1682 dir_fd = open (".", O_RDONLY | O_NOCTTY);
1684 base = base ? base + 1 : newname;
1685 len = strlen (base);
1689 memset (base, nameset[0], len);
1694 if (lstat (newname, &st) < 0)
1696 if (rename (oldname, newname) == 0)
1699 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1700 sync (); /* Force directory out */
1704 * People seem to understand this better than talking
1705 * about renaming oldname. newname doesn't need
1706 * quoting because we picked it.
1708 error (0, 0, _("%s: renamed to %s"), qoldname,
1711 memcpy (oldname + (base - newname), base, len + 1);
1716 /* The rename failed: give up on this length. */
1722 /* newname exists, so increment BASE so we use another */
1725 while (!incname (base, len));
1729 err = unlink (oldname);
1730 if (dir_fd < 0 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1733 if (!err && flags->verbose)
1734 error (0, 0, _("%s: removed"), qoldname);
1739 * Finally, the function that actually takes a filename and grinds
1740 * it into hamburger.
1743 * Detail to note: since we do not restore errno to EACCES after
1744 * a failed chmod, we end up printing the error code from the chmod.
1745 * This is actually the error that stopped us from proceeding, so
1746 * it's arguably the right one, and in practice it'll be either EACCES
1747 * again or EPERM, which both give similar error messages.
1748 * Does anyone disagree?
1751 wipefile (char *name, char const *qname,
1752 struct isaac_state *s, struct Options const *flags)
1756 fd = open (name, O_WRONLY | O_NOCTTY);
1759 if (errno == EACCES && flags->force)
1761 if (chmod (name, S_IWUSR) >= 0) /* 0200, user-write-only */
1762 fd = open (name, O_WRONLY | O_NOCTTY);
1764 else if ((errno == ENOENT || errno == ENOTDIR)
1765 && strncmp (name, "/dev/fd/", 8) == 0)
1767 /* We accept /dev/fd/# even if the OS doesn't support it */
1772 num = strtoul (name + 8, &p, 10);
1773 /* If it's completely decimal with no leading zeros... */
1774 if (errno == 0 && !*p && num <= INT_MAX &&
1775 (('1' <= name[8] && name[8] <= '9')
1776 || (name[8] == '0' && !name[9])))
1778 return wipefd ((int) num, qname, s, flags);
1785 error (0, errno, "%s", qname);
1789 err = do_wipefd (fd, qname, s, flags);
1790 if (close (fd) != 0)
1792 error (0, 0, "%s: close", qname);
1795 if (err == 0 && flags->remove_file)
1797 err = wipename (name, qname, flags);
1799 error (0, 0, _("%s: cannot remove"), qname);
1805 main (int argc, char **argv)
1807 struct isaac_state s;
1809 struct Options flags;
1815 program_name = argv[0];
1816 setlocale (LC_ALL, "");
1817 bindtextdomain (PACKAGE, LOCALEDIR);
1818 textdomain (PACKAGE);
1820 atexit (close_stdout);
1824 memset (&flags, 0, sizeof flags);
1826 flags.n_iterations = DEFAULT_PASSES;
1829 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1843 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1844 || (word32) tmp != tmp
1845 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1847 error (1, 0, _("%s: invalid number of passes"),
1848 quotearg_colon (optarg));
1850 flags.n_iterations = (size_t) tmp;
1855 flags.remove_file = 1;
1861 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0")
1864 error (1, 0, _("%s: invalid file size"),
1865 quotearg_colon (optarg));
1880 flags.zero_fill = 1;
1883 case_GETOPT_HELP_CHAR;
1885 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1892 file = argv + optind;
1893 n_files = argc - optind;
1897 error (0, 0, _("missing file argument"));
1901 for (i = 0; i < n_files; i++)
1903 char const *qname = quotearg_colon (file[i]);
1904 if (strcmp (file[i], "-") == 0)
1906 if (wipefd (STDOUT_FILENO, qname, &s, &flags) < 0)
1911 /* Plain filename - Note that this overwrites *argv! */
1912 if (wipefile (file[i], qname, &s, &flags) < 0)
1917 /* Just on general principles, wipe s. */
1918 memset (&s, 0, sizeof s);