Nss linux ��� ���
Linux – система многопользовательская. По умолчанию, большинство дистрибутивов используют «классический» набор файлов в которых хранится информация о пользователях и группах: /etc/passwd , /etc/group , /etc/shadow , /etc/gshadow . Во многих ситуациях этого вполне достаточно, но иногда возникает необходимость в интеграции Linux в более или менее чужеродное, либо просто распределенное окружение, и именно в этот момент к нам на помощь приходят такая интересная подсистема, как NSS – Name Service Switch. Основная задача NSS – создать модульное окружение для управления пользователями. Реализовано это посредством загружаемых библиотек. Основные вызовы NSS реализованы в библиотеке libc, а libc в свою очередь загружает и вызывает бакэнды NSS:
При инициализации программы, так или иначе связанной с NSS, загружаются основная библиотека libc.so , которая считывает конфигурацию из файла /etc/nsswitch.conf , после чего также загружаются те библиотеки NSS, которые указаны в этом файле.
Впоследствии при работе программы, если программе требуется работать с именованными сущностями, соответствующие вызовы функций glibc будут обращаться к функциям NSS и использовать в те источники данных, которые указаны в nsswitch.conf .
В частности, через NSS можно разрешать (определять) имена и идентификаторы протоколов, номера портов служб (сервисов), имена и идентификаторы пользователей и групп, IP-адреса и имена компьютеров и некоторые другие данные.
Пример файла nsswitch.conf :
В данном примере указано, что для определения имен пользователей и групп используются сначала текстовые файлы и затем LDAP, для определения имен компьютеров и IP-адресов используются сначала текстовые файлы и затем DNS, для определения алиасов и настроек автоматического монтирования каталогов используются сначала текстовые файлы и затем служба NIS+.
Библиотеки бакэндов системы NSS хранятся в файлах libnss_ XXX .so , где XXX – это имя бакэнда. Например libnss_files.so – это бакэнд NSS использующий в качестве источника данных текстовые файлы, libnss_db.so – бакэнд использующий файлы BerkleyDB, libnss_ldap.so – бакэнд позволяющий хранить данные в каталоге LDAP. Как правило, каждый бакэнд имеет свои дополнительные конфигурационные файлы.
Как следствие, если у вас возникла необходимость использовать вашу Linux-систему в сетевом или чужеродном окружении и обеспечить ее интеграцию с ним, вы можете воспользоваться NSS и получить доступ к информации через соответствующий бакэнд – например, для интеграции в среду Solaris, вы можете воспользоваться бакэндом NIS/NIS+, для интеграции в ActiveDirectory – бакэндом LDAP.
При этом модульность NSS позволяет вам объединять различные источники данных – например, использовать текстовые файлы и DNS для определения имен компьютеров, NIS для определения имен протоколов и сервисов, и текстовые файлы и LDAP для определения имен и идентификаторов пользователей и групп.
Подсистема PAM (Pluggable Authentification Modules) идейно очень схожа с NSS, но отличается от нее назначением. Основная задачам PAM – аутентификация пользователей (проверка паролей, прав доступ, ограничений и так далее). Как и NSS, PAM состоит из набора основных библиотек и бакэндов, причем необходимые бакэнды, порядок их вызова и некоторые опциональные параметры определяются в конфигурационных файлах PAM, обычно они расположены в каталоге /etc/pam.d . Главным отличием PAM от NSS (кроме естественно назначения) является то, что PAM является не составной и неотъемлемой частью libc, а отдельным множеством библиотек.
Основная часть стандартных утилит UNIX для управления пользователями и группами и получения информации о них, в большинстве дистрибутивов Linux общего назначения, адаптирована и собрана с поддержкой NSS и PAM. К таким утилитам относятся passwd , chsh , chfn , id , who и другие. NSS также используется даже такими утилитами как ls , find , ps – то есть всеми теми программами, которые отображают имя пользователя. Соответственно, если программа запрашивает у пользователя пароль – скорее всего она использует и NSS, и PAM (например XDM или GDM). Большинство программ в чьи функции входит обработка почты также используют NSS. Соответственно, можно уверенно говорить что подсистемы NSS и PAM и базовые знания об их предназначении на сегодняшний день являются необходимыми для администратора Linux-систем.
Источник
nss(5) — Linux man page
nss — Name Service Switch configuration file
Description
Each call to a function which retrieves data from a system database like the password or group database is handled by the Name Service Switch implementation in the GNU C library. The various services provided are implemented by independent modules, each of which naturally varies widely from the other.
The default implementations coming with the GNU C library are by default conservative and do not use unsafe data. This might be very costly in some situations, especially when the databases are large. Some modules allow the system administrator to request taking shortcuts if these are known to be safe. It is then the system administrator’s responsibility to ensure the assumption is correct.
There are other modules where the implementation changed over time. If an implementation used to sacrifice speed for memory consumption it might create problems if the preference is switched.
The /etc/default/nss file contains a number of variable assignments. Each variable controls the behavior of one or more NSS modules. White spaces are ignored. Lines beginning with ‘#’ are treated as comments.
The variables currently recognized are: NETID_AUTHORITATIVE = TRUE|FALSE If set to TRUE, the NIS backend for the initgroups(3) function will accept the information from the netid.byname NIS map as authoritative. This can speed up the function significantly if the group.byname map is large. The content of the netid.byname map is used as is. The system administrator has to make sure it is correctly generated. SERVICES_AUTHORITATIVE = TRUE|FALSE If set to TRUE, the NIS backend for the getservbyname(3) and getservbyname_r(3) functions will assume that the services.byservicename NIS map exists and is authoritative, particularly that it contains both keys with /proto and without /proto for both primary service names and service aliases. The system administrator has to make sure it is correctly generated. SETENT_BATCH_READ = TRUE|FALSE If set to TRUE, the NIS backend for the setpwent(3) and setgrent(3) functions will read the entire database at once and then hand out the requests one by one from memory with every corresponding getpwent(3) or getgrent(3) call respectively. Otherwise each getpwent(3) or getgrent(3) call might result in a network communication with the server to get the next entry.
Files
Example
The default configuration corresponds to the following configuration file:
Источник
NSS-3.70
Introduction to NSS
The Network Security Services ( NSS ) package is a set of libraries designed to support cross-platform development of security-enabled client and server applications. Applications built with NSS can support SSL v2 and v3, TLS, PKCS #5, PKCS #7, PKCS #11, PKCS #12, S/MIME, X.509 v3 certificates, and other security standards. This is useful for implementing SSL and S/MIME or other Internet security standards into an application.
This package is known to build and work properly using an LFS-11.0 platform.
Package Information
Download MD5 sum: 1624b400d750f4278f46bbda161223a0
Download size: 81 MB
Estimated disk space required: 310 MB (add 163 MB for tests)
Estimated build time: 2.0 SBU (with parallelism=4, add 19 SBU for tests)
Additional Downloads
NSS Dependencies
Required
Recommended
Installation of NSS
Install NSS by running the following commands:
To run the tests, execute the following commands:
Some information about the tests:
HOST=localhost and DOMSUF=localdomain are required Without these variables, a FQDN is required to be specified and this generic way should work for everyone.
The tests take an extremely long time to run. If desired there is information in the all.sh script about running subsets of the total test suite.
When interrupting the tests, the test suite fails to spin down test servers that are run. This leads to an infinite loop in the tests where the test suite tries to kill a server that doesn’t exist anymore because it pulls the wrong PID.
Test suite results (in HTML format!) can be found at ../../test_results/security/localhost.1/results.html
Now, as the root user:
Command Explanations
BUILD_OPT=1 : This option is passed to make so that the build is performed with no debugging symbols built into the binaries and the default compiler optimizations are used.
NSPR_INCLUDE_DIR=/usr/include/nspr : This option sets the location of the nspr headers.
USE_SYSTEM_ZLIB=1 : This option is passed to make to ensure that the libssl3.so library is linked to the system installed zlib instead of the in-tree version.
ZLIB_LIBS=-lz : This option provides the linker flags needed to link to the system zlib .
$([ $(uname -m) = x86_64 ] && echo USE_64=1) : The USE_64=1 option is required on x86_64 , otherwise make will try (and fail) to create 32-bit objects. The [ $(uname -m) = x86_64 ] test ensures it has no effect on a 32 bit system.
([ -f /usr/include/sqlite3.h ] && echo NSS_USE_SYSTEM_SQLITE=1) : This tests if sqlite is installed and if so it echo s the option NSS_USE_SYSTEM_SQLITE=1 to make so that libsoftokn3.so will link against the system version of sqlite.
NSS_DISABLE_GTESTS=1 : If you don’t need to run NSS test suite, append this option to make command, to prevent the compilation of tests and save some build time.
Источник
Nss linux ��� ���
Network Security Services
Network Security Services (NSS) is a set of libraries designed to support cross-platform development of security-enabled client and server applications. NSS supports TLS 1.2, TLS 1.3, PKCS #5, PKCS#7, PKCS #11, PKCS #12, S/MIME, X.509 v3 certificates, and other security standards.
In order to get started create a new directory on that you will be uses as your local work area, and check out NSS and NSPR. (Note that there’s no git mirror of NSPR and you require mercurial to get the latest NSPR source.)
NSS can also be cloned with mercurial
This build system is under development. It does not yet support all the features or platforms that NSS supports. To build on anything other than Mac or Linux please use the legacy build system as described below.
After changing into the NSS directory a typical build is done as follows
Once the build is done the build output is found in the directory ../dist/Debug for debug builds and ../dist/Release for opt builds. Exported header files can be found in the include directory, library files in directory lib , and tools in directory bin . In order to run the tools, set your system environment to use the libraries of your build from the «lib» directory, e.g., using the LD_LIBRARY_PATH or DYLD_LIBRARY_PATH .
See help.txt for more information on using build.sh.
Building NSS (legacy build system)
After changing into the NSS directory a typical build of 32-bit NSS is done as follows:
The following environment variables might be useful:
BUILD_OPT=1 to get an optimised build
USE_64=1 to get a 64-bit build (recommended)
The complete list of environment variables can be found here.
To clean the build directory run:
Make sure that the address $HOST.$DOMSUF on your computer is available. This is necessary because NSS tests generate certificates and establish TLS connections, which requires a fully qualified domain name. You can test this by calling ping $HOST.$DOMSUF . If this is working, you’re all set. If it’s not, set or export:
Note that you might have to add nss.local to /etc/hosts if it’s not there. The entry should look something like 127.0.0.1 nss.local nss .
Runnning all tests will take a while!
Make sure that all environment variables set for the build are set while running the tests as well. Test results are published in the folder ../../test_results/ .
Individual tests can be run with the NSS_TESTS environment variable, e.g. NSS_TESTS=ssl_gtests ./all.sh or by changing into the according directory and running the bash script there cd ssl_gtests && ./ssl_gtests.sh . The following tests are available:
To make tests run faster it’s recommended to set NSS_CYCLES=standard to run only the standard cycle.
NSS releases can be found at Mozilla’s download server. Because NSS depends on the base library NSPR you should download the archive that combines both NSS and NSPR.
Bugzilla is used to track NSS development and bugs. File new bugs in the NSS product.
A list with good first bugs to start with are listed here.
NSS Folder Structure
The nss directory contains the following important subdirectories:
coreconf contains the build logic.
lib contains all library code that is used to create the runtime libraries.
cmd contains a set of various tool programs that are built with NSS. Several tools are general purpose and can be used to inspect and manipulate the storage files that software using the NSS library creates and modifies. Other tools are only used for testing purposes.
test and gtests contain the NSS test suite. While test contains shell scripts to drive test programs in cmd , gtests holds a set of gtests.
A more comprehensible overview of the NSS folder structure and API guidelines can be found here.
Build mechanisms related to FIPS compliance
NSS supports build configurations for FIPS-140 compliance, and alternative build configurations that disable functionality specific to FIPS-140 compliance.
This section documents the environment variables and build parameters that control these configurations.
Build FIPS startup tests
The C macro NSS_NO_INIT_SUPPORT controls the FIPS startup self tests. If NSS_NO_INIT_SUPPORT is defined, the startup tests are disabled.
The legacy build system (make) by default disables these tests. To enable these tests, set environment variable NSS_FORCE_FIPS=1 at build time.
The gyp build system by default disables these tests. To enable these tests, pass parameter —enable-fips to build.sh.
Building either FIPS compliant or alternative compliant code
The C macro NSS_FIPS_DISABLED can be used to disable some FIPS compliant code and enable alternative implementations.
The legacy build system (make) never defines NSS_FIPS_DISABLED and always uses the FIPS compliant code.
The gyp build system by default defines NSS_FIPS_DISABLED. To use the FIPS compliant code, pass parameter —enable-fips to build.sh.
The NSS test suite may contain tests that are included, excluded, or are different based on the FIPS build configuration. To execute the correct tests, it’s necessary to determine which build configuration was used.
The legacy build system (make) uses environment variables to control all aspects of the build configuration, including FIPS build configuration.
Because the gyp build system doesn’t use environment variables to control the build configuration, the NSS tests cannot rely on environment variables to determine the build configuration.
A helper binary named nss-build-flags is produced as part of the NSS build, which prints the C macro symbols that were defined at build time, and which are relevant to test execution.
Источник