mat2 7.28 KB
Newer Older
1
#!/usr/bin/env python3
2

jvoisin's avatar
jvoisin committed
3
import os
jvoisin's avatar
jvoisin committed
4
from typing import Tuple, List, Union, Set
5
import sys
jvoisin's avatar
jvoisin committed
6
import mimetypes
jvoisin's avatar
jvoisin committed
7
import argparse
dkg's avatar
dkg committed
8
import logging
9
import unicodedata
jvoisin's avatar
jvoisin committed
10
import concurrent.futures
jvoisin's avatar
jvoisin committed
11

12
try:
13 14
    from libmat2 import parser_factory, UNSUPPORTED_EXTENSIONS
    from libmat2 import check_dependencies, UnknownMemberPolicy
15 16 17
except ValueError as e:
    print(e)
    sys.exit(1)
jvoisin's avatar
jvoisin committed
18

jvoisin's avatar
jvoisin committed
19
__version__ = '0.9.0'
jvoisin's avatar
jvoisin committed
20

21
# Make pyflakes happy
jvoisin's avatar
jvoisin committed
22
assert Set
23
assert Tuple
jvoisin's avatar
jvoisin committed
24
assert Union
25

jvoisin's avatar
jvoisin committed
26 27
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)

28

29
def __check_file(filename: str, mode: int = os.R_OK) -> bool:
30
    if not os.path.exists(filename):
31
        print("[-] %s doesn't exist." % filename)
32 33
        return False
    elif not os.path.isfile(filename):
jvoisin's avatar
jvoisin committed
34 35 36
        print("[-] %s is not a regular file." % filename)
        return False
    elif not os.access(filename, mode):
37 38 39 40 41 42
        mode_str = []  # type: List[str]
        if mode & os.R_OK:
            mode_str += 'readable'
        if mode & os.W_OK:
            mode_str += 'writeable'
        print("[-] %s is not %s." % (filename, 'nor '.join(mode_str)))
jvoisin's avatar
jvoisin committed
43 44
        return False
    return True
jvoisin's avatar
jvoisin committed
45

46

47
def create_arg_parser() -> argparse.ArgumentParser:
jvoisin's avatar
jvoisin committed
48
    parser = argparse.ArgumentParser(description='Metadata anonymisation toolkit 2')
49

dkg's avatar
dkg committed
50 51
    parser.add_argument('-V', '--verbose', action='store_true',
                        help='show more verbose status information')
52
    parser.add_argument('--unknown-members', metavar='policy', default='abort',
jvoisin's avatar
jvoisin committed
53 54 55
                        help='how to handle unknown members of archive-style '
                        'files (policy should be one of: %s) [Default: abort]' %
                        ', '.join(p.value for p in UnknownMemberPolicy))
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    excl_group = parser.add_mutually_exclusive_group()
    excl_group.add_argument('files', nargs='*', help='the files to process',
                            default=[])
    excl_group.add_argument('-v', '--version', action='version',
                            version='MAT2 %s' % __version__)
    excl_group.add_argument('-l', '--list', action='store_true', default=False,
                            help='list all supported fileformats')
    excl_group.add_argument('--check-dependencies', action='store_true',
                            default=False,
                            help='check if MAT2 has all the dependencies it '
                            'needs')

    excl_group = parser.add_mutually_exclusive_group()
    excl_group.add_argument('-L', '--lightweight', action='store_true',
                            help='remove SOME metadata')
    excl_group.add_argument('-s', '--show', action='store_true',
                            help='list harmful metadata detectable by MAT2 '
                            'without removing them')
jvoisin's avatar
jvoisin committed
75 76 77

    return parser

78

jvoisin's avatar
jvoisin committed
79
def show_meta(filename: str):
jvoisin's avatar
jvoisin committed
80 81 82
    if not __check_file(filename):
        return

83
    p, mtype = parser_factory.get_parser(filename)  # type: ignore
jvoisin's avatar
jvoisin committed
84
    if p is None:
jvoisin's avatar
jvoisin committed
85
        print("[-] %s's format (%s) is not supported" % (filename, mtype))
jvoisin's avatar
jvoisin committed
86
        return
87
    __print_meta(filename, p.get_meta())
88 89


90
def __print_meta(filename: str, metadata: dict, depth: int = 1):
91
    padding = " " * depth*2
92
    if not metadata:
93
        print(padding + "No metadata found in %s." % filename)
94 95
        return

96 97
    print("[%s] Metadata for %s:" % ('+'*depth, filename))

jvoisin's avatar
jvoisin committed
98
    for (k, v) in sorted(metadata.items()):
99
        if isinstance(v, dict):
100 101
            __print_meta(k, v, depth+1)
            continue
102 103 104 105 106 107 108 109 110

        # Remove control characters
        # We might use 'Cc' instead of 'C', but better safe than sorry
        # https://www.unicode.org/reports/tr44/#GC_Values_Table
        try:
            v = ''.join(ch for ch in v if not unicodedata.category(ch).startswith('C'))
        except TypeError:
            pass  # for things that aren't iterable

111 112 113 114
        try:  # FIXME this is ugly.
            print(padding + "  %s: %s" % (k, v))
        except UnicodeEncodeError:
            print(padding + "  %s: harmful content" % k)
115

jvoisin's avatar
jvoisin committed
116

117
def clean_meta(filename: str, is_lightweight: bool, policy: UnknownMemberPolicy) -> bool:
118
    if not __check_file(filename, os.R_OK):
jvoisin's avatar
jvoisin committed
119
        return False
jvoisin's avatar
jvoisin committed
120

121
    p, mtype = parser_factory.get_parser(filename)  # type: ignore
jvoisin's avatar
jvoisin committed
122 123
    if p is None:
        print("[-] %s's format (%s) is not supported" % (filename, mtype))
124
        return False
125
    p.unknown_member_policy = policy
126
    p.lightweight_cleaning = is_lightweight
127 128

    try:
jvoisin's avatar
jvoisin committed
129
        logging.debug('Cleaning %s…', filename)
130 131 132 133 134
        return p.remove_all()
    except RuntimeError as e:
        print("[-] %s can't be cleaned: %s" % (filename, e))
    return False

jvoisin's avatar
jvoisin committed
135

136

137
def show_parsers():
138
    print('[+] Supported formats:')
jvoisin's avatar
jvoisin committed
139 140
    formats = set()  # Set[str]
    for parser in parser_factory._get_parsers():  # type: ignore
141
        for mtype in parser.mimetypes:
jvoisin's avatar
jvoisin committed
142
            extensions = set()  # Set[str]
143
            for extension in mimetypes.guess_all_extensions(mtype):
144
                if extension not in UNSUPPORTED_EXTENSIONS:
145 146 147 148 149
                    extensions.add(extension)
            if not extensions:
                # we're not supporting a single extension in the current
                # mimetype, so there is not point in showing the mimetype at all
                continue
150
            formats.add('  - %s (%s)' % (mtype, ', '.join(extensions)))
jvoisin's avatar
jvoisin committed
151
    print('\n'.join(sorted(formats)))
152

153

jvoisin's avatar
jvoisin committed
154 155
def __get_files_recursively(files: List[str]) -> List[str]:
    ret = set()  # type: Set[str]
156
    for f in files:
157
        if os.path.isdir(f):
158 159
            for path, _, _files in os.walk(f):
                for _f in _files:
160 161
                    fname = os.path.join(path, _f)
                    if __check_file(fname):
jvoisin's avatar
jvoisin committed
162
                        ret.add(fname)
163
        elif __check_file(f):
jvoisin's avatar
jvoisin committed
164 165
            ret.add(f)
    return list(ret)
166

jvoisin's avatar
jvoisin committed
167
def main() -> int:
jvoisin's avatar
jvoisin committed
168 169
    arg_parser = create_arg_parser()
    args = arg_parser.parse_args()
jvoisin's avatar
jvoisin committed
170

dkg's avatar
dkg committed
171
    if args.verbose:
jvoisin's avatar
jvoisin committed
172
        logging.getLogger().setLevel(logging.DEBUG)
dkg's avatar
dkg committed
173

174
    if not args.files:
175
        if args.list:
176 177
            show_parsers()
            return 0
178
        elif args.check_dependencies:
179
            print("Dependencies for MAT2 %s:" % __version__)
180
            for key, value in sorted(check_dependencies().items()):
181 182
                print('- %s: %s %s' % (key, 'yes' if value['found'] else 'no',
                                       '(optional)' if not value['required'] else ''))
183
        else:
jvoisin's avatar
jvoisin committed
184
            arg_parser.print_help()
jvoisin's avatar
jvoisin committed
185
        return 0
186

jvoisin's avatar
jvoisin committed
187
    elif args.show:
jvoisin's avatar
jvoisin committed
188
        for f in __get_files_recursively(args.files):
jvoisin's avatar
jvoisin committed
189
            show_meta(f)
jvoisin's avatar
jvoisin committed
190
        return 0
jvoisin's avatar
jvoisin committed
191

192
    else:
193 194
        policy = UnknownMemberPolicy(args.unknown_members)
        if policy == UnknownMemberPolicy.KEEP:
195
            logging.warning('Keeping unknown member files may leak metadata in the resulting file!')
jvoisin's avatar
jvoisin committed
196

jvoisin's avatar
jvoisin committed
197
        no_failure = True
jvoisin's avatar
jvoisin committed
198 199 200 201 202 203 204 205 206 207
        files = __get_files_recursively(args.files)
        # We have to use Processes instead of Threads, since
        # we're using tempfile.mkdtemp, which isn't thread-safe.
        with concurrent.futures.ProcessPoolExecutor() as executor:
            futures = list()
            for f in files:
                future = executor.submit(clean_meta, f, args.lightweight, policy)
                futures.append(future)
            for future in concurrent.futures.as_completed(futures):
                no_failure &= future.result()
jvoisin's avatar
jvoisin committed
208
        return 0 if no_failure is True else -1
209

jvoisin's avatar
jvoisin committed
210 211

if __name__ == '__main__':
212
    sys.exit(main())