version 8.26
[coreutils.git] / src / shred.c
blobf32a5b8347c076cbe82951a46d2ee91aaa691683
1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2016 Free Software Foundation, Inc.
4 Copyright (C) 1997, 1998, 1999 Colin Plumb.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 Written by Colin Plumb. */
22 * Do a more secure overwrite of given files or devices, to make it harder
23 * for even very expensive hardware probing to recover the data.
25 * Although this process is also known as "wiping", I prefer the longer
26 * name both because I think it is more evocative of what is happening and
27 * because a longer name conveys a more appropriate sense of deliberateness.
29 * For the theory behind this, see "Secure Deletion of Data from Magnetic
30 * and Solid-State Memory", on line at
31 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
33 * Just for the record, reversing one or two passes of disk overwrite
34 * is not terribly difficult with hardware help. Hook up a good-quality
35 * digitizing oscilloscope to the output of the head preamplifier and copy
36 * the high-res digitized data to a computer for some off-line analysis.
37 * Read the "current" data and average all the pulses together to get an
38 * "average" pulse on the disk. Subtract this average pulse from all of
39 * the actual pulses and you can clearly see the "echo" of the previous
40 * data on the disk.
42 * Real hard drives have to balance the cost of the media, the head,
43 * and the read circuitry. They use better-quality media than absolutely
44 * necessary to limit the cost of the read circuitry. By throwing that
45 * assumption out, and the assumption that you want the data processed
46 * as fast as the hard drive can spin, you can do better.
48 * If asked to wipe a file, this also unlinks it, renaming it to in a
49 * clever way to try to leave no trace of the original filename.
51 * This was inspired by a desire to improve on some code titled:
52 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
53 * but I've rewritten everything here so completely that no trace of
54 * the original remains.
56 * Thanks to:
57 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
58 * paperwork.
59 * Jim Meyering, for his work merging this into the GNU fileutils while
60 * still letting me feel a sense of ownership and pride. Getting me to
61 * tolerate the GNU brace style was quite a feat of diplomacy.
62 * Paul Eggert, for lots of useful discussion and code. I disagree with
63 * an awful lot of his suggestions, but they're disagreements worth having.
65 * Things to think about:
66 * - Security: Is there any risk to the race
67 * between overwriting and unlinking a file? Will it do anything
68 * drastically bad if told to attack a named pipe or socket?
71 /* The official name of this program (e.g., no 'g' prefix). */
72 #define PROGRAM_NAME "shred"
74 #define AUTHORS proper_name ("Colin Plumb")
76 #include <config.h>
78 #include <getopt.h>
79 #include <stdio.h>
80 #include <assert.h>
81 #include <setjmp.h>
82 #include <sys/types.h>
83 #ifdef __linux__
84 # include <sys/mtio.h>
85 #endif
87 #include "system.h"
88 #include "argmatch.h"
89 #include "xdectoint.h"
90 #include "die.h"
91 #include "error.h"
92 #include "fcntl--.h"
93 #include "human.h"
94 #include "randint.h"
95 #include "randread.h"
96 #include "stat-size.h"
98 /* Default number of times to overwrite. */
99 enum { DEFAULT_PASSES = 3 };
101 /* How many seconds to wait before checking whether to output another
102 verbose output line. */
103 enum { VERBOSE_UPDATE = 5 };
105 /* Sector size and corresponding mask, for recovering after write failures.
106 The size must be a power of 2. */
107 enum { SECTOR_SIZE = 512 };
108 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
109 verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
111 enum remove_method
113 remove_none = 0, /* the default: only wipe data. */
114 remove_unlink, /* don't obfuscate name, just unlink. */
115 remove_wipe, /* obfuscate name before unlink. */
116 remove_wipesync /* obfuscate name, syncing each byte, before unlink. */
119 static char const *const remove_args[] =
121 "unlink", "wipe", "wipesync", NULL
124 static enum remove_method const remove_methods[] =
126 remove_unlink, remove_wipe, remove_wipesync
129 struct Options
131 bool force; /* -f flag: chmod files if necessary */
132 size_t n_iterations; /* -n flag: Number of iterations */
133 off_t size; /* -s flag: size of file */
134 enum remove_method remove_file; /* -u flag: remove file after shredding */
135 bool verbose; /* -v flag: Print progress */
136 bool exact; /* -x flag: Do not round up file size */
137 bool zero_fill; /* -z flag: Add a final zero pass */
140 /* For long options that have no equivalent short option, use a
141 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
142 enum
144 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
147 static struct option const long_opts[] =
149 {"exact", no_argument, NULL, 'x'},
150 {"force", no_argument, NULL, 'f'},
151 {"iterations", required_argument, NULL, 'n'},
152 {"size", required_argument, NULL, 's'},
153 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
154 {"remove", optional_argument, NULL, 'u'},
155 {"verbose", no_argument, NULL, 'v'},
156 {"zero", no_argument, NULL, 'z'},
157 {GETOPT_HELP_OPTION_DECL},
158 {GETOPT_VERSION_OPTION_DECL},
159 {NULL, 0, NULL, 0}
162 void
163 usage (int status)
165 if (status != EXIT_SUCCESS)
166 emit_try_help ();
167 else
169 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
170 fputs (_("\
171 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
172 for even very expensive hardware probing to recover the data.\n\
173 "), stdout);
174 fputs (_("\
176 If FILE is -, shred standard output.\n\
177 "), stdout);
179 emit_mandatory_arg_note ();
181 printf (_("\
182 -f, --force change permissions to allow writing if necessary\n\
183 -n, --iterations=N overwrite N times instead of the default (%d)\n\
184 --random-source=FILE get random bytes from FILE\n\
185 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
186 "), DEFAULT_PASSES);
187 fputs (_("\
188 -u truncate and remove file after overwriting\n\
189 --remove[=HOW] like -u but give control on HOW to delete; See below\n\
190 -v, --verbose show progress\n\
191 -x, --exact do not round file sizes up to the next full block;\n\
192 this is the default for non-regular files\n\
193 -z, --zero add a final overwrite with zeros to hide shredding\n\
194 "), stdout);
195 fputs (HELP_OPTION_DESCRIPTION, stdout);
196 fputs (VERSION_OPTION_DESCRIPTION, stdout);
197 fputs (_("\
199 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
200 the files because it is common to operate on device files like /dev/hda,\n\
201 and those files usually should not be removed.\n\
202 The optional HOW parameter indicates how to remove a directory entry:\n\
203 'unlink' => use a standard unlink call.\n\
204 'wipe' => also first obfuscate bytes in the name.\n\
205 'wipesync' => also sync each obfuscated byte to disk.\n\
206 The default mode is 'wipesync', but note it can be expensive.\n\
208 "), stdout);
209 fputs (_("\
210 CAUTION: Note that shred relies on a very important assumption:\n\
211 that the file system overwrites data in place. This is the traditional\n\
212 way to do things, but many modern file system designs do not satisfy this\n\
213 assumption. The following are examples of file systems on which shred is\n\
214 not effective, or is not guaranteed to be effective in all file system modes:\n\
216 "), stdout);
217 fputs (_("\
218 * log-structured or journaled file systems, such as those supplied with\n\
219 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
221 * file systems that write redundant data and carry on even if some writes\n\
222 fail, such as RAID-based file systems\n\
224 * file systems that make snapshots, such as Network Appliance's NFS server\n\
226 "), stdout);
227 fputs (_("\
228 * file systems that cache in temporary locations, such as NFS\n\
229 version 3 clients\n\
231 * compressed file systems\n\
233 "), stdout);
234 fputs (_("\
235 In the case of ext3 file systems, the above disclaimer applies\n\
236 (and shred is thus of limited effectiveness) only in data=journal mode,\n\
237 which journals file data in addition to just metadata. In both the\n\
238 data=ordered (default) and data=writeback modes, shred works as usual.\n\
239 Ext3 journaling modes can be changed by adding the data=something option\n\
240 to the mount options for a particular file system in the /etc/fstab file,\n\
241 as documented in the mount man page (man mount).\n\
243 "), stdout);
244 fputs (_("\
245 In addition, file system backups and remote mirrors may contain copies\n\
246 of the file that cannot be removed, and that will allow a shredded file\n\
247 to be recovered later.\n\
248 "), stdout);
249 emit_ancillary_info (PROGRAM_NAME);
251 exit (status);
255 * Determine if pattern type is periodic or not.
257 static bool
258 periodic_pattern (int type)
260 if (type <= 0)
261 return false;
263 unsigned char r[3];
264 unsigned int bits = type & 0xfff;
266 bits |= bits << 12;
267 r[0] = (bits >> 4) & 255;
268 r[1] = (bits >> 8) & 255;
269 r[2] = bits & 255;
271 return (r[0] != r[1]) || (r[0] != r[2]);
275 * Fill a buffer with a fixed pattern.
277 * The buffer must be at least 3 bytes long, even if
278 * size is less. Larger sizes are filled exactly.
280 static void
281 fillpattern (int type, unsigned char *r, size_t size)
283 size_t i;
284 unsigned int bits = type & 0xfff;
286 bits |= bits << 12;
287 r[0] = (bits >> 4) & 255;
288 r[1] = (bits >> 8) & 255;
289 r[2] = bits & 255;
290 for (i = 3; i < size / 2; i *= 2)
291 memcpy (r + i, r, i);
292 if (i < size)
293 memcpy (r + i, r, size - i);
295 /* Invert the first bit of every sector. */
296 if (type & 0x1000)
297 for (i = 0; i < size; i += SECTOR_SIZE)
298 r[i] ^= 0x80;
302 * Generate a 6-character (+ nul) pass name string
303 * FIXME: allow translation of "random".
305 #define PASS_NAME_SIZE 7
306 static void
307 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
309 if (data)
310 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
311 else
312 memcpy (name, "random", PASS_NAME_SIZE);
315 /* Return true when it's ok to ignore an fsync or fdatasync
316 failure that set errno to ERRNO_VAL. */
317 static bool
318 ignorable_sync_errno (int errno_val)
320 return (errno_val == EINVAL
321 || errno_val == EBADF
322 /* HP-UX does this */
323 || errno_val == EISDIR);
326 /* Request that all data for FD be transferred to the corresponding
327 storage device. QNAME is the file name (quoted for colons).
328 Report any errors found. Return 0 on success, -1
329 (setting errno) on failure. It is not an error if fdatasync and/or
330 fsync is not supported for this file, or if the file is not a
331 writable file descriptor. */
332 static int
333 dosync (int fd, char const *qname)
335 int err;
337 #if HAVE_FDATASYNC
338 if (fdatasync (fd) == 0)
339 return 0;
340 err = errno;
341 if ( ! ignorable_sync_errno (err))
343 error (0, err, _("%s: fdatasync failed"), qname);
344 errno = err;
345 return -1;
347 #endif
349 if (fsync (fd) == 0)
350 return 0;
351 err = errno;
352 if ( ! ignorable_sync_errno (err))
354 error (0, err, _("%s: fsync failed"), qname);
355 errno = err;
356 return -1;
359 sync ();
360 return 0;
363 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
364 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
365 static void
366 direct_mode (int fd, bool enable)
368 if (O_DIRECT)
370 int fd_flags = fcntl (fd, F_GETFL);
371 if (0 < fd_flags)
373 int new_flags = (enable
374 ? (fd_flags | O_DIRECT)
375 : (fd_flags & ~O_DIRECT));
376 if (new_flags != fd_flags)
377 fcntl (fd, F_SETFL, new_flags);
381 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
382 /* This is Solaris-specific. See the following for details:
383 http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view */
384 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
385 #endif
388 /* Rewind FD; its status is ST. */
389 static bool
390 dorewind (int fd, struct stat const *st)
392 if (S_ISCHR (st->st_mode))
394 #ifdef __linux__
395 /* In the Linux kernel, lseek does not work on tape devices; it
396 returns a randomish value instead. Try the low-level tape
397 rewind operation first. */
398 struct mtop op;
399 op.mt_op = MTREW;
400 op.mt_count = 1;
401 if (ioctl (fd, MTIOCTOP, &op) == 0)
402 return true;
403 #endif
405 off_t offset = lseek (fd, 0, SEEK_SET);
406 if (0 < offset)
407 errno = EINVAL;
408 return offset == 0;
411 /* By convention, negative sizes represent unknown values. */
413 static bool
414 known (off_t size)
416 return 0 <= size;
420 * Do pass number K of N, writing *SIZEP bytes of the given pattern TYPE
421 * to the file descriptor FD. K and N are passed in only for verbose
422 * progress message purposes. If N == 0, no progress messages are printed.
424 * If *SIZEP == -1, the size is unknown, and it will be filled in as soon
425 * as writing fails with ENOSPC.
427 * Return 1 on write error, -1 on other error, 0 on success.
429 static int
430 dopass (int fd, struct stat const *st, char const *qname, off_t *sizep,
431 int type, struct randread_source *s,
432 unsigned long int k, unsigned long int n)
434 off_t size = *sizep;
435 off_t offset; /* Current file position */
436 time_t thresh IF_LINT ( = 0); /* Time to maybe print next status update */
437 time_t now = 0; /* Current time */
438 size_t lim; /* Amount of data to try writing */
439 size_t soff; /* Offset into buffer for next write */
440 ssize_t ssize; /* Return value from write */
442 /* Fill pattern buffer. Aligning it to a page so we can do direct I/O. */
443 size_t page_size = getpagesize ();
444 #define PERIODIC_OUTPUT_SIZE (60 * 1024)
445 #define NONPERIODIC_OUTPUT_SIZE (64 * 1024)
446 verify (PERIODIC_OUTPUT_SIZE % 3 == 0);
447 size_t output_size = periodic_pattern (type)
448 ? PERIODIC_OUTPUT_SIZE : NONPERIODIC_OUTPUT_SIZE;
449 #define PAGE_ALIGN_SLOP (page_size - 1) /* So directio works */
450 #define FILLPATTERN_SIZE (((output_size + 2) / 3) * 3) /* Multiple of 3 */
451 #define PATTERNBUF_SIZE (PAGE_ALIGN_SLOP + FILLPATTERN_SIZE)
452 void *fill_pattern_mem = xmalloc (PATTERNBUF_SIZE);
453 unsigned char *pbuf = ptr_align (fill_pattern_mem, page_size);
455 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
456 bool write_error = false;
457 bool other_error = false;
459 /* Printable previous offset into the file */
460 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
461 char const *previous_human_offset IF_LINT ( = 0);
463 /* As a performance tweak, avoid direct I/O for small sizes,
464 as it's just a performance rather then security consideration,
465 and direct I/O can often be unsupported for small non aligned sizes. */
466 bool try_without_directio = 0 < size && size < output_size;
467 if (! try_without_directio)
468 direct_mode (fd, true);
470 if (! dorewind (fd, st))
472 error (0, errno, _("%s: cannot rewind"), qname);
473 other_error = true;
474 goto free_pattern_mem;
477 /* Constant fill patterns need only be set up once. */
478 if (type >= 0)
480 lim = known (size) && size < FILLPATTERN_SIZE ? size : FILLPATTERN_SIZE;
481 fillpattern (type, pbuf, lim);
482 passname (pbuf, pass_string);
484 else
486 passname (0, pass_string);
489 /* Set position if first status update */
490 if (n)
492 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
493 thresh = time (NULL) + VERBOSE_UPDATE;
494 previous_human_offset = "";
497 offset = 0;
498 while (true)
500 /* How much to write this time? */
501 lim = output_size;
502 if (known (size) && size - offset < output_size)
504 if (size < offset)
505 break;
506 lim = size - offset;
507 if (!lim)
508 break;
510 if (type < 0)
511 randread (s, pbuf, lim);
512 /* Loop to retry partial writes. */
513 for (soff = 0; soff < lim; soff += ssize)
515 ssize = write (fd, pbuf + soff, lim - soff);
516 if (0 < ssize)
517 assume (ssize <= lim - soff);
518 else
520 if (! known (size) && (ssize == 0 || errno == ENOSPC))
522 /* We have found the end of the file. */
523 if (soff <= OFF_T_MAX - offset)
524 *sizep = size = offset + soff;
525 break;
527 else
529 int errnum = errno;
530 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
532 /* Retry without direct I/O since this may not be supported
533 at all on some (file) systems, or with the current size.
534 I.e., a specified --size that is not aligned, or when
535 dealing with slop at the end of a file with --exact. */
536 if (! try_without_directio && errno == EINVAL)
538 direct_mode (fd, false);
539 ssize = 0;
540 try_without_directio = true;
541 continue;
543 error (0, errnum, _("%s: error writing at offset %s"),
544 qname, umaxtostr (offset + soff, buf));
546 /* 'shred' is often used on bad media, before throwing it
547 out. Thus, it shouldn't give up on bad blocks. This
548 code works because lim is always a multiple of
549 SECTOR_SIZE, except at the end. This size constraint
550 also enables direct I/O on some (file) systems. */
551 verify (PERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
552 verify (NONPERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
553 if (errnum == EIO && known (size)
554 && (soff | SECTOR_MASK) < lim)
556 size_t soff1 = (soff | SECTOR_MASK) + 1;
557 if (lseek (fd, offset + soff1, SEEK_SET) != -1)
559 /* Arrange to skip this block. */
560 ssize = soff1 - soff;
561 write_error = true;
562 continue;
564 error (0, errno, _("%s: lseek failed"), qname);
566 other_error = true;
567 goto free_pattern_mem;
572 /* Okay, we have written "soff" bytes. */
574 if (OFF_T_MAX - offset < soff)
576 error (0, 0, _("%s: file too large"), qname);
577 other_error = true;
578 goto free_pattern_mem;
581 offset += soff;
583 bool done = offset == size;
585 /* Time to print progress? */
586 if (n && ((done && *previous_human_offset)
587 || thresh <= (now = time (NULL))))
589 char offset_buf[LONGEST_HUMAN_READABLE + 1];
590 char size_buf[LONGEST_HUMAN_READABLE + 1];
591 int human_progress_opts = (human_autoscale | human_SI
592 | human_base_1024 | human_B);
593 char const *human_offset
594 = human_readable (offset, offset_buf,
595 human_floor | human_progress_opts, 1, 1);
597 if (done || !STREQ (previous_human_offset, human_offset))
599 if (! known (size))
600 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
601 qname, k, n, pass_string, human_offset);
602 else
604 uintmax_t off = offset;
605 int percent = (size == 0
606 ? 100
607 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
608 ? off * 100 / size
609 : off / (size / 100)));
610 char const *human_size
611 = human_readable (size, size_buf,
612 human_ceiling | human_progress_opts,
613 1, 1);
614 if (done)
615 human_offset = human_size;
616 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
617 qname, k, n, pass_string, human_offset, human_size,
618 percent);
621 strcpy (previous_offset_buf, human_offset);
622 previous_human_offset = previous_offset_buf;
623 thresh = now + VERBOSE_UPDATE;
626 * Force periodic syncs to keep displayed progress accurate
627 * FIXME: Should these be present even if -v is not enabled,
628 * to keep the buffer cache from filling with dirty pages?
629 * It's a common problem with programs that do lots of writes,
630 * like mkfs.
632 if (dosync (fd, qname) != 0)
634 if (errno != EIO)
636 other_error = true;
637 goto free_pattern_mem;
639 write_error = true;
645 /* Force what we just wrote to hit the media. */
646 if (dosync (fd, qname) != 0)
648 if (errno != EIO)
650 other_error = true;
651 goto free_pattern_mem;
653 write_error = true;
656 free_pattern_mem:
657 memset (pbuf, 0, FILLPATTERN_SIZE);
658 free (fill_pattern_mem);
660 return other_error ? -1 : write_error;
664 * The passes start and end with a random pass, and the passes in between
665 * are done in random order. The idea is to deprive someone trying to
666 * reverse the process of knowledge of the overwrite patterns, so they
667 * have the additional step of figuring out what was done to the disk
668 * before they can try to reverse or cancel it.
670 * First, all possible 1-bit patterns. There are two of them.
671 * Then, all possible 2-bit patterns. There are four, but the two
672 * which are also 1-bit patterns can be omitted.
673 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
674 * Then, all possible 4-bit patterns. 16-4 = 12.
676 * The basic passes are:
677 * 1-bit: 0x000, 0xFFF
678 * 2-bit: 0x555, 0xAAA
679 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
680 * 100100100100 110110110110
681 * 9 2 4 D B 6
682 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
683 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
684 * Adding three random passes at the beginning, middle and end
685 * produces the default 25-pass structure.
687 * The next extension would be to 5-bit and 6-bit patterns.
688 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
689 * 6-bit patterns, so they would increase the time required
690 * significantly. 4-bit patterns are enough for most purposes.
692 * The main gotcha is that this would require a trickier encoding,
693 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
694 * lcm(2,3,4,5) = 60 bits is not.
696 * One extension that is included is to complement the first bit in each
697 * 512-byte block, to alter the phase of the encoded data in the more
698 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
699 * are considered part of the 3-bit ones and the 2-bit patterns are
700 * considered part of the 4-bit patterns.
703 * How does the generalization to variable numbers of passes work?
705 * Here's how...
706 * Have an ordered list of groups of passes. Each group is a set.
707 * Take as many groups as will fit, plus a random subset of the
708 * last partial group, and place them into the passes list.
709 * Then shuffle the passes list into random order and use that.
711 * One extra detail: if we can't include a large enough fraction of the
712 * last group to be interesting, then just substitute random passes.
714 * If you want more passes than the entire list of groups can
715 * provide, just start repeating from the beginning of the list.
717 static int const
718 patterns[] =
720 -2, /* 2 random passes */
721 2, 0x000, 0xFFF, /* 1-bit */
722 2, 0x555, 0xAAA, /* 2-bit */
723 -1, /* 1 random pass */
724 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
725 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
726 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
727 -1, /* 1 random pass */
728 /* The following patterns have the first bit per block flipped */
729 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
730 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
731 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
732 -1, /* 1 random pass */
733 0 /* End */
737 * Generate a random wiping pass pattern with num passes.
738 * This is a two-stage process. First, the passes to include
739 * are chosen, and then they are shuffled into the desired
740 * order.
742 static void
743 genpattern (int *dest, size_t num, struct randint_source *s)
745 size_t randpasses;
746 int const *p;
747 int *d;
748 size_t n;
749 size_t accum, top, swap;
750 int k;
752 if (!num)
753 return;
755 /* Stage 1: choose the passes to use */
756 p = patterns;
757 randpasses = 0;
758 d = dest; /* Destination for generated pass list */
759 n = num; /* Passes remaining to fill */
761 while (true)
763 k = *p++; /* Block descriptor word */
764 if (!k)
765 { /* Loop back to the beginning */
766 p = patterns;
768 else if (k < 0)
769 { /* -k random passes */
770 k = -k;
771 if ((size_t) k >= n)
773 randpasses += n;
774 break;
776 randpasses += k;
777 n -= k;
779 else if ((size_t) k <= n)
780 { /* Full block of patterns */
781 memcpy (d, p, k * sizeof (int));
782 p += k;
783 d += k;
784 n -= k;
786 else if (n < 2 || 3 * n < (size_t) k)
787 { /* Finish with random */
788 randpasses += n;
789 break;
791 else
792 { /* Pad out with n of the k available */
795 if (n == (size_t) k || randint_choose (s, k) < n)
797 *d++ = *p;
798 n--;
800 p++;
801 k--;
803 while (n);
804 break;
807 top = num - randpasses; /* Top of initialized data */
808 /* assert (d == dest+top); */
811 * We now have fixed patterns in the dest buffer up to
812 * "top", and we need to scramble them, with "randpasses"
813 * random passes evenly spaced among them.
815 * We want one at the beginning, one at the end, and
816 * evenly spaced in between. To do this, we basically
817 * use Bresenham's line draw (a.k.a DDA) algorithm
818 * to draw a line with slope (randpasses-1)/(num-1).
819 * (We use a positive accumulator and count down to
820 * do this.)
822 * So for each desired output value, we do the following:
823 * - If it should be a random pass, copy the pass type
824 * to top++, out of the way of the other passes, and
825 * set the current pass to -1 (random).
826 * - If it should be a normal pattern pass, choose an
827 * entry at random between here and top-1 (inclusive)
828 * and swap the current entry with that one.
830 randpasses--; /* To speed up later math */
831 accum = randpasses; /* Bresenham DDA accumulator */
832 for (n = 0; n < num; n++)
834 if (accum <= randpasses)
836 accum += num - 1;
837 dest[top++] = dest[n];
838 dest[n] = -1;
840 else
842 swap = n + randint_choose (s, top - n);
843 k = dest[n];
844 dest[n] = dest[swap];
845 dest[swap] = k;
847 accum -= randpasses;
849 /* assert (top == num); */
853 * The core routine to actually do the work. This overwrites the first
854 * size bytes of the given fd. Return true if successful.
856 static bool
857 do_wipefd (int fd, char const *qname, struct randint_source *s,
858 struct Options const *flags)
860 size_t i;
861 struct stat st;
862 off_t size; /* Size to write, size to read */
863 off_t i_size = 0; /* For small files, initial size to overwrite inode */
864 unsigned long int n; /* Number of passes for printing purposes */
865 int *passarray;
866 bool ok = true;
867 struct randread_source *rs;
869 n = 0; /* dopass takes n == 0 to mean "don't print progress" */
870 if (flags->verbose)
871 n = flags->n_iterations + flags->zero_fill;
873 if (fstat (fd, &st))
875 error (0, errno, _("%s: fstat failed"), qname);
876 return false;
879 /* If we know that we can't possibly shred the file, give up now.
880 Otherwise, we may go into an infinite loop writing data before we
881 find that we can't rewind the device. */
882 if ((S_ISCHR (st.st_mode) && isatty (fd))
883 || S_ISFIFO (st.st_mode)
884 || S_ISSOCK (st.st_mode))
886 error (0, 0, _("%s: invalid file type"), qname);
887 return false;
889 else if (S_ISREG (st.st_mode) && st.st_size < 0)
891 error (0, 0, _("%s: file has negative size"), qname);
892 return false;
895 /* Allocate pass array */
896 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
898 size = flags->size;
899 if (size == -1)
901 if (S_ISREG (st.st_mode))
903 size = st.st_size;
905 if (! flags->exact)
907 /* Round up to the nearest block size to clear slack space. */
908 off_t remainder = size % ST_BLKSIZE (st);
909 if (size && size < ST_BLKSIZE (st))
910 i_size = size;
911 if (remainder != 0)
913 off_t size_incr = ST_BLKSIZE (st) - remainder;
914 size += MIN (size_incr, OFF_T_MAX - size);
918 else
920 /* The behavior of lseek is unspecified, but in practice if
921 it returns a positive number that's the size of this
922 device. */
923 size = lseek (fd, 0, SEEK_END);
924 if (size <= 0)
926 /* We are unable to determine the length, up front.
927 Let dopass do that as part of its first iteration. */
928 size = -1;
932 else if (S_ISREG (st.st_mode)
933 && st.st_size < MIN (ST_BLKSIZE (st), size))
934 i_size = st.st_size;
936 /* Schedule the passes in random order. */
937 genpattern (passarray, flags->n_iterations, s);
939 rs = randint_get_source (s);
941 while (true)
943 off_t pass_size;
944 unsigned long int pn = n;
946 if (i_size)
948 pass_size = i_size;
949 i_size = 0;
950 pn = 0;
952 else if (size)
954 pass_size = size;
955 size = 0;
957 /* TODO: consider handling tail packing by
958 writing the tail padding as a separate pass,
959 (that would not rewind). */
960 else
961 break;
963 for (i = 0; i < flags->n_iterations + flags->zero_fill; i++)
965 int err = 0;
966 int type = i < flags->n_iterations ? passarray[i] : 0;
968 err = dopass (fd, &st, qname, &pass_size, type, rs, i + 1, pn);
970 if (err)
972 ok = false;
973 if (err < 0)
974 goto wipefd_out;
979 /* Now deallocate the data. The effect of ftruncate on
980 non-regular files is unspecified, so don't worry about any
981 errors reported for them. */
982 if (flags->remove_file && ftruncate (fd, 0) != 0
983 && S_ISREG (st.st_mode))
985 error (0, errno, _("%s: error truncating"), qname);
986 ok = false;
987 goto wipefd_out;
990 wipefd_out:
991 memset (passarray, 0, flags->n_iterations * sizeof (int));
992 free (passarray);
993 return ok;
996 /* A wrapper with a little more checking for fds on the command line */
997 static bool
998 wipefd (int fd, char const *qname, struct randint_source *s,
999 struct Options const *flags)
1001 int fd_flags = fcntl (fd, F_GETFL);
1003 if (fd_flags < 0)
1005 error (0, errno, _("%s: fcntl failed"), qname);
1006 return false;
1008 if (fd_flags & O_APPEND)
1010 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1011 return false;
1013 return do_wipefd (fd, qname, s, flags);
1016 /* --- Name-wiping code --- */
1018 /* Characters allowed in a file name - a safe universal set. */
1019 static char const nameset[] =
1020 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
1022 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
1023 number with the digits taken from nameset. Return true if successful.
1024 Otherwise, (because NAME already has the greatest possible value)
1025 return false. */
1027 static bool
1028 incname (char *name, size_t len)
1030 while (len--)
1032 char const *p = strchr (nameset, name[len]);
1034 /* Given that NAME is composed of bytes from NAMESET,
1035 P will never be NULL here. */
1036 assert (p);
1038 /* If this character has a successor, use it. */
1039 if (p[1])
1041 name[len] = p[1];
1042 return true;
1045 /* Otherwise, set this digit to 0 and increment the prefix. */
1046 name[len] = nameset[0];
1049 return false;
1053 * Repeatedly rename a file with shorter and shorter names,
1054 * to obliterate all traces of the file name (and length) on any system
1055 * that adds a trailing delimiter to on-disk file names and reuses
1056 * the same directory slot. Finally, unlink it.
1057 * The passed-in filename is modified in place to the new filename.
1058 * (Which is unlinked if this function succeeds, but is still present if
1059 * it fails for some reason.)
1061 * The main loop is written carefully to not get stuck if all possible
1062 * names of a given length are occupied. It counts down the length from
1063 * the original to 0. While the length is non-zero, it tries to find an
1064 * unused file name of the given length. It continues until either the
1065 * name is available and the rename succeeds, or it runs out of names
1066 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1068 * The unlink is Unix-specific, as ANSI-standard remove has more
1069 * portability problems with C libraries making it "safe". rename
1070 * is ANSI-standard.
1072 * To force the directory data out, we try to open the directory and
1073 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
1074 * insist that it works: just fall back to a global sync in that case.
1075 * This is fairly significantly Unix-specific. Of course, on any
1076 * file system with synchronous metadata updates, this is unnecessary.
1078 static bool
1079 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1081 char *newname = xstrdup (oldname);
1082 char *base = last_component (newname);
1083 size_t len = base_len (base);
1084 char *dir = dir_name (newname);
1085 char *qdir = xstrdup (quotef (dir));
1086 bool first = true;
1087 bool ok = true;
1088 int dir_fd = -1;
1090 if (flags->remove_file == remove_wipesync)
1091 dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
1093 if (flags->verbose)
1094 error (0, 0, _("%s: removing"), qoldname);
1096 while ((flags->remove_file != remove_unlink) && len)
1098 memset (base, nameset[0], len);
1099 base[len] = 0;
1102 struct stat st;
1103 if (lstat (newname, &st) < 0)
1105 if (rename (oldname, newname) == 0)
1107 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
1108 ok = false;
1109 if (flags->verbose)
1112 * People seem to understand this better than talking
1113 * about renaming oldname. newname doesn't need
1114 * quoting because we picked it. oldname needs to
1115 * be quoted only the first time.
1117 char const *old = (first ? qoldname : oldname);
1118 error (0, 0, _("%s: renamed to %s"),
1119 old, newname);
1120 first = false;
1122 memcpy (oldname + (base - newname), base, len + 1);
1123 break;
1125 else
1127 /* The rename failed: give up on this length. */
1128 break;
1131 else
1133 /* newname exists, so increment BASE so we use another */
1136 while (incname (base, len));
1137 len--;
1139 if (unlink (oldname) != 0)
1141 error (0, errno, _("%s: failed to remove"), qoldname);
1142 ok = false;
1144 else if (flags->verbose)
1145 error (0, 0, _("%s: removed"), qoldname);
1146 if (0 <= dir_fd)
1148 if (dosync (dir_fd, qdir) != 0)
1149 ok = false;
1150 if (close (dir_fd) != 0)
1152 error (0, errno, _("%s: failed to close"), qdir);
1153 ok = false;
1156 free (newname);
1157 free (dir);
1158 free (qdir);
1159 return ok;
1163 * Finally, the function that actually takes a filename and grinds
1164 * it into hamburger.
1166 * FIXME
1167 * Detail to note: since we do not restore errno to EACCES after
1168 * a failed chmod, we end up printing the error code from the chmod.
1169 * This is actually the error that stopped us from proceeding, so
1170 * it's arguably the right one, and in practice it'll be either EACCES
1171 * again or EPERM, which both give similar error messages.
1172 * Does anyone disagree?
1174 static bool
1175 wipefile (char *name, char const *qname,
1176 struct randint_source *s, struct Options const *flags)
1178 bool ok;
1179 int fd;
1181 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1182 if (fd < 0
1183 && (errno == EACCES && flags->force)
1184 && chmod (name, S_IWUSR) == 0)
1185 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1186 if (fd < 0)
1188 error (0, errno, _("%s: failed to open for writing"), qname);
1189 return false;
1192 ok = do_wipefd (fd, qname, s, flags);
1193 if (close (fd) != 0)
1195 error (0, errno, _("%s: failed to close"), qname);
1196 ok = false;
1198 if (ok && flags->remove_file)
1199 ok = wipename (name, qname, flags);
1200 return ok;
1204 /* Buffers for random data. */
1205 static struct randint_source *randint_source;
1207 /* Just on general principles, wipe buffers containing information
1208 that may be related to the possibly-pseudorandom values used during
1209 shredding. */
1210 static void
1211 clear_random_data (void)
1213 randint_all_free (randint_source);
1218 main (int argc, char **argv)
1220 bool ok = true;
1221 struct Options flags = { 0, };
1222 char **file;
1223 int n_files;
1224 int c;
1225 int i;
1226 char const *random_source = NULL;
1228 initialize_main (&argc, &argv);
1229 set_program_name (argv[0]);
1230 setlocale (LC_ALL, "");
1231 bindtextdomain (PACKAGE, LOCALEDIR);
1232 textdomain (PACKAGE);
1234 atexit (close_stdout);
1236 flags.n_iterations = DEFAULT_PASSES;
1237 flags.size = -1;
1239 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1241 switch (c)
1243 case 'f':
1244 flags.force = true;
1245 break;
1247 case 'n':
1248 flags.n_iterations = xdectoumax (optarg, 0,
1249 MIN (ULONG_MAX,
1250 SIZE_MAX / sizeof (int)), "",
1251 _("invalid number of passes"), 0);
1252 break;
1254 case RANDOM_SOURCE_OPTION:
1255 if (random_source && !STREQ (random_source, optarg))
1256 die (EXIT_FAILURE, 0, _("multiple random sources specified"));
1257 random_source = optarg;
1258 break;
1260 case 'u':
1261 if (optarg == NULL)
1262 flags.remove_file = remove_wipesync;
1263 else
1264 flags.remove_file = XARGMATCH ("--remove", optarg,
1265 remove_args, remove_methods);
1266 break;
1268 case 's':
1269 flags.size = xnumtoumax (optarg, 0, 0, OFF_T_MAX, "cbBkKMGTPEZY0",
1270 _("invalid file size"), 0);
1271 break;
1273 case 'v':
1274 flags.verbose = true;
1275 break;
1277 case 'x':
1278 flags.exact = true;
1279 break;
1281 case 'z':
1282 flags.zero_fill = true;
1283 break;
1285 case_GETOPT_HELP_CHAR;
1287 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1289 default:
1290 usage (EXIT_FAILURE);
1294 file = argv + optind;
1295 n_files = argc - optind;
1297 if (n_files == 0)
1299 error (0, 0, _("missing file operand"));
1300 usage (EXIT_FAILURE);
1303 randint_source = randint_all_new (random_source, SIZE_MAX);
1304 if (! randint_source)
1305 die (EXIT_FAILURE, errno, "%s", quotef (random_source));
1306 atexit (clear_random_data);
1308 for (i = 0; i < n_files; i++)
1310 char *qname = xstrdup (quotef (file[i]));
1311 if (STREQ (file[i], "-"))
1313 ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1315 else
1317 /* Plain filename - Note that this overwrites *argv! */
1318 ok &= wipefile (file[i], qname, randint_source, &flags);
1320 free (qname);
1323 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
1326 * vim:sw=2:sts=2: