python言語ってC言語などにくらべると安全そうなイメージがありますが、やはりセキュリティには気をつけないといけない、ということで 開発した python コードが安全かどうか調べるツールがないか調べてみました。
すると、bandit というツールが無償で利用できることがわかりました。
そこでこのツールを使って自分で開発した python プログラムのセキュリティチェックを行ってみましたのでここに記録しておきます。
なお、この bandit でチェックする前に、python のコーディング規約チェッカーである PEP 8 を使ってある程度(- -; コーディング規約に従うようにプログラムを修正しております。
この PEP 8 の PyCharm での利用方法については以下のサイトに記載しております。
それでは bandit をインストールするところから行きたいと思います。
1.bandit のインストール
bandit のインストールは非常に簡単です。
pip がインストールされていれば、以下のコマンドを実行するだけです。
$ pip install pandit
なお、私の環境では pythonのバージョンがデフォルトで 2.X系になってしまっていた為、以下のような警告が出てしまいました。

これを3系に変えようと思い pyenv を利用してみましたが一筋縄ではいかず、以下のサイトに助けていただきうまくいきました。ありがとうございました。m(_ _)m
pyenvでPythonのバージョンが切り替わらないときの対処方法【Mac Apple silicon環境】(ヒトリセカイ)https://hitori-sekai.com/python/error-pyenv/
2.banditの実行
bandit の実行も非常に簡単です。以下のとおりコマンドを打つだけです。
$ bandit <プログラム名>
実際に自分で作成したスクレイピングを行う pythonプログラムに対して実行してみた結果は以下の通りです。

ちょっと上の画像は見にくいので、テキストでも掲載しておきます。
% bandit test.py
[main] INFO profile include tests: None
[main] INFO profile exclude tests: None
[main] INFO cli include tests: None
[main] INFO cli exclude tests: None
[main] INFO running on Python 3.8.3
[node_visitor] WARNING Unable to find qualified name for module: test.py
Run started:2023-08-14 01:37:45.050500
Test results:
>> Issue: [B113:request_without_timeout] Requests call without timeout
Severity: Medium Confidence: Low
CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html)
More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b113_request_without_timeout.html
Location: test.py:31:11
30 # Get the HTML content of the top page
31 response = requests.get(url)
32 html = response.content.decode("utf-8")
--------------------------------------------------
>> Issue: [B113:request_without_timeout] Requests call without timeout
Severity: Medium Confidence: Low
CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html)
More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b113_request_without_timeout.html
Location: test.py:62:15
61
62 response = requests.get(link)
63 html = response.content.decode("utf-8")
--------------------------------------------------
Code scanned:
Total lines of code: 46
Total lines skipped (#nosec): 0
Run metrics:
Total issues (by severity):
Undefined: 0
Low: 0
Medium: 2
High: 0
Total issues (by confidence):
Undefined: 0
Low: 2
Medium: 0
High: 0
Files skipped (0):
%
3.bandit 実行結果の考察
どうやら「Test results:」という部分にプログラムの問題点が列挙されているようです。
2つ「Issue」が記載されていますが、どちらも Requests call without timeout となっています。
実際このプログラムでは指定したWebサイトからデータを取ってきているのですが、その時にタイムアウトの処理をしていませんでした。
たしかにこのままだと、Webサイトから応答が返ってくるまで繋ぎっぱなしになってしまい、そのまま何度もこのプログラムを実行するとサーバもクライアントもリソーズ不足になってしまいそうです。
改めて、こういったセキュリティチェック(ツール)の重要性を認識することができました。

