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

jvoisin's avatar
jvoisin committed
3
import os
4
from typing import Tuple, Generator, List
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
jvoisin's avatar
jvoisin committed
9

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

jvoisin's avatar
jvoisin committed
17
__version__ = '0.4.0'
jvoisin's avatar
jvoisin committed
18

19 20 21 22
# Make pyflakes happy
assert Tuple


jvoisin's avatar
jvoisin committed
23
def __check_file(filename: str, mode: int=os.R_OK) -> bool:
24 25 26 27
    if not os.path.exists(filename):
        print("[-] %s is doesn't exist." % filename)
        return False
    elif not os.path.isfile(filename):
jvoisin's avatar
jvoisin committed
28 29 30 31 32 33
        print("[-] %s is not a regular file." % filename)
        return False
    elif not os.access(filename, mode):
        print("[-] %s is not readable and writeable." % filename)
        return False
    return True
jvoisin's avatar
jvoisin committed
34

35

36
def create_arg_parser() -> argparse.ArgumentParser:
jvoisin's avatar
jvoisin committed
37
    parser = argparse.ArgumentParser(description='Metadata anonymisation toolkit 2')
38
    parser.add_argument('files', nargs='*', help='the files to process')
jvoisin's avatar
jvoisin committed
39
    parser.add_argument('-v', '--version', action='version',
jvoisin's avatar
jvoisin committed
40
                        version='MAT2 %s' % __version__)
jvoisin's avatar
jvoisin committed
41
    parser.add_argument('-l', '--list', action='store_true',
jvoisin's avatar
jvoisin committed
42
                        help='list all supported fileformats')
43
    parser.add_argument('--check-dependencies', action='store_true',
jvoisin's avatar
jvoisin committed
44
                        help='check if MAT2 has all the dependencies it needs')
dkg's avatar
dkg committed
45 46
    parser.add_argument('-V', '--verbose', action='store_true',
                        help='show more verbose status information')
47
    parser.add_argument('--unknown-members', metavar='policy', default='abort',
dkg's avatar
dkg committed
48
                        help='how to handle unknown members of archive-style files (policy should' +
jvoisin's avatar
jvoisin committed
49
                        ' be one of: %s)' % ', '.join(p.value for p in UnknownMemberPolicy))
50

jvoisin's avatar
jvoisin committed
51

52
    info = parser.add_mutually_exclusive_group()
jvoisin's avatar
jvoisin committed
53
    info.add_argument('-s', '--show', action='store_true',
54
                      help='list harmful metadata detectable by MAT2 without removing them')
jvoisin's avatar
jvoisin committed
55 56
    info.add_argument('-L', '--lightweight', action='store_true',
                      help='remove SOME metadata')
jvoisin's avatar
jvoisin committed
57 58
    return parser

59

jvoisin's avatar
jvoisin committed
60
def show_meta(filename: str):
jvoisin's avatar
jvoisin committed
61 62 63
    if not __check_file(filename):
        return

64
    p, mtype = parser_factory.get_parser(filename)  # type: ignore
jvoisin's avatar
jvoisin committed
65
    if p is None:
jvoisin's avatar
jvoisin committed
66
        print("[-] %s's format (%s) is not supported" % (filename, mtype))
jvoisin's avatar
jvoisin committed
67
        return
68
    __print_meta(filename, p.get_meta())
69 70


jvoisin's avatar
jvoisin committed
71
def __print_meta(filename: str, metadata: dict, depth: int=1):
72
    padding = " " * depth*2
73
    if not metadata:
74
        print(padding + "No metadata found")
75 76
        return

77 78 79
    print("[%s] Metadata for %s:" % ('+'*depth, filename))

    for k, v in metadata.items():
80
        if isinstance(v, dict):
81 82 83 84 85
            return __print_meta(k, v, depth+1)
        try:  # FIXME this is ugly.
            print(padding + "  %s: %s" % (k, v))
        except UnicodeEncodeError:
            print(padding + "  %s: harmful content" % k)
86

jvoisin's avatar
jvoisin committed
87

88
def clean_meta(filename: str, is_lightweight: bool, policy: UnknownMemberPolicy) -> bool:
jvoisin's avatar
jvoisin committed
89
    if not __check_file(filename, os.R_OK|os.W_OK):
jvoisin's avatar
jvoisin committed
90
        return False
jvoisin's avatar
jvoisin committed
91

92
    p, mtype = parser_factory.get_parser(filename)  # type: ignore
jvoisin's avatar
jvoisin committed
93 94
    if p is None:
        print("[-] %s's format (%s) is not supported" % (filename, mtype))
95
        return False
96
    p.unknown_member_policy = policy
dkg's avatar
dkg committed
97
    if is_lightweight:
jvoisin's avatar
jvoisin committed
98 99
        return p.remove_all_lightweight()
    return p.remove_all()
jvoisin's avatar
jvoisin committed
100

101

102 103
def show_parsers():
    print('[+] Supported formats:')
104
    formats = set()
105 106
    for parser in parser_factory._get_parsers():
        for mtype in parser.mimetypes:
107 108
            extensions = set()
            for extension in mimetypes.guess_all_extensions(mtype):
109
                if extension not in UNSUPPORTED_EXTENSIONS:
110 111 112 113 114
                    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
115
            formats.add('  - %s (%s)' % (mtype, ', '.join(extensions)))
jvoisin's avatar
jvoisin committed
116
    print('\n'.join(sorted(formats)))
117

118

119
def __get_files_recursively(files: List[str]) -> Generator[str, None, None]:
120
    for f in files:
121
        if os.path.isdir(f):
122 123
            for path, _, _files in os.walk(f):
                for _f in _files:
124 125 126 127 128
                    fname = os.path.join(path, _f)
                    if __check_file(fname):
                        yield fname
        elif __check_file(f):
            yield f
129

jvoisin's avatar
jvoisin committed
130
def main():
jvoisin's avatar
jvoisin committed
131 132
    arg_parser = create_arg_parser()
    args = arg_parser.parse_args()
jvoisin's avatar
jvoisin committed
133

dkg's avatar
dkg committed
134 135 136
    if args.verbose:
        logging.basicConfig(level=logging.INFO)

137
    if not args.files:
138 139 140 141 142 143 144
        if args.list:
            show_parsers()
        elif args.check_dependencies:
            print("Dependencies required for MAT2 %s:" % __version__)
            for key, value in sorted(check_dependencies().items()):
                print('- %s: %s' % (key, 'yes' if value else 'no'))
        else:
145
            return arg_parser.print_help()
jvoisin's avatar
jvoisin committed
146
        return 0
147

jvoisin's avatar
jvoisin committed
148
    elif args.show:
jvoisin's avatar
jvoisin committed
149
        for f in __get_files_recursively(args.files):
jvoisin's avatar
jvoisin committed
150
            show_meta(f)
jvoisin's avatar
jvoisin committed
151
        return 0
jvoisin's avatar
jvoisin committed
152

153
    else:
154 155
        policy = UnknownMemberPolicy(args.unknown_members)
        if policy == UnknownMemberPolicy.KEEP:
dkg's avatar
dkg committed
156
            logging.warning('Keeping unknown member files may leak metadata in the resulting file!')
jvoisin's avatar
jvoisin committed
157

jvoisin's avatar
jvoisin committed
158
        no_failure = True
jvoisin's avatar
jvoisin committed
159
        for f in __get_files_recursively(args.files):
160
            if clean_meta(f, args.lightweight, policy) is False:
jvoisin's avatar
jvoisin committed
161 162
                no_failure = False
        return 0 if no_failure is True else -1
jvoisin's avatar
jvoisin committed
163

jvoisin's avatar
jvoisin committed
164 165

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