Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sign_macOS.py « scripts - github.com/mumble-voip/mumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 406092ebeb3e503a7dd381b7ac7e4377dc4e12e2 (plain)
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
#!/usr/bin/env python3
#
# Copyright 2013-2022 The Mumble Developers. All rights reserved.
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file at the root of the
# Mumble source tree or at <https://www.mumble.info/LICENSE>.
#
# About the tool
# --------------
# sign_macOS.py is a tool that takes a Mumble .DMG file and digitally signs its content
# (executables, codecs, plugins, installers).
#
# The file(s) may already be signed. In this case, the tool will simply replace all the existing signatures.
#
# Using the tool
# --------------
# To sign Mumble-1.4.0.unsigned.dmg, one would do the following:
#
# $ ./sign_macOS.py -i Mumble-1.4.0.unsigned.dmg -o Mumble-1.4.0.dmg
#
# Configuration
# -------------
# The signing behavior of the tool can be configured via a configuration file.
# By default the tool will read its configuration from $HOME/.sign_macOS.cfg.
#
# The configuration file uses JSON. For example, to sign using a particular
# set of Developer ID certificates in your login keychain, you could use
# something like this:
#
#   --->8---
# 	{
# 		# The keychain needs the .keychain extension explicitly typed out.
# 		"keychain": "login.keychain",
# 		# Your Application certificate.
# 		"developer-id-app": "Developer ID Application: John Appleseed",
# 		# Your Installer certificate.
# 		"developer-id-installer": "Developer ID Installer: John Appleseed"
# 	}
#   --->8---

import argparse
import io
import json
import os
import pathlib
import plistlib
import shutil
import string
import subprocess
import sys
import tempfile

# Specify a set of codesign requirements for Mumble binaries.
#
# We require an Apple CA and a Developer ID leaf certificate (the one we're signing with).
# The 'designated' line is specifically tuned to work on older versions
# of macOS that aren't Developer ID-aware without breakage.
#
# We also explicitly require all shared libraries to be codesigned by Apple.
# We can reasonably do that because Mumble is statically built on macOS.
requirements = '''designated => anchor apple generic and identifier "${identifier}" and (certificate leaf[field.1.2.840.113635.100.6.1.9] /* exists */ or certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = "${subject_OU}")
library => anchor apple'''

class Signer:
	def __init__(self, cfgFile):
		with open(cfgFile) as file:
			content = file.read()
			self.cfg = json.loads(content)

	@staticmethod
	def cmd(args, cwd = None):
		'''
		Executes the requested program and throws an exception if the program returns a non-zero return code.
		'''
		ret = subprocess.Popen(args, cwd = cwd).wait()
		if ret != 0:
			raise Exception('command "%s" exited with exit status %i' % (args[0], ret))

	def certificateSubjectOU(self):
		'''
		Extracts the subject OU from the Application DeveloperID certificate that is specified in the script's configuration.
		'''
		findCert = subprocess.Popen(('/usr/bin/security', 'find-certificate',
									 '-c', self.cfg['developer-id-app'],
									 '-p', self.cfg['keychain']),
									 stdout = subprocess.PIPE, text = True)
		pem, _ = findCert.communicate()

		openssl = subprocess.Popen(('/usr/bin/openssl', 'x509', '-subject', '-noout'),
									stdout = subprocess.PIPE, stdin = subprocess.PIPE, text = True)
		subject, _ = openssl.communicate(pem)

		start = subject.split('/OU=', 1)[1]
		end = start.index('/')

		return start[:end]

	@staticmethod
	def lookupFileIdentifier(file):
		'''
		Looks up a bundle identifier suitable for use when signing the app bundle or binary.
		'''
		try:
			d = plistlib.load(os.path.join(file, 'Contents', 'Info.plist'))
			return d['CFBundleIdentifier']
		except:
			return os.path.basename(file)

	def codesign(self, files, entitlements = None):
		'''
		Calls the codesign executable on the signable object(s) in the specified directory.
		'''
		OU = self.certificateSubjectOU()

		if hasattr(files, 'isalpha'):
			files = (files,)

		for file in files:
			identifier = self.lookupFileIdentifier(file)
			reqs = string.Template(requirements).substitute({
				'identifier': identifier,
				'subject_OU': OU,
			})

			print("Identifier:", identifier)
			print("Subject_OU:", OU)
			print("Reqs:", reqs)

			args = ['-vvvv', '--force',
					'-r=' + reqs,
					'--identifier', identifier,
					'--keychain', self.cfg['keychain'],
					'--sign', self.cfg['developer-id-app']]

			if entitlements:
				args += ['--options', 'runtime',
						 '--entitlements', entitlements]

			self.cmd(['codesign'] + args + [file])

		return 0

	def prodsign(self, inFile, outFile):
		'''
		Calls the productsign executable to sign the specified product, outputting it signed.
		'''
		self.cmd(['productsign',
				  '--keychain', self.cfg['keychain'],
				  '--sign', self.cfg['developer-id-installer'],
				  inFile, outFile])

	@staticmethod
	def volNameForMountedDMG(mountPoint):
		diskutil = subprocess.Popen(['diskutil', 'info', '-plist', mountPoint], stdout = subprocess.PIPE)
		plist, _ = diskutil.communicate()
		fileLikePlist = io.BytesIO(plist)
		diskInfo = plistlib.load(fileLikePlist)
		return diskInfo['VolumeName']

	@staticmethod
	def extractDMG(file, workDir):
		'''
		Extracts the specified DMG into the "content" subdirectory of workDir.
		It returns the volume name of the extracted DMG.
		'''
		mountDir = os.path.join(workDir, 'mount')
		os.mkdir(mountDir)
		Signer.cmd(['hdiutil', 'mount', '-readonly', '-mountpoint', mountDir, file])
		volName = Signer.volNameForMountedDMG(mountDir)
		contentDir = os.path.join(workDir, 'content')
		os.mkdir(contentDir)
		for file in os.listdir(mountDir):
			if file == '.Trashes':
				continue

			src = os.path.join(mountDir, file)
			dst = os.path.join(contentDir, file)

			if os.path.islink(src):
				target = os.readlink(src)
				os.symlink(target, dst)
			elif os.path.isdir(src):
				shutil.copytree(src, dst, True)
			else:
				shutil.copy(src, dst)

		Signer.cmd(['umount', mountDir])

		return volName

	@staticmethod
	def extractPKG(file, workDir):
		'''
		Expands the specified PKG into workDir.
		'''
		Signer.cmd(['pkgutil', '--expand-full', file, workDir])

	def signApp(self, workDir, entitlements = None):
		'''
		Signs the app bundle in the "content" subdirectory of workDir.
		'''
		app = os.path.join(workDir, 'content', 'Mumble.app')

		binaries = []
		binariesDir = os.path.join(app, 'Contents', 'MacOS')
		for binary in os.listdir(binariesDir):
			binaries.append(os.path.join(binariesDir, binary))

		codecs = []
		codecsDir = os.path.join(app, 'Contents', 'Codecs')
		for codec in os.listdir(codecsDir):
			codecs.append(os.path.join(codecsDir, codec))

		plugins = []
		pluginsDir = os.path.join(app, 'Contents', 'Plugins')
		for plugin in os.listdir(pluginsDir):
			plugins.append(os.path.join(pluginsDir, plugin))

		self.codesign(binaries)
		self.codesign(codecs)
		self.codesign(plugins)

		overlayInst = os.path.join(app, 'Contents', 'Resources', 'MumbleOverlay.pkg')
		os.rename(overlayInst, overlayInst + '.intermediate')
		self.prodsign(overlayInst + '.intermediate', overlayInst)
		os.remove(overlayInst + '.intermediate')

		self.codesign(app, entitlements)

	def signOverlay(self, workDir):
		'''
		Extracts "MumbleOverlay.pkg" (which is extracted from the app bundle),
		signs the relevant binaries and then repacks it.
		'''
		app = os.path.join(workDir, 'content', 'Mumble.app')

		overlayPKG = os.path.join(app, 'Contents', 'Resources', 'MumbleOverlay.pkg')
		overlayDir = os.path.join(workDir, 'MumbleOverlay')

		self.extractPKG(overlayPKG, overlayDir)

		binaries = []
		binariesDir = os.path.join(overlayDir, 'net.sourceforge.mumble.OverlayScriptingAddition.pkg',
											   'Payload', 'MumbleOverlay.osax',
											   'Contents', 'MacOS')
		for binary in os.listdir(binariesDir):
			binaries.append(os.path.join(binariesDir, binary))

		self.codesign(binaries)

		self.makePKG(overlayDir, overlayPKG)

	@staticmethod
	def makeDMG(workDir, volName, outFile):
		'''
		Makes a new DMG for the Mumble app that resides in the workDir's content subdirectory.
		'''
		Signer.cmd(['hdiutil', 'create', '-srcfolder', os.path.join(workDir, 'content'),
					'-format', 'UDBZ', '-size', '1g', '-volname', volName, outFile])

	@staticmethod
	def makePKG(workDir, file):
		'''
		Flattens workDir's content into a PKG file.
		'''
		Signer.cmd(['pkgutil', '--flatten-full', workDir, file])

def main():
	p = argparse.ArgumentParser(usage='sign_macOS.py --input=<in.dmg> --output=<out.dmg> [--keep-tree]')
	p.add_argument('-c', '--config', help = 'Configuration file', default = os.path.join(pathlib.Path.home(), '.sign_macOS.cfg'))
	p.add_argument('-e', '--entitlements', help = 'Entitlements file')
	p.add_argument('-i', '--input', help = 'Input file')
	p.add_argument('-o', '--output', help = 'Output file')
	p.add_argument('-kt', '--keep-tree', action = 'store_true', dest = 'keepTree',
				   help = 'Keep the working tree after signing')
	args = p.parse_args()

	if not args.input:
		print('No input specified')
		sys.exit(1)

	if not args.output:
		print('No output specified')
		sys.exit(1)

	signer = Signer(args.config)

	inFile = os.path.abspath(args.input)
	outFile = os.path.abspath(args.output)
	workDir = tempfile.mkdtemp()

	print('Input: ' + inFile)
	print('Output: ' + outFile)
	print('Working dir: ' + workDir + '\n')

	if inFile.lower().endswith('.dmg'):
		volName = signer.extractDMG(inFile, workDir)

		signer.signOverlay(workDir)
		signer.signApp(workDir, args.entitlements)

		signer.makeDMG(workDir, volName, outFile)

		signer.codesign(outFile)
	elif inFile.lower().endswith('.pkg'):
		signer.extractPKG(inFile, workDir)

		files = []
		for file in os.listdir(workDir):
			files.append(os.path.join(workDir, file))

		signer.codesign(files)

		signer.makePKG(workDir, outFile)

		os.rename(outFile, outFile + '.intermediate')
		signer.prodsign(outFile + '.intermediate', outFile)
		os.remove(outFile + '.intermediate')
	else:
		shutil.copy(inFile, outFile)
		signer.codesign(outFile)

	print('')

	if not args.keepTree:
		shutil.rmtree(workDir, ignore_errors = True)
		print('Working tree removed\n')

	print('Signed file available at ' + args.output)

if __name__ == '__main__':
	main()