程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python code security guide

編輯:Python

Code security guide for developers , To sort out API And provide detailed and feasible security coding scheme . be based on DevSecOps idea , We hope to explain the secure coding scheme in a way that is easier for developers to understand , Guide to avoid loopholes from the source .

Python Code security guide

generic class

1. Code implementation

After the code is written , follow-up work , Such as encryption code !

1.1 encryption algorithm

  • 【 must 】 Avoid using insecure symmetric encryption algorithms
    • DES and 3DES It is no longer applicable to modern applications , Should be changed to use AES.

1.2 Program log

  • 【 Suggest 】 Log every important action
    • Ensure that important actions are logged , And reliable storage 6 A month or more
  • 【 Suggest 】 Do not log unauthenticated user input directly
    • A record injection vulnerability is triggered when log entries contain raw user input
    • Malicious users will insert forged log data , So that the system administrator thinks it is a system behavior
  • 【 Suggest 】 Avoid keeping sensitive information in the log
    • Cannot save password in log ( Including plaintext password and ciphertext password )、 Keys and other sensitive information

1.3 System Password

  • 【 must 】 It is forbidden to use empty words 、 Weak password 、 The password has been leaked
  • 【 must 】 Password strength requirements

bash

# The password strength must meet
1. The password length is greater than 14 position
2. The following elements must be included : Case letters 、 Numbers 、 Special characters
3. Do not use each system 、 The default initial password for the program
4. Not with the recent 6 The password used times is repeated
5. Do not use the same password as other external systems 
  • 【 must 】 Password storage security
    • Password storage in clear text is prohibited
    • The use of weak cryptographic algorithms is prohibited ( Such as DES and 3DES) Encrypted storage password
    • Use irreversible algorithm and random salt Encrypt and store passwords
  • 【 must 】 Clear text passwords are prohibited
  • 【 must 】 It is forbidden to transmit passwords in insecure channels

2. To configure & Environmental Science

Before releasing the system or launching the environment , Something to be aware of !

2.1 Version selection

  • 【 Suggest 】 Use Python 3.6+ Version of
    • New items should use Python 3.6+ edition

bash

# Why do you do this ?
because Python2 stay 2020 Maintenance stopped in , The vulnerability of related components cannot be repaired and maintained in time !

2.2 Third party package security

  • 【 must 】 Do not use unsafe components

2.3 Configuration information

  • 【 must 】 Key storage security
    • When using symmetric cryptographic algorithms , Need to protect the encryption key . When the algorithm involves sensitivity 、 Business data , Encryption keys can be negotiated through asymmetric algorithms
    • Other less sensitive data encryption , The key can be protected by transformation algorithm and other methods
  • 【 must 】 Hard coding of sensitive configurations is prohibited
    • Hard coding in the source code is prohibited AK/SKIP、 Database account secret and other configuration information
    • A configuration system or KMS Key management system

Background class

This is a gorgeous dividing line

1. Code implementation

Writing code is a problem that needs to be considered and thought !

1.1 Input validation

  • 【 must 】 Data verification by type
    • All parameter values input outside the program , Data verification shall be performed , If the verification fails, it shall be rejected
    • The verification contents include but are not limited to : Data length 、 Data range 、 Data types and formats
    • Recommended components :CerberusjsonschemaDjango-Validators

python

# Cerberus Example
v = Validator({'name': {'type': 'string'}})
v.validate({'name': 'john doe'})
# jsonschema Example
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
},
}
validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)

1.2 SQL operation

  • 【 must 】 Using parameterized queries
    • Use parameterization SQL sentence , Force a distinction between data and commands , Avoid producing SQL Inject holes .

python

# The wrong sample
import mysql.connector
mydb = mysql.connector.connect(
... ...
)
cur = mydb.cursor()
userid = get_id_from_user()
# Use % Directly format string splicing SQL sentence
cur.execute("SELECT `id`, `password` FROM `auth_user` WHERE `id`=%s " % (userid,))
myresult = cur.fetchall()

python

# Safety example
import mysql.connector
mydb = mysql.connector.connect(
... ...
)
cur = mydb.cursor()
userid = get_id_from_user()
# Pass tuples as parameters
cur.execute("SELECT `id`, `password` FROM `auth_user` WHERE `id`=%s " , (userid,))
myresult = cur.fetchall()
  • 【 must 】 Using parameterized queries
    • Recommended ORM Framework to manipulate the database , Such as : Use SQLAlchemy.

python

# install sqlalchemy And initialize the database connection
# pip install sqlalchemy
from sqlalchemy import create_engine
# Initialize database connection , Change to your database user name and password
engine = create_engine('mysql+mysqlconnector://user:[email protected]:port/DATABASE')

python

# Reference data type
from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Definition Player object :
class Player(Base):
# Name of table :
__tablename__ = 'player'
# The structure of the table :
player_id = Column(Integer, primary_key=True, autoincrement=True)
team_id = Column(Integer)
player_name = Column(String(255))
height = Column(Float(3, 2))

python

# Additions and deletions
from sqlalchemy.orm import sessionmaker
# establish DBSession type :
DBSession = sessionmaker(bind=engine)
# establish session object :
session = DBSession()
# increase :
new_player = Player(team_id=101, player_name="Tom", height=1.98)
session.add(new_player)
# Delete :
row = session.query(Player).filter(Player.player_name=="Tom").first()
session.delete(row)
# Change :
row = session.query(Player).filter(Player.player_name=="Tom").first()
row.height = 1.99
# check :
rows = session.query(Player).filter(Player.height >= 1.88).all()
# Submit and save to database :
session.commit()
# close session:
session.close()
  • 【 must 】 Filter the parameters
    • Dynamically splice the received external parameters to SQL When the sentence is , Parameters must be safely filtered .

python

def sql_filter(sql, max_length=20):
dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+",
"&", "$", "(", ")", "%", "@", ","]
for stuff in dirty_stuff:
sql = sql.replace(stuff, "x")
return sql[:max_length]

1.3 Carry out orders

  • 【 Suggest 】 Avoid calling functions directly to execute system commands
    • The implementation of relevant functions shall avoid directly calling system commands , Such as os.system()os.popen()subprocess.call() etc. .
    • It is preferred to use other similar operations instead , such as : Through the file system API Perform file operations instead of directly invoking operating system commands .
    • If the assessment cannot be avoided , Execute the command to avoid splicing external data , At the same time, the white list for executing commands is restricted .
  • 【 must 】 Filter the characters of the incoming command execution function
    • When a program calls various functions to execute system commands , If the command involved is passed in from outside , Filter the characters of the incoming command execution function .

python

import os
import sys
import shlex
domain = sys.argv[1]
# Replace empty characters that can be used to inject commands
badchars = "\n&;|'\"$()`-"
for char in badchars:
domain = domain.replace(char, " ")
result = os.system("nslookup " + shlex.quote(domain))

1.4 XML Reading and writing

  • 【 must 】 Methods to disable external entities
    • Methods to disable external entities , To prevent XXE attack .

python

from lxml import etree
xmlData = etree.parse(xmlSource,etree.XMLParser(resolve_entities=False))

1.5 File operations

  • 【 must 】 File type restrictions
    • Type of uploaded or downloaded files through the white list 、 Size is strictly checked .
    • Only the file types required by the business are allowed to upload , Avoid uploading Trojans 、WebShell Wait for the documents .

python

import os
ALLOWED_EXTENSIONS = ['txt','jpg','png']
def allowed_file(filename):
if ('.' in filename and
'..' not in filename and
os.path.splitext(filename)[1].lower() in ALLOWED_EXTENSIONS):
return filename
return None
  • 【 must 】 Prohibit external files from being stored in the executable directory
    • Prohibit external files from being stored in WEB The executable directory of the container (appBase).
    • It is recommended to use tempfile The library handles temporary files and directories .
  • 【 must 】 Avoid path crossing
    • When saving in the local file system , The path must be legally verified , Avoid directory traversal vulnerability .

python

import os
upload_dir = '/tmp/upload/' # Expected upload directory
file_name = '../../etc/hosts' # The file name passed in by the user
absolute_path = os.path.join(upload_dir, file_name) # /tmp/upload/../../etc/hosts
normalized_path = os.path.normpath(absolute_path) # /etc/hosts
if not normalized_path.startswith(upload_dir): # Check whether the final path is in the expected upload directory
raise IOError()
  • 【 Suggest 】 Avoid path splicing
    • The file directory avoids the splicing of external parameters . It is recommended to write the file directory in the background and verify the file name ( Character type 、 length ).
  • 【 Suggest 】 file name hash Chemical treatment
    • It is recommended to save the file , Replace the file name with a random string .

python

import uuid
def random_filename(filename):
ext = os.path.splitext(filename)[1]
new_filename = uuid.uuid4().hex + ext
return new_filename

1.6 Network request

  • 【 must 】 Limit the address range for accessing network resources

bash

# When the program needs to be provided from the user URL Address for information
# As specified URL Address to get text content of web page 、 Load a picture at the specified address 、 When downloading, etc , Need for URL Address for security verification
1. Only HTTP or HTTPS agreement
2. Analyze goals URL, Get its host
3. analysis host, obtain host Point to the IP Address converted to long type
4. Check IP Whether the address is intranet IP
# With RFC Defined VPC as an example
# If there is a custom private network segment, it should also be added to the forbidden access list
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
127.0.0.0/8
5. request URL
6. If there is a jump , Execute after jump 1, Otherwise, yes URL Initiate request 

1.7 Response output

  • 【 must 】 Set up correctly HTTP Response package type
    • Response package HTTP head “Content-Type” The type of response package must be configured correctly , Prohibition of non HTML The response package of type is set to “text/html”.
  • 【 must 】 Set up safe HTTP Response head

bash

# X-Content-Type-Options
add to “X-Content-Type-Options” Response header and set its value to “nosniff”.
# HttpOnly
Control the user's login authentication Cookie The field should be set to HttpOnly Property to prevent from being XSS Loophole /JavaScript Manipulate the leak .
# X-Frame-Options
Set up X-Frame-Options Response head , And reasonably set the allowable range according to the demand .
This header is used to indicate that the browser prohibits the current page from being displayed in frame、 iframe、embed And so on , So as to avoid the click hijacking problem .
It has three optional values :
DENY: The browser will refuse to load any frame page ;
SAMEORIGIN: be frame The address of the page can only be the page under the same domain name
ALLOW-FROM origin: You can decide Semantic permission frame Page address loaded .
  • 【 must 】 When the external output page contains third-party data, it must be encoded
    • When the response “Content-Type” by “text/html” Type , The response body needs to be encoded

python

# Recommended mozilla Maintenance of bleach Library to filter
import bleach
bleach.clean('an <script>evil()</script> example')
# u'an &lt;script&gt;evil()&lt;/script&gt; example'

1.8 Data output

  • 【 must 】 Encrypted storage of sensitive data
    • Sensitive data should use SHA2RSA And so on
    • Sensitive data should use separate storage tiers , And enable access control in the access layer
    • Temporary files or caches containing sensitive information should be deleted as soon as they are no longer needed
  • 【 must 】 Sensitive information must be desensitized by the background
    • Sensitive information must be desensitized in the background and returned , The interface is forbidden to return sensitive information to the front end / Desensitize the client .
  • 【 must 】 Highly sensitive information must not be stored 、 Exhibition
    • password 、 Secret protection answer 、 Authentication information such as physiological signs shall not be displayed
    • Non financial business , The credit card cvv Codes and logs are forbidden to be stored
  • 【 must 】 Desensitization display of personal sensitive information In the case of meeting business needs , Sensitive personal information needs to be desensitized , Such as :
    • The ID card only displays the first and last characters , Such as 3***************1
    • Mobile phone numbers are hidden in the middle 6 Bit character , Such as 134******48
    • Work address / The home address is displayed up to “ District ” Class A
    • The bank card number only displays the last 4 Bit character , Such as ************8639
  • 【 must 】 Hide background address
    • If the program provides a login background address , The address should be hidden using a random string

python

# Don't do it this way
admin_login_url = "xxxx/login"
# Safety example
admin_login_url = "xxxx/ranD0Str"

1.9 Rights management

  • 【 must 】 Default authentication
    • Unless the resources are completely open to the outside world , Otherwise, the system will perform identity authentication by default ( Use the white list method to release the interfaces or pages that do not need authentication ).
  • 【 must 】 Authorization follows the principle of minimum authority
    • The default user of the program shall not have any operation authority .
  • 【 must 】 Avoid unauthorized access
    • For non-public operations , The current access account should be verified for operation permission ( Common in CMS) And Data permission verification .

bash

1. Verify the login status of the current user
2. Obtain the identity information of the verified current request account from the trusted structure ( Such as session), Prohibit requesting parameters or Cookie To obtain the identity of an external incoming untrusted user and query it directly
3. Verify whether the current user has the operation permission
4. Verify whether the current user has the permission to operate the data
5. Verify whether the current operation account is the expected account 
  • 【 Suggest 】 Clean up unnecessary permissions in time
    • The program should periodically clean up the permissions of non essential users .

1.10 exception handling

  • 【 must 】 No external error prompt
    • Should be used reasonably try/except/finally Handle system exceptions , Avoid error messages being output to the front end .
    • It is forbidden to open the external environment debug Pattern , Or output the program running log to the front end .
  • 【 must 】 It is forbidden to throw sensitive information

2. Flask Security

Use Flask Framework coding is a problem that needs to be considered and considered !

  • 【 must 】 The production environment turns off debugging mode
  • 【 Suggest 】 follow Flask Safety rules
    • Reference resources Flask Safety precautions in the documentation https://flask.palletsprojects.com/en/latest/security/

3. Django Security

Use Django Framework coding is a problem that needs to be considered and considered !

  • 【 must 】 The production environment turns off debugging mode
  • 【 Suggest 】 keep Django The built-in safety feature turns on
    • keep Django The built-in safety feature turns on https://docs.djangoproject.com/en/3.0/topics/security/
    • In the default configuration ,Django The built-in safety features are right XSSCSRFSQL Inject 、 Click hijacking and other types of vulnerabilities can play a better protective effect . Try to avoid turning off these safety features .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved