Some bits from GSoC 2007

There is some facts about current OVAL support in deb-based distributions (Debian and Ubuntu):

  • Ubuntu 8.04 Hardy released with oval-interpretator 5.3 in universe section
  • oval-interpretator 5.4 already migrated to Debian testing and ready to ship with Lenny
  • oval-interpretator 5.4 migrated to Ubuntu unstable repository and will include in next releas

In next phase we plan to add official support status to OVAL definitions for Debian and Ubuntu distributions.

Sams для Debian

Очередной шаг в нормальному пакету Sams для Debian и Ubuntu сделан. Сегодня я выложил вторую тестовую сборку для 1.0.2[3]. Из интересного стоит отметить:
  • Наступил на большие грабли — в init скрипте я запускал sams с не настроенным соединением с БД. Соответственно sams падал, т.к. запуск init скрипта происходил при установке пакета — установка пакета завершалась с ошибкой. При попытке удалить пакет — init скрипт пытается остановить sams, который и не запущен. Опять выход с ошибкой и пакет удалить нельзя. Кстати интересно почему это попытка остановить не запущенную софтину приводит к ошибке. Решил все это вводом переменной SAMS_ENABLED и установкой её по умолчанию в false. Обычно такие переменные помещают в /etc/default/<пакет>, но я не стал так делать.
  • В основном из-за п.1 пришлось разобраться с debconf. Теперь при установке sams выводится окно с сообщением что sams еще не готов работать из коробки и вам надо донастроить ручками. И ссылка на /usr/share/doc/sams/README.Debian Интересно, сколько человек это сообщение не прочитают и будут слать баги что sams не запускается.
  • Оказывается debconf имеет собственное персональное постоянное хранилище где лежат ответы на все заданные им вопросы. Но изменение параметра в конфиге с помощью sed’а для меня выглядит шаманством.
  • Открою небольшой секрет — я теперь пакеты собираю с помощью launchpad. Ибо так и не настроил нормально build системы на сервере.
  • Теперь чтобы поставить sams не надо качать полтора метров исходников. А еще sams в Debian разбит на три пакета — демоны, web и документация. В результате можно ставить демонов без вытягивания php:)

Правило обновления Linux

Обновлять дистрибутив Linux надо из сетевого репозитария на дорогом или медленном канале. Т.к. такое обновление это хороший повод сделать dpkg -l и удалить лишние пакеты нажитые за последний год.

В этот раз мой ноут избавился от php (что хороший важный факт), ruby (не понял я как его готовят) и кучи другого хлама поставленного чтобы попробовать.

Кстати, раньше php стоял у многих из-за того что использовались всякие web-интерфейсы типа phpmyadmin. Неужели эти времена уходят…

Debian project и Google Summer of Code

Вот и прошло еще одно лето и еще один Google Summer of Code, уже третий по счету. Об этом мероприятии ежегодно проводимом Google Inc слышала большая часть людей связанных с разработкой Open Source проектов, а сумма денежного вознаграждения будоражит студенческие умы постсоветского пространства. И при этом из года в год количество участников GSoC из России становится все больше и больше. Количество проектов растет. Растет и качество организации как со стороны Google, так и со стороны Open Source проектов.

Участие Debian в Google Summer of Code 2006

Участие Debian в Google Summer of Code 2006

Проект Debian участвует в этой программе уже второй год. За это время 19 студентов приняли участие в разработке одного из известнейших дистрибутивов Linux. Правда не все из них справились с взятой на себя задачей. В 2006 году четверо из 10 студентов не завершили свои проекты в срок. Итак в 2006 году Debian получил 10 спонсируемых проектов. В основном проекты были связаны с разработкой и совершенствованием инфраструктуры разработки Debian, автоматической генерацией LIVE cd и улучшениям в процессе загрузки/установки. Самыми интересными результатами GSoC 2006 для Debian (на мой взгляд конечно) это проекты Debtags AI и Improve the boot system. Первый проект связан с улучшением интеллектуальной поддержки tag’ов для пакетов Debian. Позволяя более удобно и производительно искать пакеты в репозитарии с использованием категорий. Второй проект был свзяан с оптимизацией загрузки Debian, отслеживанием зависимостей в init-скриптах. В [блоге разработчика] (http://bootdebian.blogspot.com/] я нашел немного интересной статистики — время которое тратит свежеустановленная система Debian с включения и до загрузки KDE:

  • Woody — 32 seconds
  • Sarge — 44 seconds
  • Etch — 32 seconds

Участие Debian в Google Summer of Code 2007

Участие Debian в Google Summer of Code 2007

В 2007 году подготовка к лету со стороны сообщества Debian была более серьезная. Заранее начался сбор идей от разработчиков Debian и студенты могли заранее подбирать себе проект по вкусу и обсуждать кодробности с потенциальным руководителем. Для большинства проектов была создана отдельная страница в wiki для более подробного описания идеи и целей. Был организован IRC-канал для общения потенциальных участников и руководителей. В результате было предложено больше 20 проектов, начиная от улучшения дизайна сейта debian.org и заканчивая Biometrical authentication. По прежнему освновная доля проектов связана с улучшением инфраструктуры разработки дистрибутива и написанию различных frontend’ов к существующим сервисам. Но вместе с этим были и очень интересные идеи: Biometrical authentication, Embedded Debian, Testing system upgrades automatically using QEMU. В этот раз Debian рассчитывал получить 11-12 проектов (именно столько достойных приложений было отобрано), но в результате получил только 9. И в результате были исключены Embedded Debian и i18n/l10n. Также интересно рассмотреть график интересов студентов к конкретных проектам:

  • cd tester (16 applications) xxxxxxxxxxxxxxxx
  • security (15 applications) xxxxxxxxxxxxxxx
  • website (13 applications) xxxxxxxxxxxxx
  • piuparts, u/g testing (7 applications) xxxxxxx
  • emdebian/embedded (5 applications) xxxxx
  • user2user communication (5 applications) xxxxx
  • livecd (4 applications) xxxx
  • debbugs (4 applications) xxxx
  • openid (3 applications) xxx
  • apt-checkpoint (3 applications) xxx
  • biometric auth (3 applications) xxx
  • kernel config (3 applications) xxx
  • mirroring (3 applications) xxx
  • cdd toolkit (2 applications) xx
  • i18n/l10n (2 applications) xx

Проекты которые были выбраны для GSoC 2007 можно увидеть как на странице Google, так и в wiki проекта Debian. И с 28 мая студенты официально приступили к реализации своих проектов. И хотя предварительный этап в этот раз был организован на порядок лучше — студенты имели возможность обсуждать свои предложения на раннем этапе, то сам процесс оценки и контроля за выполнением проекта мог быть лучше. К сожалению в этом году студенты не делали еженедельные отчеты о проделанной работе, также очень нехватало публично опубликованного и обновляемого плана по проекту и плана встреч с руководителем. Думаю реализация такого сервиса может значительно улучшить следующих GSoC для Debian.

Но несмотря на все это, все 10 проектов в 2007 году были завершены успешно. И в этом году все однозначно согласились что самым успешным проектом был BitTorrent Proxy for Debian Archive. Cameron Dale не только выполнил поставленные цели, но и создал действительно полезный и востребованный администраторами инструмент. И даже после завершения программы он продолжает работу над проектом и завершает интеграцию BitTorrent Proxy в качестве транскорта для apt-get. Особо также хочется отметить что многие проекты продолжают развиваться несмотря на то, что лето уже закончилось. Так Automated Upgrade Testing Using QEMU, Piuparts improvements, BitTorrent Proxy for Debian Archive, OVAL Agent for Debian, Bug Triage and Forward Tool не стоят на месте. А это самый главный показатель успешности проекта в GSoC.

Final report of project “OVAL Agent for Debian”

My task for GSoC 2007 was further integration of OVAL language and infrastructure with Debian project. OVAL language already include scheme for support Debian package system (dpkg), but this functionality was don’t implemented in referenced OVAL interpretator. Therefore my first task was implement this support, create Debian package for referenced OVAL interpretator, and submit resulted patches to upstream for inclusion in next official release.

My second task was improve script that convert DSA to OVAL definitions. This script was initially developed by my mentor Javier Fernandez-Sanguino, but was based on old OVAL version and generate only simple OVAL definition that not pass validation by OVAL definition scheme.

Implementing of this two task will allow to use OVAl interpretator to evaluate security status of Debian hosts according to issued DSA. Both of this task is finished now. During work on implementing DPKG support in referenced OVAL interpretator i was implement DPKGInfoProbe and TextFileContentProbe classes. This patches was included in ovaldi Debian package and sent to upstream. Currently this patches not fully applied to upstream source, but i will continue interaction with OVAL developers to include this feature in next release.

DSA to OVAL definitions converter was fully rewrite on python language and now produce valid OVAL definitions for most of DSA in Debian repository (some old DSA is ignored because have different naming scheme). We plan to use this script as part of oval-server package for in-place conversion of DSA and on security.debian.org web-site to provide Debian OVAL definitions feed corresponding to issued DSA. This converter require some updates to reduce memory usage on handling large DSA repository (like full DSA repository).

Second and very important task was implementing agent-server architecture over the OVAL interpretator to centralized handle security status of whole Debian networks. This task include development of oval-server program that must generate OVAL definitions repository (generate from DSA or download from official debian.org feed), generate per-client definitions to evaluate security status of Debian client hosts and generate security status reports for visual presentation of security status. Oval-agent tools was developed to work on client side and it purpose include receive OVAL definitions from server, evaluate them with OVAL interpretator and send results back to server.

At the first stage of project i will plan implement both tools in C++, but during work on this task i change my choice to python language due to time constraint and better integration with DSA2OVAL converter. Oval-server use SQLite as database engine to store information about clients and definitions, HTTP protocol to interact with oval-agents and currently support synchronization DSA repository over http, ftp, local fs (in plan mail and rss support, and support fetch prepared OVAL definitions from debian.org website).

Both, oval-agent and oval-server in working prototype stage. They implements most of required functional, but have some important issues which must be fixed before inclusion in Debian repository. I plan to keep list of this issues on DebianOval wiki page.

I plan to continue working and prepare oval-agent and oval-server packages to the end of this year or early.

OVAL for Debian on the road

Today i finished most work on adopting OVAL interpretator for work with Debian OVAL definitions. This include implementation of TextFileContentProbe DPKGInfoProbe classes. Now we have both —

Next targets:

  • Bugfixing
  • Building Debian packages
  • Merging patches in upstream

Use libapt for package quering

Second part of my work in SoC was implement support of DEB-based distribution in OVAL interpreter. After discussion with my mentor i choice libapt for interacting with Debian package system.

But i have a troubles with this library because it have poor documentation. I start use regression test, which i found in library source but some of them seems broken. After some attempt to find problem i move to apt-get source and use them to build my first package querying program. apt-get use dpkg cache file to obtain information about all available packages. Therefor source for querying packages from dpkg cache file seems like:


bool checkExist (string package) { bool exist = false;

    pkgCacheFile *Cache = new pkgCacheFile();

    OpTextProgress Prog(*_config);
    if (Cache->Open(Prog, true) == false) {
            cerr << "I need more priveleges." << endl;
    }

    pkgCache::PkgIterator Pkg = (*Cache)->FindPkg (package);

    if (strcmp (Pkg.Name(), package.c_str()) == 0 and (Pkg.CurrentVer()))
            exist = true;

    Cache->Close();

    return (exist);

 }

I think this approach is good and compact but have one lack in size of querying cache. Because we query over all available packages, not only installed. And for my machine this number about 20000.

My mentor Javier propose another approach based on apt-sort source code. This approach use dpkg status file for querying information about installed packages. There another version of checkExist function:


bool DPKGCheckExist (string name) { FileFd Fd(StatusFile, StatusFile::ReadOnly); pkgTagFile Tags(&Fd);

    bool found = false;
    if (_error->PendingError() == true)
            return "false";

    // Parse.
    vector List;
    pkgTagSection Section;
    unsigned long Offset = Tags.Offset();

    while (Tags.Step(Section) == true && found == false)
    {
            PkgName Tmp;
            /* Fetch the name, auto-detecting if this is a source file or a package file */
            Tmp.Name = Section.FindS("Package");

            if (Tmp.Name.empty() == true)
                    //return _error->Error("Unknown package record!");
                    return "false";

            if ( stringcasecmp(Tmp.Name,name) == 0 )
            {
                    if (stringcasecmp(Tmp.Stat,"install ok installed") == 0 )
                    {
                            return true;
                    } else {
                            cout << "Package not fully installed" << endl;
                            return false;
                    }

                    found = true;
            }

            Tmp.Offset = Offset;
            Tmp.Length = Section.size();

            Offset = Tags.Offset();
    }

    if (found == false)
            return "ERROR";
    if (_error->PendingError() == true)
            return "ERROR";

 }

This example contain more code, but also allow to extract more information about installed packages. And this fragments would move to other functions which used to extraction DPKG package information. Currently i use this example in my work.

If you would plan use of libapt in you project this two approach may help you get started in rigth way.