import collections
from binascii import hexlify
-from PIL import Image
+from PIL import Image, PngImagePlugin
import logging
from . import _
re.compile(".*(name='(?P<name>.*?)')(.*maxSdkVersion='(?P<maxSdkVersion>.*?)')?.*")
APK_FEATURE_PAT = re.compile(".*name='([^']*)'.*")
-screen_densities = ['640', '480', '320', '240', '160', '120']
+screen_densities = ['65534', '640', '480', '320', '240', '160', '120']
screen_resolutions = {
"xxxhdpi": '640',
"xxhdpi": '480',
SCREENSHOT_DIRS = ('phoneScreenshots', 'sevenInchScreenshots',
'tenInchScreenshots', 'tvScreenshots', 'wearScreenshots')
+BLANK_PNG_INFO = PngImagePlugin.PngInfo()
+
def dpi_to_px(density):
return (int(density) * 48) / 160
def get_icon_dir(repodir, density):
- if density == '0':
+ if density == '0' or density == '65534':
return os.path.join(repodir, "icons")
- return os.path.join(repodir, "icons-%s" % density)
+ else:
+ return os.path.join(repodir, "icons-%s" % density)
def get_icon_dirs(repodir):
logging.error("...FAILED to create page '{0}': {1}".format(pagename, e))
# Purge server cache to ensure counts are up to date
- site.pages['Repository Maintenance'].purge()
+ site.Pages['Repository Maintenance'].purge()
+
+ # Write a page with the last build log for this version code
+ wiki_page_path = 'update_' + time.strftime('%s', start_timestamp)
+ newpage = site.Pages[wiki_page_path]
+ txt = ''
+ txt += "* command line: <code>" + ' '.join(sys.argv) + "</code>\n"
+ txt += "* started at " + common.get_wiki_timestamp(start_timestamp) + '\n'
+ txt += "* completed at " + common.get_wiki_timestamp() + '\n'
+ txt += "\n\n"
+ txt += common.get_android_tools_version_log()
+ newpage.save(txt, summary='Run log')
+ newpage = site.Pages['update']
+ newpage.save('#REDIRECT [[' + wiki_page_path + ']]', summary='Update redirect')
def delete_disabled_builds(apps, apkcache, repodirs):
im.thumbnail((size, size), Image.ANTIALIAS)
logging.debug("%s was too large at %s - new size is %s" % (
iconpath, oldsize, im.size))
- im.save(iconpath, "PNG")
+ im.save(iconpath, "PNG", optimize=True,
+ pnginfo=BLANK_PNG_INFO, icc_profile=None)
except Exception as e:
logging.error(_("Failed resizing {path}: {error}".format(path=iconpath, error=e)))
Checks whether there are more than one classes.dex or AndroidManifest.xml
files, which is invalid and an essential part of the "Master Key" attack.
-
http://www.saurik.com/id/17
+
+ Janus is similar to Master Key but is perhaps easier to scan for.
+ https://www.guardsquare.com/en/blog/new-android-vulnerability-allows-attackers-modify-apps-without-affecting-their-signatures
"""
found_vuln = False
if not hasattr(has_known_vulnerability, "pattern"):
has_known_vulnerability.pattern = re.compile(b'.*OpenSSL ([01][0-9a-z.-]+)')
+ with open(filename.encode(), 'rb') as fp:
+ first4 = fp.read(4)
+ if first4 != b'\x50\x4b\x03\x04':
+ raise FDroidException(_('{path} has bad file signature "{pattern}", possible Janus exploit!')
+ .format(path=filename, pattern=first4.decode().replace('\n', ' ')) + '\n'
+ + 'https://www.guardsquare.com/en/blog/new-android-vulnerability-allows-attackers-modify-apps-without-affecting-their-signatures')
+
files_in_apk = set()
with zipfile.ZipFile(filename) as zf:
for name in zf.namelist():
app[key] = text
+def _strip_and_copy_image(inpath, outpath):
+ """Remove any metadata from image and copy it to new path
+
+ Sadly, image metadata like EXIF can be used to exploit devices.
+ It is not used at all in the F-Droid ecosystem, so its much safer
+ just to remove it entirely.
+
+ """
+
+ extension = common.get_extension(inpath)[1]
+ if os.path.isdir(outpath):
+ outpath = os.path.join(outpath, os.path.basename(inpath))
+ if extension == 'png':
+ with open(inpath, 'rb') as fp:
+ in_image = Image.open(fp)
+ in_image.save(outpath, "PNG", optimize=True,
+ pnginfo=BLANK_PNG_INFO, icc_profile=None)
+ elif extension == 'jpg' or extension == 'jpeg':
+ with open(inpath, 'rb') as fp:
+ in_image = Image.open(fp)
+ data = list(in_image.getdata())
+ out_image = Image.new(in_image.mode, in_image.size)
+ out_image.putdata(data)
+ out_image.save(outpath, "JPEG", optimize=True)
+ else:
+ raise FDroidException(_('Unsupported file type "{extension}" for repo graphic')
+ .format(extension=extension))
+
+
def copy_triple_t_store_metadata(apps):
"""Include store metadata from the app's source repo
sourcefile = os.path.join(root, f)
destfile = os.path.join(destdir, os.path.basename(f))
logging.debug('copying ' + sourcefile + ' ' + destfile)
- shutil.copy(sourcefile, destfile)
+ _strip_and_copy_image(sourcefile, destfile)
def insert_localized_app_metadata(apps):
if base in GRAPHIC_NAMES and extension in ALLOWED_EXTENSIONS:
os.makedirs(destdir, mode=0o755, exist_ok=True)
logging.debug('copying ' + os.path.join(root, f) + ' ' + destdir)
- shutil.copy(os.path.join(root, f), destdir)
+ _strip_and_copy_image(os.path.join(root, f), destdir)
for d in dirs:
if d in SCREENSHOT_DIRS:
if locale == 'images':
screenshotdestdir = os.path.join(destdir, d)
os.makedirs(screenshotdestdir, mode=0o755, exist_ok=True)
logging.debug('copying ' + f + ' ' + screenshotdestdir)
- shutil.copy(f, screenshotdestdir)
+ _strip_and_copy_image(f, screenshotdestdir)
repofiles = sorted(glob.glob(os.path.join('repo', '[A-Za-z]*', '[a-z][a-z][A-Z-.@]*')))
for d in repofiles:
if 'minSdkVersion' not in apk:
logging.warning("No SDK version information found in {0}".format(apk_file))
- apk['minSdkVersion'] = 1
+ apk['minSdkVersion'] = 3 # aapt defaults to 3 as the min
+ if 'targetSdkVersion' not in apk:
+ apk['targetSdkVersion'] = apk['minSdkVersion']
# Check for known vulnerabilities
if has_known_vulnerability(apk_file):
+ ' is not a valid minSdkVersion!')
else:
apk['minSdkVersion'] = m.group(1)
- # if target not set, default to min
- if 'targetSdkVersion' not in apk:
- apk['targetSdkVersion'] = m.group(1)
elif line.startswith("targetSdkVersion:"):
m = re.match(APK_SDK_VERSION_PAT, line)
if m is None:
if apkobject.get_max_sdk_version() is not None:
apk['maxSdkVersion'] = apkobject.get_max_sdk_version()
- apk['minSdkVersion'] = apkobject.get_min_sdk_version()
- apk['targetSdkVersion'] = apkobject.get_target_sdk_version()
+ if apkobject.get_min_sdk_version() is not None:
+ apk['minSdkVersion'] = apkobject.get_min_sdk_version()
+ if apkobject.get_target_sdk_version() is not None:
+ apk['targetSdkVersion'] = apkobject.get_target_sdk_version()
icon_id = int(apkobject.get_element("application", "icon").replace("@", "0x"), 16)
icon_name = arsc.get_id(apk['packageName'], icon_id)[1]
apkzip = zipfile.ZipFile(apkfile, 'r')
manifest = apkzip.getinfo('AndroidManifest.xml')
- if manifest.date_time[1] == 0: # month can't be zero
- logging.debug(_('AndroidManifest.xml has no date'))
- else:
- common.check_system_clock(datetime(*manifest.date_time), apkfilename)
+ # 1980-0-0 means zeroed out, any other invalid date should trigger a warning
+ if (1980, 0, 0) != manifest.date_time[0:3]:
+ try:
+ common.check_system_clock(datetime(*manifest.date_time), apkfilename)
+ except ValueError as e:
+ logging.warning(_("{apkfilename}'s AndroidManifest.xml has a bad date: ")
+ .format(apkfilename=apkfile) + str(e))
# extract icons from APK zip file
- iconfilename = "%s.%s.png" % (apk['packageName'], apk['versionCode'])
+ iconfilename = "%s.%s" % (apk['packageName'], apk['versionCode'])
try:
empty_densities = extract_apk_icons(iconfilename, apk, apkzip, repodir)
finally:
def extract_apk_icons(icon_filename, apk, apkzip, repo_dir):
- """
- Extracts icons from the given APK zip in various densities,
- saves them into given repo directory
- and stores their names in the APK metadata dictionary.
+ """Extracts PNG icons from an APK with the supported pixel densities
+
+ Extracts icons from the given APK zip in various densities, saves
+ them into given repo directory and stores their names in the APK
+ metadata dictionary. If the icon is an XML icon, then this tries
+ to find PNG icon that can replace it.
:param icon_filename: A string representing the icon's file name
:param apk: A populated dictionary containing APK metadata.
:param apkzip: An opened zipfile.ZipFile of the APK file
:param repo_dir: The directory of the APK's repository
:return: A list of icon densities that are missing
+
"""
+ res_name_re = re.compile(r'res/(drawable|mipmap)-(x*[hlm]dpi|anydpi).*/(.*)_[0-9]+dp.(png|xml)')
+ pngs = dict()
+ for f in apkzip.namelist():
+ m = res_name_re.match(f)
+ if m and m.group(4) == 'png':
+ density = screen_resolutions[m.group(2)]
+ pngs[m.group(3) + '/' + density] = m.group(0)
+
+ icon_type = None
empty_densities = []
for density in screen_densities:
if density not in apk['icons_src']:
continue
icon_src = apk['icons_src'][density]
icon_dir = get_icon_dir(repo_dir, density)
- icon_dest = os.path.join(icon_dir, icon_filename)
+ icon_type = '.png'
# Extract the icon files per density
if icon_src.endswith('.xml'):
- png = os.path.basename(icon_src)[:-4] + '.png'
- for f in apkzip.namelist():
- if f.endswith(png):
- m = re.match(r'res/(drawable|mipmap)-(x*[hlm]dpi).*/', f)
- if m and screen_resolutions[m.group(2)] == density:
- icon_src = f
+ m = res_name_re.match(icon_src)
+ if m:
+ name = pngs.get(m.group(3) + '/' + str(density))
+ if name:
+ icon_src = name
if icon_src.endswith('.xml'):
empty_densities.append(density)
- continue
+ icon_type = '.xml'
+ icon_dest = os.path.join(icon_dir, icon_filename + icon_type)
+
try:
with open(icon_dest, 'wb') as f:
f.write(get_icon_bytes(apkzip, icon_src))
- apk['icons'][density] = icon_filename
+ apk['icons'][density] = icon_filename + icon_type
except (zipfile.BadZipFile, ValueError, KeyError) as e:
logging.warning("Error retrieving icon file: %s %s", icon_dest, e)
del apk['icons_src'][density]
empty_densities.append(density)
+ # '-1' here is a remnant of the parsing of aapt output, meaning "no DPI specified"
if '-1' in apk['icons_src']:
icon_src = apk['icons_src']['-1']
- icon_path = os.path.join(get_icon_dir(repo_dir, '0'), icon_filename)
+ icon_type = icon_src[-4:]
+ icon_path = os.path.join(get_icon_dir(repo_dir, '0'), icon_filename + icon_type)
with open(icon_path, 'wb') as f:
f.write(get_icon_bytes(apkzip, icon_src))
- try:
- im = Image.open(icon_path)
- dpi = px_to_dpi(im.size[0])
- for density in screen_densities:
- if density in apk['icons']:
- break
- if density == screen_densities[-1] or dpi >= int(density):
- apk['icons'][density] = icon_filename
- shutil.move(icon_path,
- os.path.join(get_icon_dir(repo_dir, density), icon_filename))
- empty_densities.remove(density)
- break
- except Exception as e:
- logging.warning(_("Failed reading {path}: {error}")
- .format(path=icon_path, error=e))
+ if icon_type == '.png':
+ im = None
+ try:
+ im = Image.open(icon_path)
+ dpi = px_to_dpi(im.size[0])
+ for density in screen_densities:
+ if density in apk['icons']:
+ break
+ if density == screen_densities[-1] or dpi >= int(density):
+ apk['icons'][density] = icon_filename
+ shutil.move(icon_path,
+ os.path.join(get_icon_dir(repo_dir, density), icon_filename))
+ empty_densities.remove(density)
+ break
+ except Exception as e:
+ logging.warning(_("Failed reading {path}: {error}")
+ .format(path=icon_path, error=e))
+ finally:
+ if im and hasattr(im, 'close'):
+ im.close()
if apk['icons']:
- apk['icon'] = icon_filename
+ apk['icon'] = icon_filename + icon_type
return empty_densities
def fill_missing_icon_densities(empty_densities, icon_filename, apk, repo_dir):
"""
- Resize existing icons for densities missing in the APK to ensure all densities are available
+ Resize existing PNG icons for densities missing in the APK to ensure all densities are available
:param empty_densities: A list of icon densities that are missing
:param icon_filename: A string representing the icon's file name
:param apk: A populated dictionary containing APK metadata. Needs to have 'icons' key
:param repo_dir: The directory of the APK's repository
+
"""
+ icon_filename += '.png'
# First try resizing down to not lose quality
last_density = None
for density in screen_densities:
+ if density == '65534': # not possible to generate 'anydpi' from other densities
+ continue
if density not in empty_densities:
last_density = density
continue
size = dpi_to_px(density)
im.thumbnail((size, size), Image.ANTIALIAS)
- im.save(icon_path, "PNG")
+ im.save(icon_path, "PNG", optimize=True,
+ pnginfo=BLANK_PNG_INFO, icc_profile=None)
empty_densities.remove(density)
except Exception as e:
logging.warning("Invalid image file at %s: %s", last_icon_path, e)
config = None
options = None
+start_timestamp = time.gmtime()
def main():