2018/05/16

Python FTPS client with self-sign certificate and ftplib

About

Example from ftplib should fit perfectly for developers working with a real certificate. In this blog post, I am focusing on coding a FTPS client with self-sign certificate only.

Warning

  • Although I code this example in Python 2.7.14, Python 3.16 is recommended since the poor support on session reuse issue. We will go through this at Hiccup section.

Show me codes

from ftplib import FTP_TLS
import ssl

# Create a SSL context for FTPS object later on
context = ssl.SSLContext(ssl.PROTOCOL_TLS)

# In my example, I would like to force the FTP client to use TLS_V1
# instead of SSLv2 or SSLv3
context.options |= ssl.OP_NO_SSLv2
context.options |= ssl.OP_NO_SSLv3 

# We need to initialize this SSL context with self-sign certificate
# Otherwise, there is SSL handshake errors later on 
context.load_cert_chain(
    "location_of_cert_chain_in_pem", "location_of_keyfile_in_pem")

# Define the CA bundle
context.load_verify_locations(cafile="location_of_ca_bundle_in_pem")


# Instantiate a ftps client object with our context above
ftps = FTP_TLS(host='TARGET_IP', context=context)
# Verbose debug information for testing the implementation 
ftps.set_debuglevel(2) 

# login anonymously before securing control channel
ftps.login()
# Secure the channel
ftps.prot_p()

# Upload the file
with open('TARGET_FILE', 'rb') as fp:
    ftps.storbinary('STOR REMOTE_FILE_PATH', fp)
The first part of implementation focus on how to instantiate a SSLContext, while the 2nd part focus on how to config the FTP client to use our SSLContext, and the 3rd part shows how we can upload a file with this client.

Hiccups

FTPS session reuse

Session reuse is a feature provided by some FTPS server such as vsftpd. However, as stated in this stackoverflow question, ftplib in python 2.7.14 does not support session reuse until python 3.16 (16 May 2018).
In my opinion, there are 2 solutions for developers in python 2.7.14.
The first one is disable session reuse even though there is a security flaw as described in this blog
The second one is replacing ftplib with a system command lftp.

Updated

20180516: curl is not able to reuse the TLS session.

References

沒有留言:

張貼留言