⌨ Labor omnia vincit ☮

pam-accesscontrol: PAM-based access control system written in python

Posted in python, Qt, security by anaumov on 27.12.2017

In traditional UNIX/Linux authentication there is not much granularity available in limiting a user’s ability to login. For example, how would you limit the number of users from a specific group? What if you want to allow some users to log in from a specific host, but disallow all others from a same host? Firewall will not help at this point. What if you want to allow SSH for someone, but not X- or login sessions on tty? And… what if you want to be able to decide about allowing SSH for someone at the same moment when connection will be established?

PAM, or pluggable authentication modules, allows for you just this sort of functionality (and more) without the need to patch all your services. PAM is flexible enough to provide solution for all of the above listed issues. All what you need at this point is just implement a new PAM-plugin for your needs.
Some times ago I came across pam_python — a PAM module that lets you write PAM modules in python. During paying with pam-python I implemented my own plugin as a hobby. At the beginning that was just notification window about every new incoming SSH connection. After that I added possibility to allow or denied every new established SSH connection by asking the owner of the X session (that was implemented just for desktop users in mind, of course). Next – define the list of users who may to login any time, who should wait for confirmation and who should never get the shell on my machine. I came on idea to put these lists to the config file. Project grew quickly. Now I would like to introduce it, show the sources and invite everyone (who love coding) to take a part of the development 😉


I called it pam-accesscontrol. Before we start I would like to remind you, that it was implemented as a hobby project just for fun and it’s still unstable, i.e. can broke something on your system. “Someting” is nothing others as a possibility to login via tty/login(1), SSH and X (supported login managers: kdm, gdm, xdm, sddm, lightdm). So, you can just look at the source code or, if you really know what you’re doing, install the package.

To be able to understand how PAM and pam-accesscontrol communicate with other, take a look at doc-page where you can find the list of pam-python methods which are nothing other then a interface for Linux PAM APIs. Every PAM event like open_session, close_session, authenticate, etc. will call appropriate pam-python method. This method will call appropriate pam-accesscontrol function.
For example, OpenSSH: by using password authentication procedure PAM calls pam_authenticate function, which call pam-python’s pam_sm_authenticate function. You just need to implement pam_sm_authenticate-method in your plugin to intercept further steps in the authentication process. Pam-python is just a “bridge” between PAM and pam-accesscontrol:

As you can see, we also should tell PAM (add configuration to files in /etc/pam.d/ directory) to call plugin in some necessary cases. Necessary cases are services like, for example, sshd or login (depend on our wishes) and events like auth, session, etc.
Below you can see how will be configured PAM during pam-accesscontrol installation:

for i in "sddm" "login" "sshd" "lightdm" "xdm" "kdm" "gdm"; do
    if [ -f "/etc/pam.d/$i" ]; then
      echo ""
      echo "#PAM-ACCESSCONTROL configuration" >> "/etc/pam.d/$i"
      echo "auth        required     pam_python.so accesscontrol.py" >> "/etc/pam.d/$i"
      echo "session     required     pam_python.so accesscontrol.py" >> "/etc/pam.d/$i"
      echo \[DONE\] successfully configured: $i

List of all available PAM modules can be found in /lib/$(arch)-linux-gnu/security/ directory. After installiing pam-python package pam-python.so file should be there and after installing pam-accesscontrol package — accesscontrol.py script.


Pam-accesscontrol’s behavior depend on its config file. You add rules for SSH, XDM or TTY services. It’s similar to iptables rules: by an authenticate new user or creating new session, pam-accesscontrol will read config file, parse it and try to make a decision. Actually, pam-accessconfig is nothing else then just a parser. It’s possible to close access for everybody and specify in what case and for whem it will be open, or vice versa — just define who should have no access. At the end decision has made by pam-accesscontrol will be returned to PAM.

Right after package installing it has just one rule in its config file: DEFAULT:OPEN, i.e. access open for everyone. If this DEFAULT variable will be not set in config file, pam-accesscontrol initialize it with CLOSE value.

Let me show some configuration examples.

> cat /etc/pam-accesscontrol/pam-accesscontrol.conf

XDM OPEN USER bob,alice
TTY OPEN USER bob,alice

First line of this configuration closes access for all users. After that we open SSH for all users from lp and users groups (it supports LDAP groups); open access to the host via login manager for users bob and alice; open access via getty for users bob and alice. Pretty easy. Every rule should have exactly 4 fields. If rule is wrong, it will be just ignored.

It’s possible to set limit for number of users from specific group.

SSH NUMBER GROUP users:2,lp:3

For example, this line sets limit to 2 for group users and to 3 for group lp. In other words, new SSH connection will be possible for users from group lp, if only 2 or less users will be logged on this system at the same time.

It’s also possible to configure it so that it will ask you for every new incoming SSH connection. With this line in config file everyone from group lp will wait for your confirmation:


It means

  1. user should to login via SSH (know password or has ssh-key)
  2. after that you should allow this connection

It calls QMessageBox from PyQt5 that returns 0 or 1 to pam-accesscontrol depend on your choice. This value will be interpreted as allow or not allow. By the way, if there is no active Xorg session, pam-accesscontrol will not be able to ask you… so in this case this will be interpreted as an OPEN rule. Also keep in mind that pam-accesscontrol ask owner of the Xorg session only for the first SSH incoming connection. Remote user would like, for example, to copy 100 files on its host; in that case also just one confirmation at the begging will be needed.

Xorg session owner also will be informed when remote user (whose SSH session was confirmed through QMessageBox) ends its SSH session.


Pam-accesscontrol uses syslog. It creates logs after every trying to login. As usual, on systemd-based systems you can use journalctl(1). Also some logs can be found in /var/log/auth.log (authentication phase) and /var/log/syslog files. By default there is not so much information. For debugging and during development it’s a good idea to enable debug/verbose mode. Add DEBUG:True to the config file and it will put much more info about why it made this or that decision.
It also creates its own log file /var/log/pam-accesscontrol-YEAR-MON.log where is stored short statistic about when, who, via which interface tried to login and also — was it successful or not.

Use ldd(1) to check PAM compatibility for supported interfaces:

# ldd $(which sshd) | grep pam
        libpam.so.0 => /lib64/libpam.so.0 (0x00007f82cdfff000)
# ldd $(which login) | grep pam
        libpam.so.0 => /lib64/libpam.so.0 (0x00007fee7f3c9000)
        libpam_misc.so.0 => /lib64/libpam_misc.so.0 (0x00007fee7f1c5000)

pam-python is avaliable for openSUSE

Posted in openSUSE, python, security by anaumov on 21.04.2017

Last week I came across pam_python, a PAM module that lets you write PAM modules in Python. It seems interesting to play in this direction, but I had to install it manually. It seems that there was no official packages for openSUSE until now…

Yesterday I built version 1.0.6 for Tumbleweed. Please test it. It’s in our security repo. Feel free to send submit requests.

After installing it we will get /lib64/security/pam_python.so PAM modul. It’s just an interface between PAM and your own plugin (that you have to implement). To test it, you will need to add PATH of your plugin to the /etc/pam.d/login file (in case of getty-access test, for example), like described here.

This code can be used as an example. It will close access for all getty.

> cat /lib64/security/access.py

def pam_sm_authenticate(pamh, flags, argv):
  if str(pamh.service) == "login":
    return pamh.PAM_AUTH_ERR

You will also need to add this line to the /etc/pam.d/login file:

auth required pam_python.so access.py

This is just an example with login service or getty. Pam-python supports also, for example, ssh- and kdm-services. It supports many other interesting things. For more info look at documentation page.

A bit about POP3

Posted in security by anaumov on 05.02.2015

На сколько большая разница между такими понятиями как “делать” и “делать хорошо”? Я думаю, что каждый определяет это для себя сам. Зависит она от многих факторов, таких как например ответственность и квалификация сотрудников, рабочая атмосфера или просто умение начальника найти правильный подход к каждому из своих подчиненных (с целью повышения эфективности команды в целом).

Я практически забросил свой блог. Но об этом случае мне все же очень захотелось рассказать. Этот случай настолько банален, что я просто не могу пройти мимо. Я встречаю его постоянно. Наверняка в вашей сети есть что-то подобное. Я говорю не о технической части, а скорее о причинах, которые приводят к подобным курьезам. Для тех кто не знает: я работаю сетевым инженером; моя работа заключается в анализе клиентских сетей, а именно – поиске любых неполадок, анализе сетевого трафика, проверок систем безопасности и т.д.

Итак, как вы наверняка знаете, pop3 и imap передают информацию в открытом виде. В том числе и логин с паролем. По этой причине их использование без дополнительных технологий шифрования крайне нежелательно. Сервера, которые смотрят в интернет, как правило защищены как надо, но почему-то для внутренней инфраструктуры всегда применяются другие правила. В Германии есть такое понятие как “historische Gründe”. Очень распространенное. Дословный перевод – “историческая причина”, т.е. это эдакая причина, почему что-то работет не так как следовало бы, но при этом никто не делает никаких изменений, и все остается как есть. Что-то когда-то было настроенно не самым лучшим образом. На это конечно же тогда были причины. Но все остается как есть, и что-то менять, несмотря на то, что меняются сотрудники, меняется инфраструктура, никто не берется. В последствии это “не самым лучшим образом” перерастает в проблему.

читать дальше…