Skip to content

Commit

Permalink
Merge pull request #78 from kantabile/trans/python-vulnerbility-2023-…
Browse files Browse the repository at this point in the history
…03-04

RSPEC-5445, RSPEC-5527, RSPEC-5543
  • Loading branch information
bourbonkk authored Sep 16, 2023
2 parents 614c791 + 1465d3c commit f73629f
Show file tree
Hide file tree
Showing 3 changed files with 273 additions and 0 deletions.
53 changes: 53 additions & 0 deletions _posts/python/2023-03-04-RSPEC-5445.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
title: 안전하지 않은 임시 파일 생성 방법을 사용해서는 안 됩니다.
tags:
- Vulnerability
- Critical
- cwe
- owasp
- python
---

안전하지 않은 방법으로 임시 파일을 만들면 애플리케이션이 파일 이름에 대한 경쟁 조건에 노출됩니다.
악의적인 사용자가 애플리케이션보다 먼저 예측 가능한 이름으로 파일을 만들려고 시도할 수 있습니다.
공격이 성공하면 다른 파일이 액세스, 수정, 손상 또는 삭제될 수 있습니다. 애플리케이션이 상승된 권한으로 실행되는 경우 이러한 위험은 더욱 높아집니다.

과거에는 다음과 같은 취약점이 발생했습니다:
- [CVE-2014-1858](https://nvd.nist.gov/vuln/detail/CVE-2014-1858)
- [CVE-2014-1932](https://nvd.nist.gov/vuln/detail/CVE-2014-1932)

### 규칙을 어긴 코드
```python
import tempfile

filename = tempfile.mktemp() # 규칙을 어긴 코드
tmp_file = open(filename, "w+")
```


### 규칙을 준수한 해결책

```python
import tempfile

tmp_file1 = tempfile.NamedTemporaryFile(delete=False) # 규칙을 준수한 코드; tempfile.mktemp()로 쉽게 대체 가능
tmp_file2 = tempfile.NamedTemporaryFile() # 규칙을 준수한 코드; 생성된 파일은 자동으로 삭제됩니다
```


### 같이보면 좋은 자료
- [OWASP Top 10 2021 Category A1](https://owasp.org/Top10/A01_2021-Broken_Access_Control/) - 취약한 접근 제어
- [OWASP Top 10 2017 Category A9](https://owasp.org/www-project-top-ten/2017/A9_2017-Using_Components_with_Known_Vulnerabilities) - 알려진 취약점이 있는 컴포넌트 사용
- [MITRE, CWE-377](https://cwe.mitre.org/data/definitions/377) - 안전하지 않은 임시 파일
- [MITRE, CWE-379](https://cwe.mitre.org/data/definitions/379) - 잘못된 권한으로 디렉토리에 임시 파일 생성
- [OWASP, Insecure Temporary File](https://owasp.org/www-community/vulnerabilities/Insecure_Temporary_File)
- [Python tempfile module](https://docs.python.org/3/library/tempfile.html#deprecated-functions-and-variables)
- [Python 2.7 os module](https://docs.python.org/2.7/library/os.html)
---


If you like SONARKUBE, don't forget to give me a star. :star2:

> [원문으로 바로가기](https://rules.sonarsource.com/python/type/Vulnerability/RSPEC-5445)
> [![Star This Project](https://img.shields.io/github/stars/kantabile/sonarkube.svg?label=Stars&style=social)](https://github.com/kantabile/sonarkube)
72 changes: 72 additions & 0 deletions _posts/python/2023-03-04-RSPEC-5527.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
title: SSL/TLS 연결 중에 서버 호스트 이름을 확인해야 합니다.
tags:
- Vulnerability
- Critical
- cwe
- privacy
- owasp
- ssl
- python
---

중간자 공격에 취약하지 않은 SSL/TLS 연결을 설정하려면 서버가 올바른 인증서를 제공하는지 확인해야 합니다.

인증서의 호스트 이름 관련 데이터는 서버 호스트 이름과 일치해야 합니다.

사용자 지정 호스트 이름 확인을 구현하여 새것을 만들지 않는 것이 좋습니다.

TLS/SSL 라이브러리에는 호스트 이름 확인 기능이 내장되어 있으므로 이를 사용해야 합니다.

### 규칙을 어긴 코드
Python [ssl standard](https://docs.python.org/3/library/ssl.html) 라이브러리:

```python
import ssl

ctx = ssl._create_unverified_context() # 규칙을 어긴 코드: 기본적으로 호스트 이름 확인은 수행되지 않습니다
ctx = ssl._create_stdlib_context() # 규칙을 어긴 코드: 기본적으로 호스트 이름 확인은 수행되지 않습니다

ctx = ssl.create_default_context()
ctx.check_hostname = False # 규칙을 어긴 코드

ctx = ssl._create_default_https_context()
ctx.check_hostname = False # 규칙을 어긴 코드
```



### 규칙을 준수한 해결책
Python [ssl standard](https://docs.python.org/3/library/ssl.html) 라이브러리:

```python
import ssl

ctx = ssl._create_unverified_context()
ctx.check_hostname = True # 규칙을 준수한 코드

ctx = ssl._create_stdlib_context()
ctx.check_hostname = True # 규칙을 준수한 코드

ctx = ssl.create_default_context() # 규칙을 준수한 코드: 기본적으로 호스트 이름 확인이 활성화되어 있습니다
ctx = ssl._create_default_https_context() # 규칙을 준수한 코드: 기본적으로 호스트 이름 확인이 활성화되어 있습니다
```


### 같이보면 좋은 자료
- [OWASP Top 10 2021 Category A2](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/) - 암호화 실패
- [OWASP Top 10 2021 Category A5](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/) - 보안 구성 오류
- [OWASP Top 10 2021 Category A7](https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/) - 식별 및 인증 실패
- [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/2017/A3_2017-Sensitive_Data_Exposure) - 민감한 데이터 노출
- [OWASP Top 10 2017 Category A6](https://owasp.org/www-project-top-ten/2017/A6_2017-Security_Misconfiguration) - 보안 구성 오류
- [Mobile AppSec Verification Standard](https://mobile-security.gitbook.io/masvs/security-requirements/0x10-v5-network_communication_requirements) - 네트워크 통신 요구 사항
- [OWASP Mobile Top 10 2016 Category M3](https://owasp.org/www-project-mobile-top-10/2016-risks/m3-insecure-communication) - 안전하지 않은 통신
- [MITRE, CWE-297](https://cwe.mitre.org/data/definitions/297) - 호스트 불일치로 인한 부적절한 인증서 유효성 검사
---


If you like SONARKUBE, don't forget to give me a star. :star2:

> [원문으로 바로가기](https://rules.sonarsource.com/python/type/Vulnerability/RSPEC-5527)
> [![Star This Project](https://img.shields.io/github/stars/kantabile/sonarkube.svg?label=Stars&style=social)](https://github.com/kantabile/sonarkube)
148 changes: 148 additions & 0 deletions _posts/python/2023-03-04-RSPEC-5543.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
---
title: 암호화 알고리즘은 보안 모드 및 패딩 체계와 함께 사용해야 합니다.
tags:
- Vulnerability
- Critical
- cwe
- privacy
- owasp
- sans-top25
- python
---


암호화 알고리즘은 데이터 기밀성과 무결성을 보장하기 위해 적절한 경우 보안 모드와 패딩 체계를 사용해야 합니다.

- 블록 암호 암호화 알고리즘(예: AES)의 경우:
- ECB(Electronic Codebook) 암호화 모드는 주어진 키 아래에서 주어진 일반 텍스트 블록이 항상 동일한 암호 텍스트 블록으로 암호화되므로 메시지 기밀성을 제대로 제공하지 못합니다.
이 모드는 절대로 사용해서는 안 됩니다.
- CBC(Cipher Block Chaining) 모드는 그 자체로 데이터 기밀성만 제공합니다. 이 암호화 모드는 패딩과 함께 사용할 경우 [패딩 오라클 공격](https://en.wikipedia.org/wiki/Padding_oracle_attack)에 취약합니다.
메시지 인증 코드와 함께 CBC를 사용하면 데이터 무결성을 제공할 수 있으며 이러한 공격을 방지할 수 있습니다. 실제로 구현에는 많은 함정이 있으므로 패딩과 함께 CBC를 완전히 피하는 것이 좋습니다.
- [내부적](https://en.wikipedia.org/wiki/Galois/Counter_Mode#Mathematical_basis)으로 패딩이 없거나 패딩이 있는 방식으로 작동하는 GCM(Galois Counter Mode) 모드는 데이터 신뢰성(무결성)과 기밀성을 모두 제공하도록 설계되었으므로 권장됩니다.
다른 유사한 모드로는 CCM, CWC, EAX, IAPM 및 OCB가 있습니다.
- RSA 암호화 알고리즘의 경우, 권장 패딩 체계는 OAEP입니다.


### 규칙을 어긴 코드
[pycryptodomex](https://pycryptodome.readthedocs.io/) 라이브러리:
```python
from Cryptodome.Cipher import AES, PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA

# 대칭 암호의 예시: AES
AES.new(key, AES.MODE_ECB) # 규칙을 어긴 코드
AES.new(key, AES.MODE_CBC) # 규칙을 어긴 코드

# 비대칭 암호의 예시: RSA
cipher = PKCS1_v1_5.new(key) # 규칙을 어긴 코드

```

[pyca](https://cryptography.io/en/latest/) 라이브러리:
```python
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

# 대칭 암호의 예시: AES
aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # 규칙을 어긴 코드
aes = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) # 규칙을 어긴 코드

# 비대칭 암호의 예시: RSA
ciphertext = public_key.encrypt(
message,
padding.PKCS1v15() # 규칙을 어긴 코드
)

plaintext = private_key.decrypt(
ciphertext,
padding.PKCS1v15() # 규칙을 어긴 코드
)
```
[pydes](https://pypi.org/project/pyDes/) 라이브러리:
```python
# DES 암호의 경우
des = pyDes.des('ChangeIt') # 규칙을 어긴 코드
des = pyDes.des('ChangeIt', pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # 규칙을 어긴 코드
des = pyDes.des('ChangeIt', pyDes.ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # 규칙을 어긴 코드
```
[pycrypto](https://pycrypto.readthedocs.io/en/latest/) 라이브러리는 유지보수되고 있지 않기 때문에 사용해서는 안됩니다:
```python
# https://pycrypto.readthedocs.io/en/latest/
from Crypto.Cipher import *
from Crypto.Random import get_random_bytes
from Crypto.Util import Counter
from Crypto.PublicKey import RSA

# 대칭 암호의 예시: AES
AES.new(key, AES.MODE_ECB) # 규칙을 어긴 코드
AES.new(key, AES.MODE_CBC, IV=iv) # 규칙을 어긴 코드

# 비대칭 암호의 예시: RSA
cipher = PKCS1_v1_5.new(key) # 규칙을 어긴 코드
```



### 규칙을 준수한 해결책
[pycryptodomex](https://pycryptodome.readthedocs.io/) 라이브러리:
```python
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA

# AES는 GCM 모드에서 권장되는 대칭형 암호입니다
AES.new(key, AES.MODE_GCM) # 규칙을 준수한 해결책

# RSA는 OAEP 패딩이 있는 권장 비대칭 암호입니다
cipher = PKCS1_OAEP.new(key) # 규칙을 준수한 해결책
```

[pyca](https://cryptography.io/en/latest/) 라이브러리:
```python
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

# AES는 GCM 모드에서 권장되는 대칭형 암호입니다
aes = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) # 규칙을 준수한 해결책

# RSA는 OAEP 패딩이 있는 권장 비대칭 암호입니다
ciphertext = public_key.encrypt(
message,
padding.OAEP( # 규칙을 준수한 해결책
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)

plaintext = private_key.decrypt(
ciphertext,
padding.OAEP( # 규칙을 준수한 해결책
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
```


### 같이보면 좋은 자료
- [OWASP Top 10 2021 Category A2](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/) - 암호화 실패
- [OWASP Top 10 2017 Category A6](https://owasp.org/www-project-top-ten/2017/A6_2017-Security_Misconfiguration) - 보안 구성 오류
- [MITRE, CWE-327](https://cwe.mitre.org/data/definitions/327) - 깨지거나 위험한 암호화 알고리즘 사용
- [SANS Top 25](https://www.sans.org/top25-software-errors/#cat3) - 다공성 방어
---


If you like SONARKUBE, don't forget to give me a star. :star2:

> [원문으로 바로가기](https://rules.sonarsource.com/python/type/Vulnerability/RSPEC-5543)
> [![Star This Project](https://img.shields.io/github/stars/kantabile/sonarkube.svg?label=Stars&style=social)](https://github.com/kantabile/sonarkube)

0 comments on commit f73629f

Please sign in to comment.