File: verify.py

package info (click to toggle)
mintstick 1.6.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,516 kB
  • sloc: python: 1,034; sh: 46; makefile: 11
file content (383 lines) | stat: -rwxr-xr-x 16,432 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/python3

import gettext
import gi
import gnupg
import locale
import os
import requests
import subprocess
import sys
import threading

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib

APP = 'mintstick'
LOCALE_DIR = "/usr/share/locale"
locale.bindtextdomain(APP, LOCALE_DIR)
gettext.bindtextdomain(APP, LOCALE_DIR)
gettext.textdomain(APP)
_ = gettext.gettext

TRUSTED_SIGNATURES = {"27DEB15644C6B3CF3BD7D291300F846BA25BAE09": "Linux Mint",
                      "C5986B4F1257FFA86632CBA746181433FBB75451": "Ubuntu",
                      "843938DF228D22F7B3742BC0D94AA3F0EFE21092": "Ubuntu",
                      "10460DAD76165AD81FBC0CE9988021A964E6EA7D": "Debian",
                      "DF9B9C49EAA9298432589D76DA87E80D6294BE9B": "Debian",
                      "F41D30342F3546695F65C66942468F4009EA8AC3": "Debian"}

MINT_MIRROR = "https://mirrors.kernel.org/linuxmint"

CACHE_DIR = os.path.expanduser("~/.cache/mintstick")
subprocess.call(["mkdir", "-p", CACHE_DIR])
PATH_SUMS = os.path.join(CACHE_DIR, "sha256sum.txt")
PATH_GPG = os.path.join(CACHE_DIR, "sha256sum.txt.gpg")

# Used as a decorator to run things in the background
def async_function(func):
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=func, args=args, kwargs=kwargs)
        thread.daemon = True
        thread.start()
        return thread
    return wrapper

# Used as a decorator to run things in the main loop, from another thread
def idle_function(func):
    def wrapper(*args):
        GLib.idle_add(func, *args)
    return wrapper

# Converts bytes to readable size
def convert_bytes(num):
    for x in [_('bytes'), _('KB'), _('MB'), _('GB'), _('TB')]:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

class App():

    def __init__(self, iso_path_arg=None):
        self.gpg = gnupg.GPG()
        self.sha256sum = None # the sum of the ISO
        self.path = None # path of the ISO
        self.filename = None # filename of the ISO
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain(APP)
        self.builder.add_from_file("/usr/share/mintstick/verify.ui")
        self.window = self.builder.get_object("main_window")
        self.window.connect("destroy", self.quit)
        self.window.set_position(Gtk.WindowPosition.CENTER)
        self.window.show()
        self.filechooser = self.builder.get_object("filechooser")
        if iso_path_arg is not None and os.path.isfile(iso_path_arg):
            self.filechooser.set_filename(iso_path_arg)
            self.file_selected()

        self.filechooser.connect("file-set", self.file_selected)
        self.builder.get_object("verify_url_button").connect("clicked", self.verify_url)
        self.builder.get_object("verify_files_button").connect("clicked", self.verify_files)
        self.builder.get_object("verify_checksum_button").connect("clicked", self.verify_checksum)
        self.builder.get_object("back_button").connect("clicked", self.go_back)
        self.builder.get_object("stack_checksum").connect("notify::visible-child-name", self.update_verify_button)
        self.builder.get_object("entry_sum").connect("changed", self.update_verify_button)

        # filechoosers
        file_filter = Gtk.FileFilter()
        file_filter.set_name(_("ISO images"))
        file_filter.add_mime_type("application/x-cd-image")
        self.filechooser.add_filter(file_filter)
        file_filter = Gtk.FileFilter()
        file_filter.set_name(_("Checksum files"))
        file_filter.add_mime_type("text/plain")
        self.builder.get_object("filechooser_sums").add_filter(file_filter)
        file_filter = Gtk.FileFilter()
        file_filter.set_name(_("GPG signatures"))
        file_filter.add_mime_type("application/pgp-encrypted")
        file_filter.add_mime_type("application/pgp-signature")
        file_filter.add_mime_type("application/pgp-keys")
        self.builder.get_object("filechooser_gpg").add_filter(file_filter)

        self.builder.get_object("filechooser_sums").connect("file-set", self.update_verify_button)
        self.builder.get_object("filechooser_gpg").connect("file-set", self.update_verify_button)


    def file_selected(self, widget=None):
        self.path = None
        self.filename = None
        self.sha256sum = None
        path = self.filechooser.get_filename()
        self.builder.get_object("size_label").set_text(_("Calculating..."))
        self.builder.get_object("volume_label").set_text(_("Calculating..."))
        self.builder.get_object("checksum_label").set_text(_("Calculating..."))
        self.builder.get_object("headerbar").set_subtitle(path)
        self.builder.get_object("verify_url_button").set_sensitive(False)
        self.builder.get_object("verify_files_button").set_sensitive(False)
        self.builder.get_object("verify_checksum_button").set_sensitive(False)
        if path is not None and os.path.isfile(path):
            self.builder.get_object("result_stack").set_visible_child_name("page_verification")
            self.builder.get_object("stack_checksum").set_visible_child_name("page_url")
            self.path = path
            self.filename = os.path.basename(path)
            self.guess_urls()
            self.calculate_size()
            self.calculate_volume()
            self.calculate_checksum()

    def guess_urls(self):
        # guess the SUMS/GPG URL based on the ISO name
        try:
            sums = ""
            gpg = ""
            if self.filename.startswith("linuxmint-"):
                if self.filename.endswith("-beta.iso"):
                    sums = f"{MINT_MIRROR}/testing/sha256sum.txt"
                elif self.filename.endswith(".iso"):
                    # extract version number
                    version = self.filename.split("-")[1]
                    sums = f"{MINT_MIRROR}/stable/{version}/sha256sum.txt"
                gpg = sums + ".gpg"
            elif self.filename.startswith("lmde-"):
                if self.filename.endswith("-beta.iso"):
                    sums = f"{MINT_MIRROR}/testing/sha256sum.txt"
                elif self.filename.endswith(".iso"):
                    # extract version number
                    sums = f"{MINT_MIRROR}/debian/sha256sum.txt"
                gpg = sums + ".gpg"
            elif self.filename.startswith("ubuntu-"):
                version = self.filename.split("-")[1]
                # remove point version from version
                major = version.split(".")[0]
                minor = version.split(".")[1]
                version = f"{major}.{minor}"
                sums = f"http://releases.ubuntu.com/{version}/SHA256SUMS"
                gpg = sums + ".gpg"
            self.builder.get_object("entry_url_sums").set_text(sums)
            self.builder.get_object("entry_url_gpg").set_text(gpg)
        except Exception as e:
            # best effort
            print(e)
            pass

    @async_function
    def calculate_size(self):
        file_info = os.stat(self.path)
        text = convert_bytes(file_info.st_size)
        self.set_label("size_label", text)

    @async_function
    def calculate_volume(self):
        volume_id = _("No volume ID found")

        try:
            stdout = subprocess.check_output(["isoinfo", "-d", "-i", self.path], text=True)
            for line in stdout.split("\n"):
                if "volume id:" in line.lower():
                    volume_id = line.split(":")[1].strip()
        except Exception as e:
            print("Can't get volume id: %s" % str(e))

        self.set_label("volume_label", volume_id)

    @async_function
    def calculate_checksum(self):
        print("Checking ", self.path)

        try:
            checksum = subprocess.check_output(["sha256sum", "-b", self.path], text=True)
            checksum = checksum.replace(self.path, "").replace("*", "").strip()
        except Exception as e:
            checksum = str(e)

        self.set_label("checksum_label", checksum)
        self.sha256sum = checksum

    def update_verify_button(self, *args):
        self.builder.get_object("verify_url_button").set_sensitive(False)
        self.builder.get_object("verify_files_button").set_sensitive(False)
        self.builder.get_object("verify_checksum_button").set_sensitive(False)

        if self.sha256sum is None:
            return

        if self.builder.get_object("entry_url_sums").get_text() != "" and self.builder.get_object("entry_url_gpg").get_text() != "":
            self.builder.get_object("verify_url_button").set_sensitive(True)

        if self.builder.get_object("filechooser_sums").get_filename() is not None and self.builder.get_object("filechooser_gpg").get_filename() is not None:
            self.builder.get_object("verify_files_button").set_sensitive(True)

        if (self.builder.get_object("entry_sum").get_text() != ""):
            self.builder.get_object("verify_checksum_button").set_sensitive(True)

    @idle_function
    def set_label(self, label, text):
        self.builder.get_object(label).set_text(text)
        self.update_verify_button()

    def verify_checksum(self, button):
        if self.builder.get_object("entry_sum").get_text().lower() == self.sha256sum.lower():
            self.show_result("dialog-warning", _("The checksum is correct"),
                    summary=_("The checksum is correct but the authenticity of the sum was not verified."))
        else:
            self.show_result("dialog-error", _("Checksum mismatch"),
                    summary=_("Download the ISO image again. Its checksum does not match."))

    def verify_url(self, button):
        # Download files
        try:
            with open(PATH_SUMS, "wb") as file:
                url = self.builder.get_object("entry_url_sums").get_text()
                response = requests.get(url)
                response.raise_for_status()
                file.write(response.content)
        except:
            self.dialog(_("The sums file could not be downloaded. Check the URL."))
            return
        try:
            with open(PATH_GPG, "wb") as file:
                url = self.builder.get_object("entry_url_gpg").get_text()
                response = requests.get(url)
                response.raise_for_status()
                file.write(response.content)
        except:
            self.dialog(_("The gpg file could not be downloaded. Check the URL."))
            return
        self.verify()

    def verify_files(self, button):
        # Copy files
        try:
            with open(PATH_SUMS, "wb") as file:
                path = self.builder.get_object("filechooser_sums").get_filename()
                subprocess.call(["cp", path, PATH_SUMS])
        except:
            self.dialog(_("The sums file could not be checked."))
            return
        try:
            with open(PATH_GPG, "wb") as file:
                path = self.builder.get_object("filechooser_gpg").get_filename()
                subprocess.call(["cp", path, PATH_GPG])
        except:
            self.dialog(_("The gpg file could not be checked."))
            return
        self.verify()

    def verify(self):
        details = []
        try:
            integrity_ok, explanation = self.check_integrity()
            if not integrity_ok:
                # Incorrect SUM
                self.show_result("dialog-error", _("Integrity check failed"),
                    summary=explanation)
                return

            # note: verify_file automatically closes the file handle
            verified = self.gpg.verify_file(open(PATH_GPG, "rb"), PATH_SUMS)

            if verified.fingerprint is None:
                # The GPG file is not signed
                self.show_result("dialog-error", _("The SHA256 sums file is not signed."))
                return

            fingerprint = verified.fingerprint
            details.append(_("Signed by: %s") % fingerprint)

            for keyserver in ['hkp://keyserver.ubuntu.com', 'hkp://keys.openpgp.org']:
                if not verified.valid:
                    # The key isn't in the keyring, download it from the keyserver
                    # Note: keyserver.ubuntu.com is fast but unreliable, start with that one
                    # keys.opengpg.org is reliable but slower, it's a good fallback
                    print(f"Importing {fingerprint} from {keyserver}")
                    # re-verify
                    self.gpg.recv_keys(keyserver, fingerprint)
                    verified = self.gpg.verify_file(open(PATH_GPG, "rb"), PATH_SUMS)
                    # Remove it from the keyring
                    print("Deleting", fingerprint)
                    self.gpg.delete_keys(fingerprint)

            if not verified.valid:
                # The key still isn't in the keyring
                self.show_result("dialog-warning", _("Unknown signature"),
                    summary=_("Key not found on keyserver."),
                    details=details)
                return

            if verified.username is not None:
                details.append(verified.username)

            if verified.fingerprint in TRUSTED_SIGNATURES.keys():
                name = TRUSTED_SIGNATURES[verified.fingerprint]
                logo_name = name.replace(" ", "").lower().strip()
                logo_name = f"mintstick-logo-{logo_name}"
                self.show_result(logo_name, _("Everything looks good!"),
                    summary=_("This is an official ISO image."),
                    details=details)
                return

            if verified.trust_level is not None and verified.trust_level >= verified.TRUST_FULLY:
                self.show_result("application-certificate", _("Everything looks good!"),
                    summary=_("This ISO image is verified by a trusted signature."),
                    details=details)
            else:
                details.append(_("If you trust the signature you can trust the ISO."))
                self.show_result("dialog-warning", _("Untrusted signature"),
                    summary=_("This ISO image is verified by an untrusted signature."),
                    details=details)
                return

        except Exception as e:
            self.show_result("dialog-error", _("An error occurred"), details=[str(e)])

    def check_integrity(self):
        with open(PATH_SUMS) as sums_file:
            for line in sums_file:
                line = line.strip()
                if line.endswith(f" *{self.filename}") or line.endswith(f" {self.filename}"):
                    if line == f"{self.sha256sum} *{self.filename}" or \
                       line == f"{self.sha256sum} {self.filename}":
                        return (True, None)
                    else:
                        return (False, _("The SHA256 sum of the ISO image is incorrect."))
        return (False, _("The SHA256 sums file does not contain sums for this ISO image."))

    def show_result(self, icon_name, text, summary=None, details=None):
        self.builder.get_object("image_result").set_from_icon_name(icon_name, 64)
        self.builder.get_object("label_result").set_text(text)
        if summary is not None:
            self.builder.get_object("label_result_summary").set_text(summary)
        if details is not None:
            self.builder.get_object("label_result_details").set_text("\n".join(details))
        self.builder.get_object("result_stack").set_visible_child_name("page_result")
        # Unselect the summary label
        self.builder.get_object("label_result_summary").select_region(0, 0)
        self.builder.get_object("back_button").grab_focus()

    def dialog(self, text):
        dialog = Gtk.MessageDialog(parent=self.window,
            modal=True,
            message_type=Gtk.MessageType.WARNING,
            buttons=Gtk.ButtonsType.OK,
            text=text)
        dialog.set_default_response(Gtk.ResponseType.OK)
        dialog.run()
        dialog.destroy()

    def go_back(self, button):
        self.builder.get_object("result_stack").set_visible_child_name("page_verification")

    def quit(self, widget=None):
        Gtk.main_quit()

if len(sys.argv) != 2:
    print("Usage:\n  mint-iso-verify iso_file\n\nExiting.")
    sys.exit(1)

filename = sys.argv[1]
if not os.path.exists(filename):
    print(f"File not found '{filename}'.\nExiting.")
    sys.exit(1)

App(sys.argv[1])
Gtk.main()