file_crypto.py 8.37 KB
Newer Older
Philipp Hörist's avatar
Philipp Hörist committed
1
# Copyright (C) 2019 Philipp Hörist <philipp AT hoerist.com>
Philipp Hörist's avatar
Philipp Hörist committed
2
#
Philipp Hörist's avatar
Philipp Hörist committed
3
# This file is part of OMEMO Gajim Plugin.
Philipp Hörist's avatar
Philipp Hörist committed
4
#
Philipp Hörist's avatar
Philipp Hörist committed
5
6
7
# OMEMO Gajim Plugin is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 only.
Philipp Hörist's avatar
Philipp Hörist committed
8
#
Philipp Hörist's avatar
Philipp Hörist committed
9
10
11
12
# OMEMO Gajim Plugin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
Philipp Hörist's avatar
Philipp Hörist committed
13
#
Philipp Hörist's avatar
Philipp Hörist committed
14
15
# You should have received a copy of the GNU General Public License
# along with OMEMO Gajim Plugin. If not, see <http://www.gnu.org/licenses/>.
Philipp Hörist's avatar
Philipp Hörist committed
16
17

import os
Philipp Hörist's avatar
Philipp Hörist committed
18
import sys
Philipp Hörist's avatar
Philipp Hörist committed
19
20
21
22
23
24
25
import hashlib
import logging
import socket
import threading
import platform
import subprocess
import binascii
26
import ssl
Philipp Hörist's avatar
Philipp Hörist committed
27
28
29
30
31
32
from urllib.request import urlopen
from urllib.error import URLError
from urllib.parse import urlparse, urldefrag
from io import BufferedWriter, FileIO, BytesIO

from gi.repository import GLib
Philipp Hörist's avatar
Philipp Hörist committed
33

34
from gajim.common import app
35
from gajim.common import configpaths
36
from gajim.common.const import URIType
Philipp Hörist's avatar
Philipp Hörist committed
37
from gajim.plugins.plugins_i18n import _
Daniel Brötzmann's avatar
Daniel Brötzmann committed
38
39
40
from gajim.gtk.dialogs import ErrorDialog
from gajim.gtk.dialogs import DialogButton
from gajim.gtk.dialogs import NewConfirmationDialog
Philipp Hörist's avatar
Philipp Hörist committed
41

42
from omemo.gtk.progress import ProgressWindow
Philipp Hörist's avatar
Philipp Hörist committed
43
44
from omemo.backend.aes import aes_decrypt_file

Philipp Hörist's avatar
Philipp Hörist committed
45
if sys.platform in ('win32', 'darwin'):
Philipp Hörist's avatar
Philipp Hörist committed
46
47
    import certifi

Philipp Hörist's avatar
Philipp Hörist committed
48
log = logging.getLogger('gajim.p.omemo.filedecryption')
Philipp Hörist's avatar
Philipp Hörist committed
49

50
DIRECTORY = os.path.join(configpaths.get('MY_DATA'), 'downloads')
Philipp Hörist's avatar
Philipp Hörist committed
51

Philipp Hörist's avatar
Philipp Hörist committed
52
ERROR = False
Philipp Hörist's avatar
Philipp Hörist committed
53
54
55
56
57
58
59
60
61
try:
    if not os.path.exists(DIRECTORY):
        os.makedirs(DIRECTORY)
except Exception:
    ERROR = True
    log.exception('Error')


class File:
62
63
    def __init__(self, url, account):
        self.account = account
Philipp Hörist's avatar
Philipp Hörist committed
64
65
66
67
68
69
70
71
72
73
74
75
        self.url, self.fragment = urldefrag(url)
        self.key = None
        self.iv = None
        self.filepath = None
        self.filename = None


class FileDecryption:
    def __init__(self, plugin):
        self.plugin = plugin
        self.window = None

76
77
    def hyperlink_handler(self, uri, instance, window):
        if ERROR or uri.type != URIType.WEB:
Philipp Hörist's avatar
Philipp Hörist committed
78
79
            return
        self.window = window
80
        urlparts = urlparse(uri.data)
81
        file = File(urlparts.geturl(), instance.account)
Philipp Hörist's avatar
Philipp Hörist committed
82

83
        if urlparts.scheme not in ['https', 'aesgcm'] or not urlparts.netloc:
84
            log.info("Not accepting URL for decryption: %s", uri.data)
Philipp Hörist's avatar
Philipp Hörist committed
85
86
            return

87
88
89
90
        if urlparts.scheme == 'aesgcm':
            log.debug('aesgcm scheme detected')
            file.url = 'https://' + file.url[9:]

Philipp Hörist's avatar
Philipp Hörist committed
91
        if not self.is_encrypted(file):
92
            log.info('URL not encrypted: %s', uri.data)
Philipp Hörist's avatar
Philipp Hörist committed
93
            return
94

Philipp Hörist's avatar
Philipp Hörist committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        self.create_paths(file)

        if os.path.exists(file.filepath):
            instance.plugin_modified = True
            self.finished(file)
            return

        event = threading.Event()
        progressbar = ProgressWindow(self.plugin, self.window, event)
        thread = threading.Thread(target=Download,
                                  args=(file, progressbar, self.window,
                                        event, self))
        thread.daemon = True
        thread.start()
        instance.plugin_modified = True

    def is_encrypted(self, file):
        if file.fragment:
            try:
                fragment = binascii.unhexlify(file.fragment)
                file.key = fragment[16:]
                file.iv = fragment[:16]
                if len(file.key) == 32 and len(file.iv) == 16:
                    return True
119
120
121
122
123

                file.key = fragment[12:]
                file.iv = fragment[:12]
                if len(file.key) == 32 and len(file.iv) == 12:
                    return True
Philipp Hörist's avatar
Philipp Hörist committed
124
125
126
127
128
129
130
131
132
133
134
135
136
            except:
                return False
        return False

    def create_paths(self, file):
        file.filename = os.path.basename(file.url)
        ext = os.path.splitext(file.filename)[1]
        name = os.path.splitext(file.filename)[0]
        urlhash = hashlib.sha1(file.url.encode('utf-8')).hexdigest()
        newfilename = name + '_' + urlhash[:10] + ext
        file.filepath = os.path.join(DIRECTORY, newfilename)

    def finished(self, file):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
137
138
139
140
141
142
143
144
145
146
147
        NewConfirmationDialog(
            _('Open File'),
            _('Open File?'),
            _('Do you want to open %s?') % file.filename,
            [DialogButton.make('Cancel',
                               text=_('_No')),
             DialogButton.make('OK',
                               text=_('_Open'),
                               callback=self.open_file(file.filepath))],
            transient_for=self.window).show()

Philipp Hörist's avatar
Philipp Hörist committed
148
149
        return False

Daniel Brötzmann's avatar
Daniel Brötzmann committed
150
    def open_file(self, path):
Philipp Hörist's avatar
Philipp Hörist committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        if platform.system() == "Windows":
            os.startfile(path)
        elif platform.system() == "Darwin":
            subprocess.Popen(["open", path])
        else:
            subprocess.Popen(["xdg-open", path])


class Download:
    def __init__(self, file, progressbar, window, event, base):
        self.file = file
        self.progressbar = progressbar
        self.window = window
        self.event = event
        self.base = base
        self.download()

    def download(self):
169
        GLib.idle_add(self.progressbar.set_text, _('Downloading...'))
Philipp Hörist's avatar
Philipp Hörist committed
170
171
172
173
174
175
        data = self.load_url()
        if isinstance(data, str):
            GLib.idle_add(self.progressbar.close_dialog)
            GLib.idle_add(self.error, data)
            return

176
        GLib.idle_add(self.progressbar.set_text, _('Decrypting...'))
Philipp Hörist's avatar
Philipp Hörist committed
177
178
179
180

        decrypted_data = aes_decrypt_file(self.file.key,
                                          self.file.iv,
                                          data.getvalue())
Philipp Hörist's avatar
Philipp Hörist committed
181
182

        GLib.idle_add(
183
            self.progressbar.set_text, _('Writing file to harddisk...'))
Philipp Hörist's avatar
Philipp Hörist committed
184
185
186
187
188
189
190
191
192
        self.write_file(decrypted_data)

        GLib.idle_add(self.progressbar.close_dialog)

        GLib.idle_add(self.base.finished, self.file)

    def load_url(self):
        try:
            stream = BytesIO()
193
194
195
196
197
198
199
200
            if not app.config.get_per('accounts',
                                      self.file.account,
                                      'httpupload_verify'):
                context = ssl.create_default_context()
                context.check_hostname = False
                context.verify_mode = ssl.CERT_NONE
                log.warning('CERT Verification disabled')
                get_request = urlopen(self.file.url, timeout=30, context=context)
Philipp Hörist's avatar
Philipp Hörist committed
201
            else:
Philipp Hörist's avatar
Philipp Hörist committed
202
                cafile = None
Philipp Hörist's avatar
Philipp Hörist committed
203
                if sys.platform in ('win32', 'darwin'):
Philipp Hörist's avatar
Philipp Hörist committed
204
205
206
                    cafile = certifi.where()
                context = ssl.create_default_context(cafile=cafile)
                get_request = urlopen(self.file.url, timeout=30, context=context)
207

Philipp Hörist's avatar
Philipp Hörist committed
208
209
210
211
212
213
214
215
            size = get_request.info()['Content-Length']
            if not size:
                errormsg = 'Content-Length not found in header'
                log.error(errormsg)
                return errormsg
            while True:
                try:
                    if self.event.isSet():
216
                        raise DownloadAbortedException
Philipp Hörist's avatar
Philipp Hörist committed
217
218
219
220
221
222
223
224
225
226
227
                    temp = get_request.read(10000)
                    GLib.idle_add(
                        self.progressbar.update_progress, len(temp), size)
                except socket.timeout:
                    errormsg = 'Request timeout'
                    log.error(errormsg)
                    return errormsg
                if temp:
                    stream.write(temp)
                else:
                    return stream
228
229
        except DownloadAbortedException as error:
            log.info('Download Aborted')
Philipp Hörist's avatar
Philipp Hörist committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            errormsg = error
        except URLError as error:
            log.exception('URLError')
            errormsg = error.reason
        except Exception as error:
            log.exception('Error')
            errormsg = error
        stream.close()
        return str(errormsg)

    def write_file(self, data):
        log.info('Writing data to %s', self.file.filepath)
        try:
            with BufferedWriter(FileIO(self.file.filepath, "wb")) as output:
                output.write(data)
                output.close()
        except Exception:
            log.exception('Failed to write file')

    def error(self, error):
        ErrorDialog(_('Error'), error, transient_for=self.window)
        return False


254
class DownloadAbortedException(Exception):
Philipp Hörist's avatar
Philipp Hörist committed
255
    def __str__(self):
256
        return _('Download Aborted')