Данная статья применима к:
- Astra Linux Special Edition РУСБ.10015-01 (очередное обновление 1.7)
- Astra Linux Special Edition РУСБ.10152-02 (очередное обновление 4.7)
- Astra Linux Special Edition РУСБ.10015-01 (очередное обновление 1.6)
- Astra Linux Special Edition РУСБ.10015-16 исп. 1
- Astra Linux Common Edition 2.12
Оригинальная статья: https://wiki.debian.org/DebianInstaller/Modify/CD
Введение
В данной статье рассматривается создание модифицированного установочного диска путем создания загрузочного образа с измененным составом deb-пакетов. Подразумевается, что служебные пакеты (udebs) не изменяются. Для изменения пакетов udeb используется отдельная процедура (см. how to build a full image with a custom kernel). Новый образ создается с использованием образа стандартного установочного диска (и, по необходимости, других дисков). Все основные действия выполняются от имени непривилегированного пользователя, привилегии суперпользователя (в Astra Linux Special Edition с включенным МКЦ - привилегий суперпользователя с высоки уровнем целостности) требуются только для установки пакетов, монтирования носителей (если используется) и операции записи созданного образа на носитель.
Создание распакованной копии установочного диска
При написании статьи использовался ISO-образ установочного диска Astra Linux Special Edition РУСБ.10015-01 (очередное обновление 1.7) сохраненный в файле с именеми 1.7.0-11.06.2021_12.40.iso. Для распаковки образа:
Установить пакет bsdtar, если он не был ранее установлен:
sudo apt install bsdtar- Создать подкаталог для распаковки:
mkdir ~/cd - Распаковать ISO-образ в созданный каталог:
bsdtar -xf Загрузки/1.7.0-11.06.2021_12.40.iso -C ~/cd - Разрешить запись в распакованные файлы:
chmod -R +w cd
Изменение состава пакетов в репозитории
В составе распакованного образа важны следующие каталоги:
- каталог ~/cd/pool/ содержит пакеты, и в него должны добавляться дополнительные пакеты;
- каталог ~/cd/dists/1.7.0_x86-64/main/binary-amd64 содержит список пакетов (файл Packages.gz) и файл Release.
Добавить новые пакеты можно любым удобным способом, например, скопировать их из репозитория или:
- не используя права суперпользователя распаковать образ диска с помощью команды bsdtar скопировать их в соответствующие подкаталоги каталога с распакованным ISO-образом ~/cd/pool;
- используя права суперпользователя примонтировать диск (образ диска) и так же выполнить копирование;
Ненужные пакеты можно просто удалить.
Изменение файла preseed.cfg
chmod +w -R isofiles/install.386/
gunzip isofiles/install.386/initrd.gz
echo preseed.cfg | cpio -H newc -o -A -F isofiles/install.386/initrd
gzip isofiles/install.386/initrd
chmod -w -R isofiles/install.386/
Regenerating md5sum.txt
cd isofiles
chmod +w md5sum.txt
find -follow -type f ! -name md5sum.txt -print0 | xargs -0 md5sum > md5sum.txt
chmod -w md5sum.txt
cd ..
Обновление индексов Packages, Release и контрольных сумм md5sum.txt
После изменения состава пакетов необходимо обновить индексные файлы (Packages, Packages.gz и Release) и контрольные суммы (файл md5sums.txt). Для этого:
Создать файл config-deb со следующим содержимым:
# Указание на подкаталог, содержащий распакованный диск Dir { ArchiveDir "cd"; }; # Указание на начало дерева каталогов, содержащих deb-файлы TreeDefault { Directory "pool/"; }; # Указание на расположение файла Packages BinDirectory "pool/main" { Packages "dists/1.7_x86-64/main/binary-amd64/Packages"; }; # Расширение индексируемых файлов Default { Packages { Extensions ".deb"; }; };
Выполнить индексирование командой:
apt-ftparchive generate config-deb
pool/main: New 5 437 kB 3159 files 2 616 MB 37с
Packages done, Starting contents.
Done. 2 616 MB in 3159 archives. Took 37с- cd ~/cd; dpkg-scanpackages --arch amd64 pool/ > dists/stable/main/binary-amd64/Packages ; cd ..
- Обновить контрольные суммы, для чего:
- Удалить старые контрольные суммы из файла cd/dists/1.7_x86-64/Release:
sed -i '/MD5Sum:/,$d' ~/cd/dists/1.7_x86-64/Release - Добавить новые контрольные суммы:
apt-ftparchive packages cd/pool/main > cd/dists/1.7_x86-64/main/binary-amd64/Packages
cat cd/dists/1.7_x86-64/main/binary-amd64/Packages | gzip -9 > cd/dists/1.7_x86-64/main/binary-amd64/Packages.gz
apt-ftparchive release cd/dists/ >> cd/dists/1.7_x86-64/Release - Обновить контрольные суммы в файле cd/md5sum.txt:
cd cd; md5sum `find ! -name "md5sum.txt" ! -path "./isolinux/*" -follow -type f` > md5sum.txt; cd ..
Предупреждение
find: Обнаружено зацикливание в файловой системе; ‘./astra’ является частью той же петли файловой системы что и ‘.’.
можно игнорировать
- Удалить старые контрольные суммы из файла cd/dists/1.7_x86-64/Release:
Можно проверить корректность репозитория, для чего:
- Примонтировать обновленную структуру:
sudo mount -o bind $HOME/cd /mnt - Указать репозиторий в составе источников пакетов:
deb [trusted=yes] file:/mnt 1.7_x86-64 main contrib non-free - Обновить списки пакетов:
sudo apt update - Проверить доступность добавленных пакетов:
apt policy <имя_добавленного_пакета>
Добавление переопределений (overriding)
В данной статье не рассматривается. См. оригинальную статью: https://wiki.debian.org/DebianInstaller/Modify/CD
Создание загрузочного ISO-образа, запись загрузочного носителя
Для создания загрузочного образа используется пакет xorriso. Если пакет ранее не был установлен, то установить его можно командой:
sudo apt install xorriso
также для создания нового загрузочного образа при отсутствии старого образа загрузочного диска может понадобиться пакет isolinux (комментарии см. ниже):
sudo apt unstall isolinux
Для создания загрузочного образа:
- Запретить запись в файловые объекты распакованного образа:
chmod -R -w cd - Получить загрузочную запись (MBR). Сделать это можно двумя способами:
- Не используя привилегии суперпользователя при наличии исходного загрузочного образа извлечь оригинальный запись из него и сохранить в файле isohdpfx.bin:
dd if=1.7.0-11.06.2021_12.40.iso bs=1 count=432 of=isohdpfx.bin
Этот способ является предпочтительным, так как гарантирует совместимость полученной записи с ISO-образом. Далее предполагается, что используется именно этот способ; - Используя привилегии суперпользователя установить пакет isolinux и использовать входящий в него файл /usr/lib/ISOLINUX/isohdpfx.bin;
- Не используя привилегии суперпользователя при наличии исходного загрузочного образа извлечь оригинальный запись из него и сохранить в файле isohdpfx.bin:
- Создать образ командой:
xorriso -as mkisofs -isohybrid-mbr isohdpfx.bin -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table -c isolinux/boot.cat -V "WIKI_ISO"\
-eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot -isohybrid-gpt-basdat -append_partition 2 0xef cd/boot/grub/efi.img \
-o wiki_iso.iso ./cd
основные опции команды (полное описание см man xorriso):- isohdpfx.bin - имя файла с MBR (при использовании пакета isolinux - /usr/lib/ISOLINUX/isohdpfx.bin);
- -V "WIKI_ISO" - метка (label) создаваемого образа;
- -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot -isohybrid-gpt-basdat -append_partition 2 0xef cd/boot/grub/efi.img - опции для загрузки с помощью UEFI;
- -o wiki_iso.iso - имя файла, в котором будет сохранен образ;
- ./cd - рабочий каталог
Запись созданного образа на USB-носитель выполняется так же, как для штатных образов Astra Linux: Создание загрузочных носителей USB flash drive (требуются привилегии суперпользователя). Или, для записи на оптический диск:
xorriso -as cdrecord -v dev=/dev/sr0 -eject wiki_iso.iso
Installing From the New Image
Installing Debian from the new i386 ISO is just a matter of providing a computer's input device with it, booting from it and choosing the installation method. Perhaps, however, there is one thing to be aware of, depending on how it is intended to use the archive after installation. With a connection to the internet any package updates that are available (security updates, for example) would normally be pulled in during the installation of the image. Archive information would now become outdated and some packages from an archive would be uninstallable. If this is unwanted, use one of these two solutions:
- Dispense with a network connection during the installation.
Press the TAB key at the boot menu and add pkgsel/upgrade=none to the command line (after quiet).
On the other hand, if the intention is to have access to stable updates and security fixes on the installed system, add
deb http://deb.debian.org/debian stable main contrib
after the package archive entry.
Packages not available in the package archive will come from deb.debian.org.
Accessing the New Image's Archive
At first boot of the new operating system /etc/apt/sources.list will have a line something like this:
deb cdrom:[Debian GNU/Linux 9.3.0 _Stretch_ - Official i386 NETINST 20171209-13:03]/ stretch contrib main non-free
Change that to
deb [trusted=yes] cdrom:[Debian GNU/Linux 9.3.0 _Stretch_ - Official i386 NETINST 20171209-13:03]/ stretch contrib main non-free
apt update
should now produce a positive outcome.
Assuming the installation image and the archive is held on a a USB device, its block device (found from lsblk), can be mounted (as root) with
mount /dev/sdX /media/cdrom
and packages installed with
apt install <package>
Alternatively, a USB devices's LABELs can be found from
lsblk -f
and used for automatic mounting as described below. Automatically mounting a partition on the device when it is accessed and automatically unmounting it when access to it is not wanted can be done with an entry in /etc/fstab. All the parameters necessary for this to happen are available from systemd 220 onwards and explained in the systemd.mount manual. Comment out any /dev/srX entry in /etc/fstab.
LABEL=ISOIMAGE /media/cdrom0 iso9660 defaults, noauto,x-systemd.automount,x-systemd.idle-timeout=5,x-systemd.device-timeout=1 0 0
x-systemd.automount mounts /media/cdrom when any command wants to use it.
systemd.idle-timeout leads to unmounting the partition a specified time period after the calling program ceases to access it.
noauto causes /media/cdrom not to be mounted while the machine is booting.
x-systemd.device-timeout configures how long systemd should wait when no device is plugged in or an incorrect device is found.
On a running system, do
systemctl daemon reload
followed by
systemctl restart media-cdrom0.automount
after changing /etc/fstab.
Miscellaneous
The account in the previous sections should be sufficient to obtain a bootable, remastered ISO image. The following material was part of the original page and is left here in the event that some of it could prove useful.
Files and hooks
A list of hooks available for debian-installer: https://d-i.debian.org/doc/internals/apb.html
(filepaths as seen from the installer)
List of packages (udebs) to install or not install in into the d-i ramdisk.
''cdrom''.disk/udeb_include ["anna"] ''cdrom''.disk/udeb_exclude
The content of these files are taken as lists of packages to install or not into the target area.
''cdrom''.disk/base_include [base-installer] ''cdrom''.disk/base_exclude
If the file ''cdrom''.disk/base_installable exists, the base-installer udeb selects the cdrom as source for the installation.
Alternate Method
If you use apt-move to store the packages apt downloads when updating your system, you can use the mirror it creates to fill the cdrom with all the packages on your current system. Remember to call "apt-move sync" before mastering the image, to make sure, all dependencies are met.
Helper scripts: diunpk, dipk
Here are example scripts for unpacking and packing d-i CD image file. You need to have aufs modules available. * diunpk: execute this with d-i.iso file as its argument. This generates tree under dated directory and cd into it.
#!/bin/sh -e # Local customization to match your id (check with 'id' command). uid=1000 gid=1000 # Default values # $1 d-i iso image file # $2 d-i ro mount point # $3 d-i rw tree di_iso=${1:-d-i.iso} di_ro=${2:-d-i.ro} di_rw=${3:-d-i.rw} pwd=$(pwd) timestamp=$(date -u +%Y%m%d%H%M%S) mkdir $timestamp mkdir $timestamp/$di_ro mkdir $timestamp/$di_rw sudo mount ${di_iso} $timestamp/${di_ro} -t iso9660 -o loop,uid=${uid},gid=${gid} sudo mount -t aufs -o br:$timestamp/${di_rw}:$timestamp/${di_ro} none $timestamp/${di_rw} sudo chmod u+w $timestamp/${di_rw} sudo chmod u+w $timestamp/${di_rw}/md5sum.txt sudo find $timestamp/${di_rw}/dists -exec chmod u+w {} \; sudo find $timestamp/${di_rw}/pool -type d -exec chmod u+w {} \; cd $timestamp
* dipk: execute this in dated directory.
#!/bin/sh -e set -x # Local customization uid=1000 gid=1000 arch=amd64 release=squeeze # Default values # $1 d-i iso image file # $2 d-i ro mount point # $3 d-i rw tree di_iso=${1:-d-i.iso} di_ro=${2:-d-i.ro} di_rw=${3:-d-i.rw} cat > config << EOF Dir { ArchiveDir "."; OverrideDir "."; CacheDir "."; }; TreeDefault { Directory "pool/"; }; BinDirectory "pool/main" { Packages "dists/${release}/main/debian-installer/binary-${arch}/Packages"; }; Default { Packages { Extensions ".udeb"; }; }; EOF cd $di_rw sudo apt-ftparchive generate ../config sudo md5sum $(find ! -name "md5sum.txt" ! -path "./isolinux/*" -follow -type f) > md5sum.txt cd - #genisoimage ... sudo genisoimage -r -o $di_iso -V di$(date -u +%m%d%H%M%S) \ -b isolinux/isolinux.bin -c isolinux/boot.cat \ -no-emul-boot -boot-load-size 4 -boot-info-table $di_rw # check mounted by "mount" #sudo umount ${di_rw} #sudo umount ${di_ro} #rm -rf $di_rw
Create a udeb packages file
Write a config-udeb file with something like this :
Dir { ArchiveDir "cd"; OverrideDir "indices"; CacheDir "indices"; }; TreeDefault { Directory "pool/"; }; BinDirectory "pool/main" { Packages "dists/squeeze/main/binary-i386/Packages"; BinOverride "override"; ExtraOverride "override.extra"; }; Default { Packages { Extensions ".udeb"; }; };
Because of the BinOverride line you also need the override file, you can get it from any debian mirror, e.g. get http://ftp.de.debian.org/debian/indices/override.squeeze.main.gz and extract it to the indices/override.
Now go into the directory with your config file and run
apt-ftparchive generate config-udeb
to generate the Packages and Releases files.
To update the cd/dists/squeeze/Release file, make a new text file called config-rel with something like this:
APT::FTPArchive::Release::Codename "squeeze"; APT::FTPArchive::Release::Origin "Debian"; APT::FTPArchive::Release::Components "main"; APT::FTPArchive::Release::Label "Debian"; APT::FTPArchive::Release::Architectures "i386"; APT::FTPArchive::Release::Suite "testing";
To generate the Release file, run
# apt-ftparchive -c config-rel release cd/dists/squeeze > cd/dists/squeeze/Release
See Also
Adding a preseed file to a modified installation ISO.
An alternative preseeding and package archive technique.