GNU/Linux >> Tutoriels Linux >  >> Linux

Comment détecter le lancement de programmes sous Linux ?

J'étais intéressé à essayer de comprendre comment faire cela sans sondage. inotify() ne semble pas fonctionner sur /proc, donc cette idée est abandonnée.

Cependant, tout programme lié dynamiquement accédera à certains fichiers au démarrage, tels que l'éditeur de liens dynamique. Cela serait inutile pour des raisons de sécurité car il ne se déclenchera pas sur un programme lié statiquement, mais pourrait toujours être intéressant :

#include <stdio.h>
#include <sys/inotify.h>
#include <assert.h>
int main(int argc, char **argv) {
    char buf[256];
    struct inotify_event *event;
    int fd, wd;
    fd=inotify_init();
    assert(fd > -1);
    assert((wd=inotify_add_watch(fd, "/lib/ld-linux.so.2", IN_OPEN)) > 0);
    printf("Watching for events, wd is %x\n", wd);
    while (read(fd, buf, sizeof(buf))) {
      event = (void *) buf;
      printf("watch %d mask %x name(len %d)=\"%s\"\n",
         event->wd, event->mask, event->len, event->name);
    }
    inotify_rm_watch(fd, wd);
    return 0;
}

Les événements affichés ne contiennent aucune information intéressante - le pid du processus de déclenchement ne semble pas être fourni par inotify. Cependant, il pourrait être utilisé pour se réveiller et déclencher une nouvelle analyse de /proc

Sachez également que les programmes de courte durée peuvent disparaître à nouveau avant que cette chose ne se réveille et ne termine l'analyse de /proc - vous apprendrez probablement qu'ils ont existé, mais vous ne pourrez pas savoir ce qu'ils sont. Et bien sûr, n'importe qui pourrait continuer à ouvrir et à fermer un fd vers l'éditeur de liens dynamique pour vous noyer dans le bruit.


Pour Linux, il semble y avoir une interface dans le noyau. En recherchant ce problème, j'ai rencontré des personnes utilisant la configuration du noyau CONFIG_CONNECTOR et CONFIG_PROC_EVENTS pour obtenir des événements lors de la mort du processus.

Encore un peu de Google et j'ai trouvé ceci :

http://netsplit.com/2011/02/09/the-proc-connector-and-socket-filters/

Le connecteur Proc et les filtres de socketPublié le 9 février 2011 par scott

Le connecteur proc est l'une de ces fonctionnalités intéressantes du noyau que la plupart des gens rencontrent rarement, et encore plus rarement trouvent de la documentation. De même le filtre de prise. C'est dommage, car ce sont deux interfaces vraiment très utiles qui pourraient servir à diverses fins si elles étaient mieux documentées.

Le connecteur proc vous permet de recevoir une notification des événements de processus tels que les appels fork et exec, ainsi que les modifications apportées à l'uid, le gid ou le sid (id de session) d'un processus. Ceux-ci sont fournis via une interface basée sur des sockets en lisant des instances de struct proc_event définies dans l'en-tête du noyau....

L'en-tête qui vous intéresse est :

#include <linux/cn_proc.h>

J'ai trouvé un exemple de code ici :

http://bewareofgeek.livejournal.com/2945.html

/* This file is licensed under the GPL v2 (http://www.gnu.org/licenses/gpl2.txt) (some parts was originally borrowed from proc events example)

pmon.c

code highlighted with GNU source-highlight 3.1
*/

#define _XOPEN_SOURCE 700
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
#include <signal.h>
#include <errno.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*
* connect to netlink
* returns netlink socket, or -1 on error
*/
static int nl_connect()
{
int rc;
int nl_sock;
struct sockaddr_nl sa_nl;

nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (nl_sock == -1) {
    perror("socket");
    return -1;
}

sa_nl.nl_family = AF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = getpid();

rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
if (rc == -1) {
    perror("bind");
    close(nl_sock);
    return -1;
}

return nl_sock;
}

/*
* subscribe on proc events (process notifications)
*/
static int set_proc_ev_listen(int nl_sock, bool enable)
{
int rc;
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
    struct nlmsghdr nl_hdr;
    struct __attribute__ ((__packed__)) {
    struct cn_msg cn_msg;
    enum proc_cn_mcast_op cn_mcast;
    };
} nlcn_msg;

memset(&nlcn_msg, 0, sizeof(nlcn_msg));
nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
nlcn_msg.nl_hdr.nlmsg_pid = getpid();
nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;

nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);

nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;

rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
if (rc == -1) {
    perror("netlink send");
    return -1;
}

return 0;
}

/*
* handle a single process event
*/
static volatile bool need_exit = false;
static int handle_proc_ev(int nl_sock)
{
int rc;
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
    struct nlmsghdr nl_hdr;
    struct __attribute__ ((__packed__)) {
    struct cn_msg cn_msg;
    struct proc_event proc_ev;
    };
} nlcn_msg;

while (!need_exit) {
    rc = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
    if (rc == 0) {
    /* shutdown? */
    return 0;
    } else if (rc == -1) {
    if (errno == EINTR) continue;
    perror("netlink recv");
    return -1;
    }
    switch (nlcn_msg.proc_ev.what) {
    case PROC_EVENT_NONE:
        printf("set mcast listen ok\n");
        break;
    case PROC_EVENT_FORK:
        printf("fork: parent tid=%d pid=%d -> child tid=%d pid=%d\n",
            nlcn_msg.proc_ev.event_data.fork.parent_pid,
            nlcn_msg.proc_ev.event_data.fork.parent_tgid,
            nlcn_msg.proc_ev.event_data.fork.child_pid,
            nlcn_msg.proc_ev.event_data.fork.child_tgid);
        break;
    case PROC_EVENT_EXEC:
        printf("exec: tid=%d pid=%d\n",
            nlcn_msg.proc_ev.event_data.exec.process_pid,
            nlcn_msg.proc_ev.event_data.exec.process_tgid);
        break;
    case PROC_EVENT_UID:
        printf("uid change: tid=%d pid=%d from %d to %d\n",
            nlcn_msg.proc_ev.event_data.id.process_pid,
            nlcn_msg.proc_ev.event_data.id.process_tgid,
            nlcn_msg.proc_ev.event_data.id.r.ruid,
            nlcn_msg.proc_ev.event_data.id.e.euid);
        break;
    case PROC_EVENT_GID:
        printf("gid change: tid=%d pid=%d from %d to %d\n",
            nlcn_msg.proc_ev.event_data.id.process_pid,
            nlcn_msg.proc_ev.event_data.id.process_tgid,
            nlcn_msg.proc_ev.event_data.id.r.rgid,
            nlcn_msg.proc_ev.event_data.id.e.egid);
        break;
    case PROC_EVENT_EXIT:
        printf("exit: tid=%d pid=%d exit_code=%d\n",
            nlcn_msg.proc_ev.event_data.exit.process_pid,
            nlcn_msg.proc_ev.event_data.exit.process_tgid,
            nlcn_msg.proc_ev.event_data.exit.exit_code);
        break;
    default:
        printf("unhandled proc event\n");
        break;
    }
}

return 0;
}

static void on_sigint(int unused)
{
need_exit = true;
}

int main(int argc, const char *argv[])
{
int nl_sock;
int rc = EXIT_SUCCESS;

signal(SIGINT, &on_sigint);
siginterrupt(SIGINT, true);

nl_sock = nl_connect();
if (nl_sock == -1)
    exit(EXIT_FAILURE);

rc = set_proc_ev_listen(nl_sock, true);
if (rc == -1) {
    rc = EXIT_FAILURE;
    goto out;
}

rc = handle_proc_ev(nl_sock);
if (rc == -1) {
    rc = EXIT_FAILURE;
    goto out;
}

    set_proc_ev_listen(nl_sock, false);

out:
close(nl_sock);
exit(rc);
}

J'ai constaté que ce code doit être exécuté en tant que root pour recevoir les notifications.


Linux
  1. Comment utiliser la commande Linux grep

  2. Comment utiliser la commande history sous Linux

  3. Comment Linux est arrivé sur le mainframe

  4. Comment déboguer des programmes C sous Linux à l'aide de gdb

  5. Comment changer l'identité d'un système Linux

Comment obtenir la taille d'un répertoire sous Linux

Comment vérifier la version du noyau sous Linux

Comment vérifier la complexité du mot de passe sous Linux

Comment lister les membres d'un groupe sous Linux

Comment vérifier le niveau d'exécution sous Linux

Comment personnaliser la commande Linux top