メインコンテンツ

CWE Rule 367

Time-of-check Time-of-use (TOCTOU) Race Condition

R2024a 以降

説明

ルールの説明

The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check.This can cause the product to perform invalid actions when the resource is in an unexpected state.

Polyspace 実装

ルール チェッカーは、"チェック時と使用時 (TOCTOU) の間のファイル アクセス" をチェックします。

すべて展開する

問題

この問題は、ファイルまたはフォルダーの存在をチェックして使用するまでの間に競合状態が生じた場合に発生します。

リスク

攻撃者は、ファイルのチェックとファイルの使用の間に、そのファイルにアクセスして操作できます。攻撃者はシンボリック リンクが指す場所を変更できるため、シンボリック リンクは特にリスクが大きくなります。

修正方法

ファイルを使用する前は、そのステータスをチェックしないようにします。代わりに、ファイルを使用してから、その結果をチェックします。

例 — ファイルを使用前にチェック
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

extern void print_tofile(FILE* f);

void toctou(char * log_path) {
    if (access(log_path, W_OK)==0) {
        FILE* f = fopen(log_path, "w"); //Noncompliant
        if (f) {
            print_tofile(f);
            fclose(f);
        }
    }
}

この例では、ファイルを開いて使用する前に、ファイルが存在するかどうかを関数でチェックしています。しかし攻撃者は、関数の 1 行目と 2 行目の間でファイルを変更できます。

修正 — 開いてからチェック

1 つの修正方法として、ファイルを開き、後からその存在と内容をチェックします。

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

extern void print_tofile(FILE* f);

void toctou(char * log_path) {
    int fd = open(log_path, O_WRONLY);
    if (fd!=-1) {
        FILE *f = fdopen(fd, "w");
        if (f) {
            print_tofile(f);
            fclose(f);
        }
    }
}

チェック情報

カテゴリ: Concurrency Issues

バージョン履歴

R2024a で導入