Дерево страниц

Сравнение версий

Ключ

  • Эта строка добавлена.
  • Эта строка удалена.
  • Изменено форматирование.

Оглавление

См. также: https://wiki.debian.org/DebianInstaller/Modify/CD


Информация
titleДанная статья применима к:
  • Astra Linux Special Edition РУСБ.10015-01 (очередное обновление 1.7)Astra Linux Special Edition РУСБ.10152-02 и РУСЬ.10015-10 (очередное обновление 41.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



Предупреждение

Ответственность за применение и сопровождение модифицированных операционных систем, установленных с модифицированных установочных носителей, полностью лежит на авторах этих носителей. Замкнутость полученного дистрибутива не проверяется и возможность установки из него пакетов не гарантируется. Стандартная техническая поддержка Astra Linux не распространяется на такие системы. Действие сертификатов Astra Linux не распространяется на такие системы.
См. также:


Введение

В данной статье рассматривается создание модифицированного установочного диска. Модифицированный образ создается на основе стандартного образа установочного диска Astra Linux Special Edition РУСБ.10015-01 очередное обновление 1.7. Модификация подразумевает изменение состава DEB-пакетов и preseed-сценария. Подразумевается, что служебные пакеты (udebs) не изменяются. Для изменения пакетов udeb используется отдельная процедура (см. how to build a full image with a custom kernel). Все основные действия выполняются от имени непривилегированного пользователя, привилегии суперпользователя (в Astra Linux Special Edition с включенным МКЦ - привилегий суперпользователя с высоки уровнем целостности) требуются только для установки пакетов, монтирования носителей (если используется) и операции записи созданного образа на носитель.

Подготовка компьютера

Для выполнения дальнейших действий на компьютер, на котором будут создаваться модифицированные образы, установить необходимые пакеты:

Command
sudo apt install bsdtar reprepro xorriso build-essential debootstrap

Создание распакованной копии установочного диска

Далее предполагается, что образ установочного диска загружен в домашний каталог текущего пользователя и что все действия выполняются в этом домашнем каталоге. Для распаковки загруженного образа:

  1. Создать подкаталог для распаковки:

    Command
    mkdir ~/cd


  2. Распаковать ISO-образ в созданный каталог:

    Command
    bsdtar -xf <имя_файла_с_образом> -C ~/cd


  3. Для выполнения дальнейших модификаций разрешить запись в распакованные файлы:

    Command
    chmod -R +w ~/cd


В результате этого шага в подкаталоге cd домашнего каталога текущего пользователя будет создан подкаталог cd с копией содержимого образа установочного диска, и будет разрешено вносить изменения в содержимое этой копии.

Создание и пакетизация собственного ключа для подписания измененного установочного образа

Создание собственного ключа

Предупреждение
Для подписания измененного установочного образа следует использовать ключи, выпущенные в соответствии с установленными в организации правилами. Приведенный далее пример создания ключа применим исключительно в демонстрационных целях.
  1. Зафиксировать имя, которое будет использоваться в ключе. Обычно в качестве такого имени применяют адрес электронной почты, который для повторного применения удобно экспортировать в переменную окружения:

    Command
    mail="<адрес_электронной_почты>"

    например:

    Command
    mail="support@organization.ru"


  2. Создать конфигурационный файл gen-key.cfg с параметрами генерации ключа. Содержимое файла:


    Блок кода
    Key-Type: 1
    %no-protection
    Key-Length: 4096
    Subkey-Type: 1
    Subkey-Length: 4096
    Name-Real: <имя_владельца_ключа>
    Name-Email: <адрес_электронной_почты>
    Expire-Date: 0


    Создать такой файл можно следующей командой (в качестве имени владельца ключа используется имя support, для указания адреса электронной почты используется ранее экспортированная переменная mail):

    Command
    echo "Key-Type: 1
    %no-protection
    Key-Length: 4096
    Subkey-Type: 1
    Subkey-Length: 4096
    Name-Real: support
    Name-Email: $mail
    Expire-Date: 0" > gen-key.cfg


  3. Выполнить генерацию ключа используя созданный конфигурационный файл:

    Command
    gpg --batch --gen-key gen-key.cfg

    опции команды:
    --batch - генерация ключа без запросов подтверждений;
    --gen-key - команда генерации ключа;
    gen-key.cfg - конфигурационный файл с параметрами генерации ключа.

  4. Экспортировать созданный ключ в файл с именем <адрес_электронной_почты>.gpg.key (удобно опять использовать значение ранее созданной переменной окружения mail):

    Command
    gpg --armor --output "$mail.gpg.key" --export "$mail"

    опции команды:
    --armor - экспорт в формате ASCII;
    --output "$mail.gpg.key" - имя файла, в котором сохраняется экспортированный ключ (в имени файла используется значение ранее созданной переменной окружения);
    --export "$mail" - указание операции (экспорт) и имя экспортируемого объекта  (используется значение ранее созданной переменной окружения);

  5. Импортировать экспортированный ключ в комплект ключей Astra Linux:

    Command
    sudo gpg --no-default-keyring --keyring /usr/share/apt/astra-archive.gpg --import "$mail.gpg.key"

    Далее копия созданного ключа, находящаяся в комплекте ключей Astra Linux, будет использована для подписания измененного репозитория установочного диска.

Пакетизация собственного ключа

Информация
Для того, чтобы исключить проверку подписей пакетов при установке, можно в файл /boot/grub/grub.cfg добавить опцию debian-installer/allow-unauthenticated=true.

Для того, чтобы подпись репозитория, сделанная собственным ключом, могла быть проверена при установке операционной системы с модифицированного носителя собственный ключ должен быть включен в репозитории установочного диска. Это можно сделать оформив примитивный  UDEB-пакет:

  1. Экспортировать ключ в файл:

    Command
    gpg --output "$mail.gpg" --export "$mail"

    в данном случае экспорт выполняется в двоичном формате, а не в формате ASCII;

  2. Установить права доступа на файл с экспортированным ключом:

    Command
    sudo chmod 644 "$mail.gpg"


  3. Создать UDEB-пакет для включения собственного ключа в модифицированный дистрибутив. Для примера далее используется имя пакета aptkey:
    1. Для удобства работы сохранить имя пакета в переменной окружения. Это можно сделать командой:

      Command
      package="aptkey"


    2. Создать подкаталог для размещения пакета:

      Command
      mkdir -p "$package/DEBIAN"


    3. Создать файл $package/DEBIAN/control с параметрами пакета (в приведенном примере команды используются значения ранее заданных переменных окружения):

      Command
      echo "Package: $package
      Version: 1.0
      Section: debian-installer
      Priority: important
      Architecture: all
      Essential: no
      Installed-Size: 1024
      Maintainer: $mail
      #Package-Type: udeb
      #XC-Package-Type: udeb
      Description: Add own keyring to apt
      Depends: apt" > "$package/DEBIAN/control"


    4. Создать файл $package/DEBIAN/postinst постустановочного сценария (сценарий нечего не делает, возвращая код завершения 0 (успешное окончание)) и присвоить файлу со сценарием разрешение на выполнение:

      Command
      echo "exit 0" > "$package/DEBIAN/postinst"
      chmod 0755 "$package/DEBIAN/postinst"


    5. Создать и наполнить структуру каталогов с данными пакета:

      Command
      mkdir -p "$package/etc/apt/trusted.gpg.d"
      cp "$mail.gpg" "$package/etc/apt/trusted.gpg.d/"

      Экспортированный ключ помещается в каталог пакета "$package/etc/apt/trusted.gpg.d" чтобы при установке пакета этот ключ был размещен в системном каталоге доверенных ключей /etc/apt/trusted.gpg.d;

    6. Собрать пакет:

      Command
      dpkg-deb --build "$package"


    7. Экспортированный ключ переместить в каталог доверенных ключей рабочей системы:

      Command
      sudo mv "$mail.gpg" /etc/apt/trusted.gpg.d/


Изменение состава пакетов в репозитории

Предупреждение
После изменения состава пакетов репозитория репозиторий перестает быть подписанным ключами ООО "РусБИТех-Астра" (становится неподписанным).
    1. Создать каталог для временной копии репозитория. Для примера использовано имя каталога cache:

      Command
      mkdir -p cache


    2. Переместить в созданный временный каталог DEB- и UDEB-пакеты из копии установочного диска:

      Command

      find cd/pool -name \*.deb -print -exec mv {} cache \;
      find cd/pool -name \*.udeb -exec mv {} cache \;


    3. Переместить (или скопировать) в созданный временный каталог ранее созданный пакет с собственным ключом:

      Command
      mv "$package.deb" "cache/${package}_1.0.deb"


    4. Очистить копию установочного диска от ненужных каталогов:

      Command
      rm -rf $HOME/cd/{db,dists,pool}


    5. Выполнить модернизацию состава пакетов дистрибутива:

      1. Добавить во временный каталог собственные пакеты;

      2. Удалить во временном каталоге ненужные пакеты;

    6. Создать в каталоге с копией установочного диска подкаталог ~/cd/conf:

      Command
      mkdir -p ~/cd/conf


    7. Создать конфигурационный файл ~/cd/conf/distributions для восстановления репозитория:

      Command

      echo 'Origin: Debian
      Codename: 1.7_x86-64
      Suite: stable
      Version: 1.7.0
      Architectures: amd64
      Components: main contrib non-free
      UDebComponents: main
      SignWith: yes' > ~/cd/conf/distributions


Приведенная для примера конфигурация использует дистрибутив Astra Linux Special Edition РУСБ.10015-01 очередное обновление 1.7, архитектура amd64, компоненты main, contrib, nonfree. При использовании других дистрибутивов параметры конфигурации должны быть соответственно откорректированы;

  1. Инициализировать репозиторий:

    Command
    reprepro -b cd/ export 1.7_x86-64


  2. Выгрузить ключ для подписи репозитория:

    Command
    gpg --yes --armor -o ~/cd/dists/1.7_x86-64/Release.gpg -sb ~/cd/dists/1.7_x86-64/Release


  3. Наполнить репозиторий пакетами, сохраненными во временном каталоге cache:

    Command
    reprepro --ask-passphrase -Vb cd includedeb  1.7_x86-64 cache/*.deb
    reprepro --ask-passphrase -Vb cd includeudeb 1.7_x86-64 cache/*.udeb


  4. Обновить файл с контрольными суммами:

    Command
    cd ~/cd; find ! -name md5sum.txt ! -name gostsums.txt -follow -type f -print0 | xargs -0 md5sum > md5sum.txt ; cd ..

    Предупреждение 

    Информация

    find: Обнаружено зацикливание в файловой системе; ...

    можно игнорировать.

  5. Восстановить структуру ссылок репозитория:

    Command
    ln -s 1.7_x86-64 ~/cd/dists/stable


  6. Удалить ненужный каталог ~/cd/conf и временные копии пакетов:

    Command
    rm -rf ~/cd/conf ~/cd/db cache


Замена файла конфигурации установки preseed.cfg при установке

На установочном диске содержится файл с ответами на вопросы установщика ОС - файл preseed.cfg. Для простой автоматизации установки можно задать альтернативный файл непосредственно при установке ОС. Эта возможность не обеспечивает полной автоматизации установки, так всегда будут запрашиваться подтверждение согласия с лицензией и выбор клавиш переключения клавиатуры, но может упростить и стандартизировать установку ОС. 

Для замены файла preseed.cfg:

  1. При использовании установочных носителей созданных на USB-накопителях (на модифицируемых носителях) для замены файла preseed:
    1. Примонтировать носитель.
    2. Скопировать заменяющий файл (например, preseed.cfg) в корень установочного  носителя;
    3. Внести в файл boot/grub/grub.cfg в строки с параметрами загрузки ядра (начинаются со слова linux) указание файла preseed, например:

      Блок кода
      linux /install.amd/vmlinuz quiet modprobe.blacklist=evbug astra_install=1 nomodeset debian-installer/locale=ru debian-installer/language=ru keyboard-configuration/xkb-keymap=ru console-keymaps-at/keymap=ru preseed/file=/cdrom/preseed.cfg


    4. Отмонтировать накопитель.

  2. При использовании немодифицируемых установочных носителей (CD-ROM, DVD-ROM) заменяющий файл можно предоставить с помощью USB-накопителя: 
    1. Подготовить накопитель: 
      1. Подключить USB-накопитель к компьютеру.

      2. Отформатировать USB-накопитель файловой системой vfat без создания дискового раздела:

        Предупреждение
        При форматировании все данные с накопителя будут удалены.
        При форматировании использовать имя накопителя (например, sdh), а не имя дискового раздела (sdh1).


        Command
        sudo mkfs.vfat -I /dev/<имя_накопителя>


      3. Примонтировать накопитель.

      4. Скопировать заменяющий preseed файл на накопитель.

      5. Отмонтировать накопитель.

    2. При установке ОС:

      1. Выбрать язык установки.

      2. Не нажимая Enter выбрать способ установки (графический или текстовый).

      3. Нажать F2. Откроется список выбора параметров ядра.

      4. Нажать Esc. Список выбора параметров ядра закроется, и можно будет непосредственно редактировать строку параметров ядра.

      5. В строку параметров ядра добавить указание файла preseed, при этом использовать не каталог /cdrom, а каталог /media, например:

        Блок кода
        linux /install.amd/vmlinuz quiet modprobe.blacklist=evbug astra_install=1 nomodeset debian-installer/locale=ru debian-installer/language=ru keyboard-configuration/xkb-keymap=ru console-keymaps-at/keymap=ru preseed/file=/media/preseed.cfg


      6. Нажать Enter.

Как упоминается ранее, при таком использовании полная автоматизация не обеспечивается, и всегда придется согласиться с лицензией и выбрать клавиши переключения языка. Порядок дальнейшей установки определяется указанным файлом preseed.

Замена файла конфигурации установки preseed.cfg в составе дистрибутива

Подразумевается, что файл с новым сценарием установки preseed.cfg сохранен в текущем каталоге. Подробнее про сценарии установки см. Установка Astra Linux по сети (UEFI или Legacy BIOS).

Далее приведен сценарий выполняющий действия по замене файла preseed.cfg, находящегося в составе дистрибутива:

  1. Распаковываются загрузочные образы из копии дистрибутива. Для распаковки создается временный каталог, который далее используется в качестве рабочего;
  2. В распакованных образах файл preseed.cfg заменяется новым файлом;
  3. Образы упаковываются и помещаются в копию установочного диска.

Сценарий:

Command

for n in ~/cd/install.amd ~/cd/install.amd/gtk ~/cd/hd-media ~/cd/hd-media/gtk; do
    if [ -d $n ] ; then
        pushd `mktemp -d`
        chmod u+w $n $n/initrd.gz
        cat $n/initrd.gz | gzip -d | sudo cpio -i
        sudo cp ~/preseed.cfg .
        sudo find | cpio -o --format=newc | gzip -9c > $n/initrd.gz
        sudo rm -rf *
        chmod -R -w $n
        popd
    fi
done

Состав каталогов, содержащих загрузочные образы (и, соответственно, файл pressed.cfg), различается в разных дистрибутивах, в частности может отсутствовать каталог hd-media. 

Обновление индексов

После внесения всех изменений выполнить обновление индексов репозитория:

Command
cd ~/cd; find ! -name md5sum.txt -follow -type f -print0 | xargs -0 md5sum > md5sum.txt ; cd ..

Предупреждение 

Информация

find: Обнаружено зацикливание в файловой системе; ...

можно игнорировать.

Первичные проверки модифицированного дистрибутива


  1. Примонтировать каталог с дистрибутивом:

    Command
    sudo mount -o bind $HOME/cd /mnt


Chroot


  1. Выполнить создание chroot-образа из примонтированного дистрибутива:

    Информация

    На момент последнего обновления настоящей статьи для выполнения данной проверки с использованием образа Astra Linux Special Edition РУСБ.10015-01 (очередное обновление 1.7) на обновлениях Astra Linux, выпущенных до очередного обновления 1.7, необходимо использовать пакеты debootstrap и debian-archive-keyring из очередного обновления 1.7 (см. Подключение репозиториев с пакетами в ОС Astra Linux и установка пакетов).


    Command
    sudo debootstrap --components=main,contrib,non-free --arch=amd64 1.7_x86-64 chroot "file:///mnt"


Состав репозитория

  1. Создать на рабочей машине файл /etc/apt/sources.list.d/mounted.list со ссылкой на примонтированный репозиторий:

    Command
    echo "deb file:/mnt 1.7_x86-64 main contrib non-free" | sudo tee /etc/apt/sources.list.d/mounted.list


  2. Очистить кеш пакетов:

    Command
    sudo rm -fr /var/lib/apt/lists/*


  3. Обновить списки пакетов:

    Command
    sudo apt update


  4. Убедиться, что добавленные в модифицированный репозиторий пакеты доступны:

    Command
    apt policy <имя_добавленного_пакета>


  5. Удалить файл /etc/apt/sources.list.d/mounted.list:

    Command
    sudo rm /etc/apt/sources.list.d/mounted.list


  6. Обновить списки пакетов:

    Command
    sudo apt update


После выполнения проверок отмонтировать дистрибутив:

Command
sudo umount /mnt

Создание файла с загрузочным ISO-образом модифицированного дистрибутива

  1. Извлечь сектор MBR из исходного ISO-образа дистрибутива:

    Command
    dd if=<имя_файла_с_ISO-образом> bs=1 count=432 of=isohdpfx.bin

    Извлеченный сектор будет сохранен в файле isohdpfx.bin;

  2. Создать модифицированный ISO-образ:

    Command
    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

    В приведенном примере опция -V определяет метку (volume id) создаваемого образа (в примере использована метка WIKI_ISO), опция -o определяет имя файла, в который будет записан образ (в примере - wiki_iso.iso). Значение остальных опций см. man xorriso.

  3. Опционально: удалить файл isohdpfx.bin:

    Command
    rm isohdpfx.bin



Дальнейшая работа с модифицированным образом не отличается от работы со стандартным образом

Ведение

В данной статье рассматривается создание модификация установочного диска путем создания образа с измененным составом пакетов. Для установки Astra Linux The Debian installer is based on udebs. Many of those udebs are in the installation image but some of them are in the image's initrd. If you want to modify the udeb's in the initrd then you should follow the instructions on how to build a full image with a custom kernel. However, when you simply want to substitute, amend or add to Debian packages or non-initrd udeb's, you can do this without building a full image.

An already built installation image is required; a netinst or CD/DVD/BD image would be suitable. The remastering of such an image will be illustrated here using the first two DVD images for the Debian 9 (stretch) i386 architecture. The first image is the installation image and the second contains packages we want to add to the first image.

Almost all the remastering process can be carried out as an ordinary user. There is no need for root privileges until it comes to writing the new image to a USB device with dd (or using the genisoimage command).

Creating a Copy of the Installation Image

This is the image (DVD-1) that gets modified; it forms the basis for the remastered image. Because an ISO9660 image cannot be modified directly (it is a read-only image) it must first be extracted. There is a number of techniques to do this but bsdtar will be used here.

First make a directory in which to put the extracted files and then extract them:

$ mkdir cd
$ bsdtar -C cd/ -xf debian-9.3.0-i386-DVD-1.iso

Make the files in cd writable:

chmod -R +w cd

Transferring Packages to the Installation Image

Looking at the contents of DVD-1 when extracted to cd the following two directories will be seen:

~/cd/pool/main 
~/cd/dists/stretch/main/binary-i386

pool contains the Debian packages and it is where any additional packages (from DVD-2, say) would be put. dists is for storing Packages lists and Release files - the index files.

Now put any packages that you want in your image into pool/main or pool/contrib. As an example, suppose you want to copy all of pool/main on DVD-2 to pool/main on DVD-1, the installation image. This could be done either by loopmounting DVD-2 or directly extracting its files to a directory.

Choosing the second method:

mkdir dvd-2
bsdtar -C dvd-2/ -xf debian-9.3.0-i386-DVD-2.iso
chmod -R +w dvd-2
cp -a dvd-2/pool/main/* cd/pool/main/

Creating New Packages and Release Files and Fixing md5sum.txt

Putting packages in pool is not sufficient to produce a valid new image; all the index files (Packages, Packages.gz and Release) and md5sums.txt have to be updated to reflect this change in the image.

It is convenient to update package information using apt-ftparchive and a configuration file.

Create the file config-deb and run:

apt-ftparchive generate config-deb

to generate Packages and Packages.gz files.

# A config-deb file.

# Points to where the unpacked DVD-1 is.
Dir {
    ArchiveDir "cd";
};

# Sets the top of the .deb directory tree.
TreeDefault {
   Directory "pool/";
};

# The location for a Packages file.                
BinDirectory "pool/main" {
   Packages "dists/stretch/main/binary-i386/Packages";
};

# We are only interested in .deb files (.udeb for udeb files).                                
Default {
   Packages {
       Extensions ".deb";
    };
};

One way of updating the Release file in cd/dists/stretch/ is to delete everything in the file from the MD5Sum: line to the end of the file

sed -i '/MD5Sum:/,$d' cd/dists/stretch/Release

followed by (editing the file, if desired)

apt-ftparchive release cd/dists/stretch >> cd/dists/stretch/Release

The md5sum of any image file has to accord with what is in cd/md5sum.txt. Regenerate it with

cd cd; md5sum `find ! -name "md5sum.txt" ! -path "./isolinux/*" -follow -type f` > md5sum.txt; cd ..

It is likely there will be warning message, which appears not to affect the production of an md5sum.txt:

find: File system loop detected; ‘./debian’ is part of the same file system loop as ‘.’.

Including Override Information

The new image to be created will differ from the image it is based on, if only because of the extra packages it contains. As it stands at this stage, another difference between the new image and DVD-1 (say) lies in the Packages file content. In the course of producing this file no account was taken of the centrally managed override file. Although not critical, the absence of override information could be seen as a defect; fortunately, it is an easy one to rectify.

The purpose of an override file is explained here. To illustrate the intention: the package description for less has a Priority field value of important. This is considered by the Debian archive maintainers to be too high, so it is adjusted via an override file to standard, which is what is used in constructing the installer to determine what is installed. As it happens, a user argued against this downgrading, with the result that less has returned to Priority: important for Debian 10 (buster).

In the config-deb file change

BinDirectory "pool/main" {
   Packages "dists/stretch/main/binary-i386/Packages";
};

to

BinDirectory "pool/main" {
   Packages "dists/stretch/main/binary-i386/Packages";
   BinOverride "override";
   ExtraOverride "override.extra";
 };

and add this snippet:

Dir {
   ArchiveDir "cd";
   OverrideDir "indices";
   CacheDir "indices";
 };

Obtain override files from a mirror, put uncompressed versions (use gunzip) in the created directory cd/indices/override and carry out the previous procedures.

Creating a New Image

The original installation image (DVD-1) was designed to be bootable after being burned to a CD, DVD or BD medium or written to a USB device such as a USB stick. The next three commands will achieve this versatility for Legacy BIOS and for EFI in Legacy/CSM mode.

xorriso is the package required to create a hybrid image, one which can be booted both from CD/DVD/BD media as well as from a usb key drive. isolinux will also need to be on the system.

chmod -R -w cd

dd if=debian-9.3.0-i386-DVD-1.iso bs=1 count=432 of=isohdpfx.bin

xorriso -as mkisofs -o test.iso \
-isohybrid-mbr isohdpfx.bin \
-c isolinux/boot.cat -b isolinux/isolinux.bin \
-no-emul-boot -boot-load-size 4 -boot-info-table ./cd

The dd command is advised so that isohdpfx.bin and isolinux.bin stem from the same version of SYSLINUX. It is safer but, without it, you could still find the xorriso command to be successful with /usr/lib/ISOLINUX/isohdpfx.bin in its place.

Insert the key into a USB port and use lsblk to find its block device, /dev/sdX. Then, as root (using su or sudo), write the image to a usb key drive:

dd if=test.iso bs=4M of=/dev/sdX; sync

or, as an ordinary user, burn the image to a CD, DVD, or BD medium in drive /dev/sr0:

xorriso -as cdrecord -v dev=/dev/sr0 -eject test.iso

For a medium which is bootable from a cdrom only, genisoimage can be used in place of xorriso. To make the cdrom bootable, you need to run genisoimage with appropriate parameters. Here is how to do it for x86/amd64, using isolinux for Legacy BIOS. For instructions on how to re-use the full boot equipment of installation ISOs for i386, amd64, arm64 and other architectures, see RepackBootableISO.

cd cd
genisoimage -o test.iso -r -J -no-emul-boot -boot-load-size 4 \
-boot-info-table -b isolinux/isolinux.bin -c isolinux/boot.cat ./cd 

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

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

DebianInstaller/Modify/CD (last modified 2019-10-30 18:17:36)

  • Debian privacy policy, Wiki team, bugs and config.
  • Powered by MoinMoin and Python, withhosting provided by Metropolitan Area Network Darmstadt

    .