Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

Directory Reading

In the last weeks I have seen far too much code which reads directory content in horribly inefficient ways to let this slide. Programmers really have to learn…

Beitrag
0
Seite
0
↗ Quelle (udrepper.livejournal.com)
Cloud & Tech-Stack · 5 Min. Lesezeit
Quelle: udrepper.livejournal.com
Rubrik: Servidores Unix y Linux

In the last weeks I have seen far too much code which reads directory content in horribly inefficient ways to let this slide. Programmers really have to learn doing this efficiently. Some of the instances I've seen are in code which runs frequently. Frequently as in once per second. Doing it right can make a huge difference.



The following is an exemplary piece of code. Not taken from an actual project but it shows some of the problems quite well, all in one example. I drop the error handling to make the point clearer.




DIR *dir = opendir(some_path);
struct dirent *d;
struct dirent d_mem;
while (readdir_r(d, &d_mem, &d) == 0) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s/somefile", some_path, d->d_name);
int fd = open(path, O_RDONLY);
if (fd != -1) {
... do something ...
close (fd);
}
}
closedir(dir);


How many things are inefficient at best and outright problematic in some cases?



Let's enumerate:




  1. Why use readdir_r?

  2. Even the use of readdir is dangerous.

  3. Creating a path string might exceed the PATH_MAX limit.

  4. Using a path like this is racy.

  5. What if the directory contain entries which are not directories?



readdir_r is only needed if multiple threads are using the same directory stream. I have yet to see a program where this really is the case. In this toy example the stream (variable dir) is definitely not shared between different threads. Therefore the use of readdir is just fine. Should this matter? Yes, it should, since readdir_r has to copy the data in into the buffer provided by the user while readdir has the possibility to avoid that.



Instead of readdir code should in fact use readdir64. The definition of the dirent structure comes from an innocent time when hard drive with a couple of dozen MB of capacity were huge. Things change and we need larger values for inode numbers etc. Modern (i.e., 64-bit) ABIs do this by default but if the code is supposed to be used on 32-bit machines as well the *64 variants should always be used.



Path length limits are becoming an ever-increasing problem. Linux, like most Unix implementations, imposes a length limit on each filename string which is passed to a system call. But this does not mean that in general path names have any length limit. It just means that longer names have to be implicitly constructed through the use of multiple relative path names. In the example above, what happens if some_path is already close to PATH_MAX bytes in size? It means the snprintf call will truncate the output. This can and should of course be caught but this doesn't help the program. It is crippled.



Any use of filenames with path components (i.e., with one or more slashes in the name) is racy and an attacker change any of the contained path components. This can lead to exploits. In the example, the some_path string itself might be long and traverse multiple directories. A change in any of these will lead to the open call not reaching the desired file or directory.



Finally, while the code above works (the open call will fail if d->d_name does not name a directory) it is anything but efficient. In fact, the open system calls are quite expensive. Before any work is done, the kernel has to reserve a file descriptor. Since file descriptors are a shared resource this requires coordination and synchronization which is expensive. Synchronization also reduces parallelism, which might be a big issue in some code. The open call then has to follow the path which also is not free.



To make a long story short, here is how the code should look like (again, sans error handling):




DIR *dir = opendir(some_path);
int dfd = dirfd(dir);
struct dirent64 *d;
while ((d = readdir64(dir)) != NULL) {
if (d->d_type != DT_DIR && d->d_type != DT_UNKNOWN)
continue;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/somefile", d->d_name);
int fd = openat(dfd, path, O_RDONLY);
if (fd != -1) {
... do something ...
close (fd);
}
}
closedir(dir);


This rewrite addresses all the issues. It uses readdir64 which will do just fine in this case and it is safe when it comes to huge disk drives. It uses the d_type field of the dirent64 to check whether we already know the file is no directory. Most of Linux's directories today fill in the d_type field correctly (including all the pseudo filesystems like sysfs and proc). Those file systems which do not have the information handy fill in DT_UNKNOWN which is why the code above allows this case, too. In some program one also might want to allow DT_LNK since a symbolic link might point to a directory. But more often enough this is not the case and not following symlinks is a security measure.



Finally, the new code uses openat to open the file. This avoids the length path lookup and it closes most of the races of the original open call since the pathname lookup starts at the directory read by readdir64. Any change to the filesystem below this directory has no effect on the openat call. Also, since now the generated path is very short (just the maximum of 256 bytes for d_name plus 10 we know that the buffer path is sufficient.



It is easy enough to apply these changes to all the places which read directories. The result will be small, faster, and safer code.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Debate de la comunidad y comentarios

🌐 Unirse al chat principal

Inicia el debate en el stream de difusión del Social Chat o envía arriba una contribución experta mediante el formulario de ampliación.

🔍 CTI & Forensik

Inteligencia de Ciberamenazas y Forense

Navegador ATT&CK · Radar IoC · Evidencias de Exploit
CTI Threat Relationship Graph
Akteure · Techniken · Beziehungen
3 Knoten · 2 Relationen
CVE / Incident Threat Actor Software MITRE ATT&CK CWE Weakness IoC
Briefing de seguridad Gratis · baja en 1 clic

Intelligence Digest — gratis

Cada día las noticias de seguridad más importantes · baja en cualquier momento

Valoración de la comunidad & prueba social
⭐ Valoración de los lectores
–
Ø / 5.0
Aún no hay valoraciones de lectores
¿Le ha resultado útil este artículo?
0
Dejar una valoración ahora
Valoración detallada (opcional)
Contenido & calidad
Fuente & credibilidad
Actualidad

Clústeres de historias relacionados & fuentes (IA vectorial)

6 Cluster
26 fuentes
Black Friday Oura Ring deals: The best of the deals so far, picked by a wearable-tech expert
Latest from TechRadar hace 13 min.
25 fuentes más
CNEThace 6 añosOur Favorite Blenders of 2026 Are on Sale Ahead of Black Friday CNEThace 17 min.Brighten Up Your Day by Saving 20% Off Flashlights With Olight’s Black Friday Sale CNEThace 9 min.Live: Black Friday Deals Are Here. Shop Expert Picks Across Tech, Everyday Essentials and More at Up to 60% Off Golem.dehace 23 min.Anzeige: Logitech-Tastatur MX Keys S am Black Friday zum Sensationspreis auf Amazon PC-WELThace 35 min.Luminar zum Black Friday: KI-Bildbearbeitung für nur 79,20 Euro Latest from TechRadarhace 50 min.This is the pair of open earbuds to hunt down over Black Friday Latest from TechRadarhace 1 hBest AirPods Black Friday deals: all live savings on AirPods Pro 3 and more Computer Bildhace 1 hPhilips Sonicare DiamondClean 9000 zum Black Friday günstiger netzwelt.dehace 2 hESR startet mit Black-Friday-Rabatten: Diese AirPods-Hüllen lohnen sich jetzt netzwelt.dehace 2 hPlayStation 5 geschenkt: Diese Black-Friday-Aktion legt die Konsole gratis obendrauf netzwelt.dehace 1 h6 Dyson-Staubsauger im Vergleich: Dieser Sauger wird am Black Friday überraschend zum Preis/Leistungssieger netzwelt.dehace 1 hMonitore im Angebot zum Black Friday: Gutes Bild für Office, Gaming und mehr Golem.dehace 53 min.Anzeige: Akkuschrauber mit 20 Bits zum Black Friday erstmals unter 50 Euro bei Amazon PC-WELThace 1 hDie günstigsten Handytarife an Black Friday von 10 GB bis Unlimited: Hier lohnt sich ein Wechsel PC-WELThace 1 hBlack Friday 2026 bei LiberNovo: Ergonomische Bürostühle mit bis zu 44 Prozent Rabatt Latest from TechRadarhace 1 hThe best Black Friday robot vacuum deals: Dreame, Shark, Dyson, and Roborock Golem.dehace 1 hAnzeige: Topdon-Starthilfe-Powerbank für Kfz zum Black-Friday-Bestpreis nur rund 85 Euro heise online Newshace 1 hBlack Friday: Die besten Kopfhörer zum Tiefstpreis – Sonos Ace, Nothing & Shokz Latest from Windows Centralhace 1 hDell's Black Friday deals drop major savings on Alienware OLED monitors CNEThace 2 añosMake Every Night Game Night and Save $90 on the Nex Playground With This Black Friday Deal DEV Communityhace 1 hThe app is part of the gadget: 14,000 App Store reviews of 28 device apps before Black Friday Latest from TechRadarhace 2 hBlack Friday tech deals under $100 / £100: Fire TV Sticks, earbuds, coffee machines and more Caschys Bloghace 3 hGoogle One: Black-Friday-Angebot mit bis zu 50 Prozent Rabatt netzwelt.dehace 2 hDem Testsieger ebenbürtig: Zum Black Friday stürzt Xiaomis stärkster E-Scooter im Preis ab Macerkopf.dehace 2 hFotos verbessern mit Aiarty: 52 % Rabatt + Gratisgeschenke zum Black Friday
Artículos similares
🔍 Verwandte News

Auch interessante Nachrichten Directory Reading

Thematisch verwandte Begriffe: Directory, Reading · 6 Treffer

Laden...

Cargando vídeos ...

Laden...

Cargando artículos ...

Laden...

Cargando vídeos ...

Laden...

Cargando artículos ...

Laden...

Cargando vídeos ...

💬 Cargando comentarios…
Desliza para actualizar
Widgets & Topics
Loading widgets…
Nächster Beitrag