- Знакомьтесь — Linux From Scratch
- Вместо вступления
- Единственный бумажный дистрибутив
- Но почему начинать с него?
- Цифры и суровая правда жизни
- Состав дистрибутива
- Вместо заключения
- What is Hardened Linux From Scratch?
- Why would I want an HLFS system?
- What can I do with my HLFS system?
- Who’s who:
- What is Linux From Scratch?
- Why would I want an LFS system?
- What can I do with my LFS system?
- Who’s who:
- Linux From Scratch
- Introduction to Linux From Scratch
- Requirements and Procedure
- How does Linux From Scratch work in Linux?
- Conclusion
- Recommended Articles
Знакомьтесь — Linux From Scratch
Вместо вступления
«Хочешь начать изучать GNU/Linux? Начни с Linux From Scratch.»
Единственный бумажный дистрибутив
LFS (здесь и далее аббревиатура от Linux From Scratch) – книга, написанная Герардом Бикмансом, описывающая процесс сборки минимального рабочего варианта GNU/Linux из исходных кодов. Почему бумажный? В свое время книгу можно было купить в твердом переплете, что делает «дистрибутив» несколько необычным, не правда-ли? Помимо самой книги, для сборки конечно-же понадобится интернет (или заранее загруженные исходные коды), свободный раздел на жестком диске, и любая операционная система на базе ядра Linux, имеющая компилятор. Лично я всегда использую либо уже собранный дистрибутив LFS, либо полную установку Slackware – в нем есть все необходимое, чего не скажешь про (например) Ubuntu. Конечно, всегда можно загрузить нехватающие пакеты, но ведь мы хотим только-только научиться линуксу? А Slackware даже в своей базовой установке и без конфигурирования предоставляет требуемый инструментарий.
Следует сказать сразу — дистрибутив собранный по книге LFS не умеет толком ничего. Вернее, ничего такого, что потребуется неискушенному пользователю. Он умеет включаться, выключаться, перезагружаться, использовать Ethernet подключение, но что самое главное — компилировать. Так существуют другие книги, теперь уже поддерживаемые сообществом — Beyond LFS позволяет собрать те самые, интересные пользователю, программы. От браузера и графической среды, до систем управления базами данных и DHCP сервера. Книга имеет свойство отставать в версии от базовой книги, но полученный от LFS опыт обычно достаточен, для самостоятельного разрешения конфликтов версий. Три другие книги — Automated LFS, Cross LFS и Hardened LFS полностью соответствуют названиям и выходят за пределы этой статьи. Впрочем, всегда можно почитать в интернете, правда?
Но почему начинать с него?
Все очень просто, если не сказать — до смешного. Помимо инструкций, в книге много теоретического (но крайне сжатого и как следствие — не заунывного) материала. Установите Ubuntu. Вы знаете что делает пакет Libtool? Или Gawk? После пары успешных сборок LFS, вы будете знать каждый пакет в своей системе и что самое главное — представлять, как они взаимодействуют. Да, состав системы минимальный, но это постоянно подогревает интерес к ее усовершенствованию. Приучит частенько обращаться за помощью к Google и читать англоязычную документацию. Поначалу вы не будете понимать и половины своих действий, внимательно перепечатывая или копируя блоки кода в консоль. Но в самом конце, осознание того, что эту неказистую, без поддержки графики и вашей мощной видеокарты, без новомодного Aero и сенсорных экранов, операционную систему вы собрали сами, придаст вам такой запас сил и гордость, что вы сами потянитесь за новыми знаниями и новыми победами. Я немного утрирую, но ощущения после первой перезагрузки в новую систему сложно забыть даже сейчас.
Цифры и суровая правда жизни
LFS вовсе не минимальный по своему весу дистрибутив. Для сборки потребуется порядка 3 свободный гигабайтов на диске (это помимо уже рабочей Linux-Based системы) — тем не менее, после определенных танцев, систему можно будет превратить в Live-CD. Если у меня будет такая возможность, я расскажу как это делается, в последствии. Компиляция всего и вся (с учетом необходимости создания конфигурационных файлов и прочего) занимает около двух дней. Это если с перерывами на сон, питание и отключение компьютера на ночь. С другой стороны, это зависит от производительности компьютера, на котором собирается система. Моей первой жертвой был ноутбук MSI X-340 — процессор Intel Core 2 Solo с тактовой частотой 1.2 гигагерца (вообще говоря, LFS рекомендуется собирать на одноядерной системе). Оперативная память — 2GB DDR2. Вполне достаточно даже более низких характеристик, а на быстром процессоре сборка пойдет значительно быстрее.
Кстати, приблизительное время сборки каждого из пакетов указано в учебнике. За единицу времени, принимается время сборки пакета Binutils — ассемблера, линкера и ряда других, более мелких утилит для работы с объектными файлами. На вышеуказанной системе это заняло три минуты.
Состав дистрибутива
Перечислять все входящие в LFS пакеты не имеет большого смысла. Список получится длинным, и практически ни о чем не говорящим новичку; избыточным для человека разбирающегося. В этом небольшом разделе я лишь хотел дать несколько общих советов. Во-первых, собирая пакет, не описанный в книге, загляните в репозиторий патчей — возможно его уже адаптировали для использования в LFS. Во-вторых, BLFS почти полностью состоит из опциональных пакетов — просто выбирайте те, которые вам нужны и смело добавляйте в свою сборку LFS. И третье: с самого начала используйте пакетный менеджер. В книге этому уделяется глава, но практические инструкции отсутствуют чуть менее, чем полностью. Я лишь могу порекомендовать Guarded Installation Tool – написанный на Bash’е скрипт, обеспечивающий минимальный набор команд, для управления пакетами, зависимостями и версиями. В LFS этого будет достаточно. В последствии вы можете скомпилировать из исходных кодов APT или DPKG — это неплохо освещено на форумах сообщества.
Вместо заключения
За прошедшие полтора года я сильно продвинулся в своем изучении. Продвинулся со стадии «Есть такая операционная система» до уровня «Подниму сервер под Gentoo за трое суток». Я еще очень далек от идеала и вряд ли могу даже называть себя настоящий линуксоидом — на домашнем компьютере уживаются старенькая Windows XP и Xubuntu 10.10, но знаете что я отвечаю, когда меня спрашивают с чего начать изучать линукс? Начните с Linux From Scratch.
Источник
What is Hardened Linux From Scratch?
Hardened Linux From Scratch (HLFS) is a project that provides you with step-by-step instructions for building your own customized and hardened Linux system entirely from source. Based on LFS, this project will incorporate parts of BLFS as well. The main differences from these other projects will be the amount of text dealing with security configuration issues as well as patching or substituting many of the packages used for improved security.
Why would I want an HLFS system?
If you are wondering why you would want an HLFS system, just read any number of articles dealing with hackers and script kiddies breaking into systems and destroying them or stealing from them. This book goes to some extremes to lock down known and unknown security threats, including patching the core toolchain to prevent buffer overflows.
If you are wondering why you would want an LFS system or don’t know what LFS is then you don’t want to be here just yet — you should head over to the LFS Project Homepage where all will be explained.
What can I do with my HLFS system?
This book will initially be geared towards building production-quality servers, routers, and firewalls. Many BLFS packages will compile and run as-is and work is under way to support the most problematic desktop tools as well.
Who’s who:
- Project Leader: Archaic
- Editor: Robert Connolly
- XML/XSL Editor: Manuel Canales Esparcia
© 1998-2021 Gerard Beekmans. Website design by Jeremy Huntwork & Matthew Burgess.
Источник
What is Linux From Scratch?
Linux From Scratch (LFS) is a project that provides you with step-by-step instructions for building your own customized Linux system entirely from source.
Why would I want an LFS system?
Many wonder why they should go through the hassle of building a Linux system from scratch when they could just download an existing Linux distribution. However, there are several benefits of building LFS. Consider the following:
LFS teaches people how a Linux system works internally
Building LFS teaches you about all that makes Linux tick, how things work together and depend on each other. And most importantly, how to customize it to your own tastes and needs.
Building LFS produces a very compact Linux system
When you install a regular distribution, you often end up installing a lot of programs that you would probably never use. They’re just sitting there taking up (precious) disk space. It’s not hard to get an LFS system installed under 100 MB. Does that still sound like a lot? A few of us have been working on creating a very small embedded LFS system. We installed a system that was just enough to run the Apache web server; total disk space usage was approximately 8 MB. With further stripping, that can be brought down to 5 MB or less. Try that with a regular distribution.
LFS is extremely flexible
Building LFS could be compared to a finished house. LFS will give you the skeleton of a house, but it’s up to you to install plumbing, electrical outlets, kitchen, bath, wallpaper, etc. You have the ability to turn it into whatever type of system you need it to be, customized completely for you.
LFS offers you added security
You will compile the entire system from source, thus allowing you to audit everything, if you wish to do so, and apply all the security patches you want or need to apply. You don’t have to wait for someone else to provide a new binary package that (hopefully) fixes a security hole. Often, you never truly know whether a security hole is fixed or not unless you do it yourself.
What can I do with my LFS system?
A by-the-book LFS system is fairly minimal, but is designed to provide a strong base on which you can add any packages you want. See the BLFS project for a selection of commonly used packages.
Who’s who:
- Project Creator: Gerard Beekmans
- Managing Editor: Bruce Dubbs
- Editor: Ken Moffat
- Editor: Pierre Labastie
- Editor: DJ Lucas
- Editor: Douglas R. Reno
- Editor: Thomas Trepl
- Editor: Tim Tassonis
- Editor: Xi Ruoyao
- Plus numerous people who contribute to the book and its side projects.
© 1998-2021 Gerard Beekmans. Website design by Jeremy Huntwork & Matthew Burgess.
Источник
Linux From Scratch
By Alokananda Ghoshal
Introduction to Linux From Scratch
The concept of Linux From Scratch is an installation in Linux which will install a full-fledged Linux system by building all the components of the Linux system manually. As we can purely understand that the making of Linux from scratch is a much longer process than actually install a Linux distribution in the system, but with this it brings the customization that might be required for the Linux which gets installed. The flexible, compact and secure system will be as per the requirement of the user and no extra components would be present and will also enable user or developer to learn how Linux systems work internally. With this, in this article, we will see the procedure to install and how this component works in general in a development environment.
Requirements and Procedure
Here we will go through the requirements which is necessary for building your own Linux from scratch. The list of all the software are mentioned in the book Linux from scratch including the minimum version which is mentioned so that the Linux build is spotless.
Web development, programming languages, Software testing & others
The list is as follows:
Software | Version |
Bash | 3.2 |
Binutils | 2.25 |
Bison | 2.7 |
Bzip2 | 1.0.4 |
Coreutils | 6.9 |
Diffutils | 2.8.1 |
Findutils | 4.2.31 |
Gawk | 4.0.1 |
GCC | 6.2 |
Glibc | 2.11 |
Grep | 2.5.1a |
Gzip | 1.3.12 |
Linux Kernel | 3.2 |
Now, once the requirement is fulfilled, following steps are followed.
Here, we would also see about any specific syntax that would be required for fulfilling the build.
- In the current operating system, or the Virtual Box or VM, a partition is created and then the correct file format is set up. Basic directories like the bin folder, the place where binaries of the files need to be installed, usr folder where the user related data resides etc. are created and kept ready.
- The compressed source code which is available on GitHub or any private repository is downloaded as .tar.gz or .tar files.
- While downloading the tar file, one needs to keep in mind to verify the integrity of the tarball by doing a hash check to look for any tampering in the compressed file.
- The compressed file is extracted for getting the source code for the desired process or command’s source code.
- make command (syntax: make check) is run to perform a check on the source code. Post that (syntax: make install) is run for building and installing the required process and store the binaries in the bin folder.
- The steps 2 to 5 is repeated for any other command or process that one would need to install in the Linux system.
How does Linux From Scratch work in Linux?
In Linux from scratch it is undoubtedly about understanding the working of LFS-Bootscripts. These Bootscripts are installed as a part of the Step 5. LFS-Bootscripts are a set of scripts which are installed in order to perform some basic yet important tasks. These SysV type scripts performs various tasks like performing check on the filesystem integrity during boot, loading of keymaps, setting up of networks, and halting process in case of shutdown. These, although looks primal tasks, but are equally important for smooth functioning of the Linux system.
Before we see the working, it is imperative to know about the different set of scripts which are installed as a part of LFS-Bootscripts.
Given below we have some set of scripts which are basic yet the most important ones.
- checkfs: Looks for any issues in a file system before they are mounted.
- cleanfs: Removes any files which need not be preserved between reboots.
- halt: Helps in halting the system.
- network: Helps in setting up of network interfaces.
- localnet: Makes sure that hostname and local device for loopback is correctly set up.
- reboot: Helps in rebooting the system.
- halt: Helps in halting the system.
The above list is not exhaustive, and reader should be mindful of the same.
Now that we have a brief idea on what Bootscripts are, let us know on how these Bootscripts work? The booting facility of Linux is a special one which is known as SysVinit and the running concept is based on run-levels. Here, there are 7 run-levels where each of these level corresponds to a state and also refers to the actions that needs to be performed when the operating system starts up.
The run-levels are as follows.
- 0: To halt the computer.
- 1: Allow only a single user.
- 2: Allows multiple users but with no networking.
- 3: Allows multiple users with networking.
- 4: Placeholder for any customized option.
- 5: Again, a placeholder but most likely used for logging in using GUI.
- 6: To reboot the computer.
Using init command one can easily modify the run levels as per the requirement of the use case. In the location /etc/rc.d there are numerous files present like rc?.d where? signifies the run level one is looking for. This also consists of rcsysinit.d which contains symbolic links having a nomenclature which helps in determining the order in which the scripts in the directory needs to run in. The lower the number in the nomenclature the earlier the file gets executed.in the folder /etc/rc.d/init.d the actual scripts are stored. The symbolic links points to the scripts stored here, and these are the scripts which does the entire work as desired by the developer.
This is where, the customization kicks in, one can choose the lifestyle it needs for its Linux system by choosing the way the boot process works. After all this is one’s own system where one can put all creativity to bring something to life.
Conclusion
In this article though there is no example, but nevertheless the article focusses on a project named Linux from Scratch (LFS) and how one can build customized Linux system which can suits one’s requirement and is free of any unwanted components in the Linux system getting developed. There are above and beyond LFS, for example, BLFS (Beyond Linux From Scratch), ALFS (Automated Linux From Scratch) etc. which is outside the scope of the article, but is a preferred read for our readers.
Recommended Articles
This is a guide to Linux From Scratch. Here we discuss the introduction, requirements and procedure, how does linux from scratch work in linux? You may also have a look at the following articles to learn more –
All in One Software Development Bundle (600+ Courses, 50+ projects)
Источник