Fix Race Condition / I/O Buffering in status_flush() causing truncated/zero-byte status file reads

Aperta
#1,054 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
45/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Tranquilla
Stack tecnologico
c
Ambito
backend

Direzione di ricerca

Inizia in src/openvpn/status.c, in status_flush(), e verifica come il file di stato viene troncato e riscritto. Riproduci il problema con un file di stato periodico e un lettore esterno aggressivo, quindi valuta il comportamento proposto di blocco e sincronizzazione sulle piattaforme supportate. Il lavoro è completato quando i lettori esterni non osservano più dati di stato vuoti o parziali senza compromettere l’output di stato esistente.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Describe the bug
There is a race condition and I/O buffering issue inside status_flush() in src/openvpn/status.c. When OpenVPN periodically updates the status file (e.g., via status-version 1), it calls ftruncate() to resize/truncate the file descriptor before overwriting it with fresh data.

Because OpenVPN does not utilize any kernel-level file locking (flock) or immediate buffer flushing (fsync) during this exact window, external third-party plugins, daemons, or parsers (such as radiusplugin or custom accounting scripts) that poll the status file frequently can hit a race condition. They randomly read the file exactly when it is truncated (0 bytes) or while data is still half-written/cached in the OS I/O buffers. This causes external plugins to parse incomplete tables, leading to critical accounting bugs (e.g., incorrectly reporting 0 bytes for active users).

To Reproduce
Steps to reproduce the behavior:

  1. Configure OpenVPN to log periodic status updates to a specific file path (e.g., status /run/openvpn/status.log 10).
  2. Have multiple active clients connected transferring data.
  3. Run an aggressive asynchronous external script or plugin that continuously reads and parses /run/openvpn/status.log every few seconds.
  4. Observe that occasionally, the external reader hits a race condition exactly during OpenVPN's status_flush() loop, reading a completely empty or partial file, resulting in missed accounting data (0 bytes processed) even though the user is fully active.

Expected behavior
OpenVPN should implement an atomic or synchronized write/flush mechanism on its status file descriptor. While the file is being truncated and rewritten inside status_flush(), it should temporarily acquire an exclusive advisory lock (flock) and force a buffer sync (fsync) right before releasing the lock. This ensures that any external parser attempting to read the file will be safely blocked for a few microseconds by the OS kernel until a 100% complete file structure is ready.

Version information:

  • OS: Linux (e.g., Ubuntu 24.04 / Debian 13 using tmpfs / ramdisk)
  • OpenVPN version: 2.7.x / 2.6.x (Affects all versions using the traditional status_flush logic in status.c)

Additional context
I have locally patched and successfully tested this issue by modifying the status_flush() function inside src/openvpn/status.c. Implementing an exclusive kernel lock (LOCK_EX) and forcing a buffer commit via fsync entirely resolved the random 0-byte parsing issues without adding any measurable CPU or memory overhead.

Here is the exact diff/proposed fix that eliminates the race condition:

void
status_flush(struct status_output *so)
{
    if (so && so->fd >= 0 && (so->flags & STATUS_OUTPUT_WRITE))
    {
        /* Step 1: Apply an exclusive kernel lock BEFORE truncating the file.
         * This prevents external parsers from opening or reading a half-written/empty file. */
        #ifdef HAVE_SYS_FILE_H
        flock(so->fd, LOCK_EX);
        #endif

#if defined(HAVE_FTRUNCATE)
        {
            const off_t off = lseek(so->fd, (off_t)0, SEEK_CUR);
            if (ftruncate(so->fd, off) != 0)
            {
                msg(M_WARN | M_ERRNO, "Failed to truncate status file");
            }
        }
#elif defined(HAVE_CHSIZE)
        {
            const long off = (long)lseek(so->fd, (off_t)0, SEEK_CUR);
            chsize(so->fd, off);
        }
#else /* if defined(HAVE_FTRUNCATE) */
#warning both ftruncate and chsize functions appear to be missing from this OS
#endif

        /* Step 2: Flush internal stdio buffers to ensure data is physically committed */
        fsync(so->fd);

        /* Step 3: Release the kernel lock. Now external hooks can safely read a 100% complete file. */
        #ifdef HAVE_SYS_FILE_H
        flock(so->fd, LOCK_UN);
        #endif

        /* clear read buffer */
        if (buf_defined(&so->read_buf))
        {
            ASSERT(buf_init(&so->read_buf, 0));
        }
    }
}

By ensuring that flock(so->fd, LOCK_EX) encapsulates the ftruncate block and adding fsync(so->fd), the kernel serializes read/write operations seamlessly. I highly recommend merging a similar thread-safe approach into upstream core to prevent data corruption for downstream management tools.

Disclaimer & Technical Note:
Please note that I am sharing this patch based on my own local troubleshooting and testing, which successfully resolved the issue in my environment. As I do not possess deep architectural knowledge of the OpenVPN codebase, I am not 100% certain if this is the most optimal or standard way upstream handles file synchronization, or if it might impact other platforms (like Windows/macOS).

This is purely a constructive suggestion from my testing experience, offered with the utmost respect to the core maintainers. I would highly appreciate the core developers' expert insight on whether this approach is safe or if there is a more idiomatic way within the OpenVPN architecture to achieve the same synchronized/atomic write behavior.

Lingua principale
C
Stelle
14.8k
Fork
3.4k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di OpenVPN/openvpn

Tutte le issue di OpenVPN/openvpn

Issue simili

Altre issue su C

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.