![]() |
Unsicherer Code
Hallo,
ich habe das Problem folgenden unsicheren Code in einen sicheren Code umschreiben zu müssen. Dieses Programm erzeugt temporäre Dateien nach einem Schema, dass eine Race Condition, zwischen Erzeugung der temporären Datei und dem Nachsehen ob es eine Datei mit diesem Namen schon gibt, zulässt. Soweit ich weiss ist dies mit Verwendung von mkstemp(3) kein Problem mehr. Nur weiss ich nicht wie ich es umsetzen soll. Dem Programm übergibt man als Kommandozeilenargument ein Präfix, dass um die PID und eine fortlaufende Nummer erweitert, als Name der temorären Datei verwendet wird. #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <limits.h> /* times are in mikroseconds */ /* #define USLEEPTIME 5000 */ #define LOOPTIME 10000 void usage(const char *progname) { fprintf(stderr, "%s: usage\n" "%s <tempfile>", progname, progname); } int main(int argc, char *argv[]) { const char *tempfile; struct timespec nano; struct stat statbuf; char buf[80]; char filename[PATH_MAX + 100]; int fd; int rc; int cnt = 0; if (argc < 2) { usage(argv[0]); exit(1); } tempfile = argv[1]; sprintf(filename, "%s.%d.%d", tempfile, getpid(), cnt++); printf("using %s as temporary file\n", filename); sprintf(buf, "%ld\n", getpid()); for ( ; ; usleep(LOOPTIME) ) { /* check for existing tempfile ... */ if (stat(filename, &statbuf) == 0 || lstat(filename, &statbuf) == 0) { sprintf(filename, "%s.%d.%d", tempfile, getpid(), cnt++); printf("\ntempfile exists already - retrying with %s\n", filename); continue; } usleep(LOOPTIME); fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0600); if (fd == -1) { perror("open"); exit(2); } rc = write(fd, buf, strlen(buf)); if (rc == -1) { perror("write"); exit(2); } close(fd); unlink(filename); printf("."); fflush(stdout); } return 0; } Wie macht man daraus ein sicheres Programm? AlphaCentauri |
Code:
#include <stdio.h> |
Alle Zeitangaben in WEZ +2. Es ist jetzt 16:31 Uhr. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
© 2009 FSL Verlag