44import asyncio
55import aiohttp
66import gzip
7+ import hashlib
78import os
89import re
910import shutil
1617from collections import deque
1718from functools import cmp_to_key
1819
19- async def download_file (session , url , dest_path , max_retries = 3 , retry_delay = 2 , timeout = 60 ):
20+ async def download_file (session , url , dest_path , max_retries = 3 , retry_delay = 2 , timeout = 60 , checksum = None ):
2021 """Asynchronous file download with retries."""
2122 attempt = 0
2223 while attempt < max_retries :
@@ -25,19 +26,25 @@ async def download_file(session, url, dest_path, max_retries=3, retry_delay=2, t
2526 if response .status == 200 :
2627 with open (dest_path , "wb" ) as f :
2728 content = await response .read ()
29+
30+ # verify checksum if provided
31+ if checksum :
32+ sha256 = hashlib .sha256 (content ).hexdigest ()
33+ if sha256 != checksum :
34+ raise Exception (f"SHA256 mismatch for { url } : expected { checksum } , got { sha256 } " )
35+
2836 f .write (content )
2937 print (f"Downloaded { url } at { dest_path } " )
3038 return
3139 else :
32- print (f"Failed to download { url } , Status Code: { response .status } " )
33- break
40+ raise Exception (f"Failed to download { url } , Status Code: { response .status } " )
3441 except (asyncio .CancelledError , asyncio .TimeoutError , aiohttp .ClientError ) as e :
3542 print (f"Error downloading { url } : { type (e ).__name__ } - { e } . Retrying..." )
3643
3744 attempt += 1
3845 await asyncio .sleep (retry_delay )
3946
40- print (f"Failed to download { url } after { max_retries } attempts." )
47+ raise Exception (f"Failed to download { url } after { max_retries } attempts." )
4148
4249async def download_deb_files_parallel (mirror , packages , tmp_dir ):
4350 """Download .deb files in parallel."""
@@ -51,22 +58,21 @@ async def download_deb_files_parallel(mirror, packages, tmp_dir):
5158 if filename :
5259 url = f"{ mirror } /{ filename } "
5360 dest_path = os .path .join (tmp_dir , os .path .basename (filename ))
54- tasks .append (asyncio .create_task (download_file (session , url , dest_path )))
61+ tasks .append (asyncio .create_task (download_file (session , url , dest_path , checksum = info . get ( "SHA256" ) )))
5562
5663 await asyncio .gather (* tasks )
5764
58- async def download_package_index_parallel (mirror , arch , suites ):
65+ async def download_package_index_parallel (mirror , arch , suites , check_sig , keyring ):
5966 """Download package index files for specified suites and components entirely in memory."""
6067 tasks = []
6168 timeout = aiohttp .ClientTimeout (total = 60 )
6269
6370 async with aiohttp .ClientSession (timeout = timeout ) as session :
6471 for suite in suites :
6572 for component in ["main" , "universe" ]:
66- url = f"{ mirror } /dists/{ suite } /{ component } /binary-{ arch } /Packages.gz"
67- tasks .append (fetch_and_decompress (session , url ))
73+ tasks .append (fetch_and_decompress (session , mirror , arch , suite , component , check_sig , keyring ))
6874
69- results = await asyncio .gather (* tasks , return_exceptions = True )
75+ results = await asyncio .gather (* tasks )
7076
7177 merged_content = ""
7278 for result in results :
@@ -77,20 +83,75 @@ async def download_package_index_parallel(mirror, arch, suites):
7783
7884 return merged_content
7985
80- async def fetch_and_decompress (session , url ):
86+ async def fetch_and_decompress (session , mirror , arch , suite , component , check_sig , keyring ):
8187 """Fetch and decompress the Packages.gz file."""
82- try :
83- async with session .get (url ) as response :
84- if response .status == 200 :
85- compressed_data = await response .read ()
86- decompressed_data = gzip .decompress (compressed_data ).decode ('utf-8' )
87- print (f"Downloaded index: { url } " )
88- return decompressed_data
89- else :
90- print (f"Skipped index: { url } (doesn't exist)" )
91- return None
92- except Exception as e :
93- print (f"Error fetching { url } : { e } " )
88+
89+ path = f"{ component } /binary-{ arch } /Packages.gz"
90+ url = f"{ mirror } /dists/{ suite } /{ path } "
91+
92+ async with session .get (url ) as response :
93+ if response .status == 200 :
94+ compressed_data = await response .read ()
95+ decompressed_data = gzip .decompress (compressed_data ).decode ('utf-8' )
96+ print (f"Downloaded index: { url } " )
97+
98+ if check_sig :
99+ # Verify the package index against the sha256 recorded in the Release file
100+ release_file_content = await fetch_release_file (session , mirror , suite , keyring )
101+ packages_sha = parse_release_file (release_file_content , path )
102+
103+ sha256 = hashlib .sha256 (compressed_data ).hexdigest ()
104+ if sha256 != packages_sha :
105+ raise Exception (f"SHA256 mismatch for { path } : expected { packages_sha } , got { sha256 } " )
106+ print (f"Checksum verified for { path } " )
107+
108+ return decompressed_data
109+ else :
110+ print (f"Skipped index: { url } (doesn't exist)" )
111+ return None
112+
113+ async def fetch_release_file (session , mirror , suite , keyring ):
114+ """Fetch Release and Release.gpg files and verify the signature."""
115+
116+ release_url = f"{ mirror } /dists/{ suite } /Release"
117+ release_gpg_url = f"{ mirror } /dists/{ suite } /Release.gpg"
118+
119+ with tempfile .NamedTemporaryFile () as release_file , tempfile .NamedTemporaryFile () as release_gpg_file :
120+ await download_file (session , release_url , release_file .name )
121+ await download_file (session , release_gpg_url , release_gpg_file .name )
122+
123+ print ("Verifying signature of Release with Release.gpg." )
124+ # Use gpgv rather than gpg for verification. gpgv verifies a detached
125+ # signature against a fixed keyring without involving gpg-agent or
126+ # keyboxd, which makes it robust on hosts running GnuPG 2.4+ (e.g. Azure
127+ # Linux) where "gpg --keyring" routes through keyboxd and can fail.
128+ verify_command = ["gpgv" ]
129+ if keyring :
130+ verify_command += ["--keyring" , keyring ]
131+ verify_command += [release_gpg_file .name , release_file .name ]
132+ result = subprocess .run (verify_command , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
133+
134+ if result .returncode != 0 :
135+ raise Exception (f"Signature verification failed: { result .stderr .decode ('utf-8' )} " )
136+
137+ print ("Signature verified successfully." )
138+
139+ with open (release_file .name ) as f :
140+ return f .read ()
141+
142+ def parse_release_file (content , path ):
143+ """Parses the Release file and returns sha256 checksum of the specified path."""
144+
145+ # data looks like this:
146+ # <checksum> <size> <path>
147+ matches = re .findall (r'^ (\S*) +(\S*) +(\S*)$' , content , re .MULTILINE )
148+
149+ for entry in matches :
150+ # the file has both md5 and sha256 checksums, we want sha256 which has a length of 64
151+ if entry [2 ] == path and len (entry [0 ]) == 64 :
152+ return entry [0 ]
153+
154+ raise Exception (f"Could not find checksum for { path } in Release file." )
94155
95156def parse_debian_version (version ):
96157 """Parse a Debian package version into epoch, upstream version, and revision."""
@@ -171,13 +232,15 @@ def parse_package_index(content):
171232 filename = fields .get ("Filename" )
172233 depends = fields .get ("Depends" )
173234 provides = fields .get ("Provides" , None )
235+ sha256 = fields .get ("SHA256" )
174236
175237 # Only update if package_name is not in packages or if the new version is higher
176238 if package_name not in packages or compare_debian_versions (version , packages [package_name ]["Version" ]) > 0 :
177239 packages [package_name ] = {
178240 "Version" : version ,
179241 "Filename" : filename ,
180- "Depends" : depends
242+ "Depends" : depends ,
243+ "SHA256" : sha256
181244 }
182245
183246 # Update aliases if package provides any alternatives
@@ -233,7 +296,7 @@ def extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool):
233296 os .makedirs (extract_dir , exist_ok = True )
234297
235298 with tempfile .TemporaryDirectory (dir = tmp_dir ) as tmp_subdir :
236- result = subprocess .run (f" { ar_tool } t { os .path .abspath (deb_file )} " , cwd = tmp_subdir , check = True , shell = True , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
299+ result = subprocess .run ([ ar_tool , "t" , os .path .abspath (deb_file )] , cwd = tmp_subdir , check = True , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
237300
238301 tar_filename = None
239302 for line in result .stdout .decode ().splitlines ():
@@ -247,7 +310,8 @@ def extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool):
247310 tar_file_path = os .path .join (tmp_subdir , tar_filename )
248311 print (f"Extracting { tar_filename } from { deb_file } .." )
249312
250- subprocess .run (f"{ ar_tool } p { os .path .abspath (deb_file )} { tar_filename } > { tar_file_path } " , check = True , shell = True )
313+ with open (tar_file_path , "wb" ) as outfile :
314+ subprocess .run ([ar_tool , "p" , os .path .abspath (deb_file ), tar_filename ], check = True , stdout = outfile , stderr = subprocess .PIPE )
251315
252316 file_extension = os .path .splitext (tar_file_path )[1 ].lower ()
253317
@@ -268,7 +332,18 @@ def extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool):
268332 raise ValueError (f"Unsupported compression format: { file_extension } " )
269333
270334 with tarfile .open (tar_file_path , mode ) as tar :
271- tar .extractall (path = extract_dir , filter = 'fully_trusted' )
335+ tar .extractall (path = extract_dir , filter = _rootfs_extraction_filter )
336+
337+ def _rootfs_extraction_filter (member , dest_path ):
338+ """Tarfile extraction filter based on the 'data' filter that additionally
339+ rewrites absolute-target symlinks/hardlinks into rootfs-relative paths.
340+ """
341+ if (member .issym () or member .islnk ()) and os .path .isabs (member .linkname ):
342+ link_dir = os .path .dirname (member .name )
343+ new_linkname = os .path .relpath (member .linkname .lstrip ('/' ),
344+ start = link_dir or '.' )
345+ member = member .replace (linkname = new_linkname , deep = False )
346+ return tarfile .data_filter (member , dest_path )
272347
273348def finalize_setup (rootfsdir ):
274349 lib_dir = os .path .join (rootfsdir , 'lib' )
@@ -295,24 +370,17 @@ def finalize_setup(rootfsdir):
295370
296371if __name__ == "__main__" :
297372 parser = argparse .ArgumentParser (description = "Generate rootfs for .NET runtime on Debian-like OS" )
298- parser .add_argument ("--distro" , required = False , help = "Distro name (e.g., debian, ubuntu, etc.)" )
299373 parser .add_argument ("--arch" , required = True , help = "Architecture (e.g., amd64, loong64, etc.)" )
300374 parser .add_argument ("--rootfsdir" , required = True , help = "Destination directory." )
301375 parser .add_argument ('--suite' , required = True , action = 'append' , help = 'Specify one or more repository suites to collect index data.' )
302- parser .add_argument ("--mirror" , required = False , help = "Mirror (e.g., http://ftp.debian.org/debian-ports etc.)" )
376+ parser .add_argument ("--mirror" , required = True , help = "Mirror (e.g., http://ftp.debian.org/debian-ports etc.)" )
303377 parser .add_argument ("--artool" , required = False , default = "ar" , help = "ar tool to extract debs (e.g., ar, llvm-ar etc.)" )
378+ parser .add_argument ("--force-check-gpg" , required = False , action = 'store_true' , help = "Verify the packages against signatures in Release file." )
379+ parser .add_argument ("--keyring" , required = False , default = '' , help = "Keyring file to check signature of Release file." )
304380 parser .add_argument ("packages" , nargs = "+" , help = "List of package names to be installed." )
305381
306382 args = parser .parse_args ()
307383
308- if args .mirror is None :
309- if args .distro == "ubuntu" :
310- args .mirror = "http://archive.ubuntu.com/ubuntu" if args .arch in ["amd64" , "i386" ] else "http://ports.ubuntu.com/ubuntu-ports"
311- elif args .distro == "debian" :
312- args .mirror = "http://ftp.debian.org/debian-ports"
313- else :
314- raise Exception ("Unsupported distro" )
315-
316384 DESIRED_PACKAGES = args .packages + [ # base packages
317385 "dpkg" ,
318386 "busybox" ,
@@ -322,9 +390,16 @@ def finalize_setup(rootfsdir):
322390 "debianutils"
323391 ]
324392
325- print (f"Creating rootfs. rootfsdir: { args .rootfsdir } , distro: { args .distro } , arch: { args .arch } , suites: { args .suite } , mirror: { args .mirror } " )
393+ print (f"Creating rootfs. rootfsdir: { args .rootfsdir } , arch: { args .arch } , suites: { args .suite } , mirror: { args .mirror } " )
394+
395+ check_sig = args .force_check_gpg
396+ if check_sig and not args .keyring :
397+ print ("ERROR: --force-check-gpg requires --keyring to specify a keyring file for signature verification." )
398+ print ("Install the appropriate keyring package (e.g., debian-ports-archive-keyring, ubuntu-archive-keyring)" )
399+ print ("or pass --skipsigcheck to build-rootfs.sh to disable signature checking." )
400+ sys .exit (1 )
326401
327- package_index_content = asyncio .run (download_package_index_parallel (args .mirror , args .arch , args .suite ))
402+ package_index_content = asyncio .run (download_package_index_parallel (args .mirror , args .arch , args .suite , check_sig , args . keyring ))
328403
329404 packages_info , aliases = parse_package_index (package_index_content )
330405
0 commit comments