杰瑞科技汇

如何在SUSE系统用Python调用OpenSSL?

Of course! The combination of python, openssl, and SUSE (like openSUSE or SLES) is a common scenario for system administrators and developers. Let's break down how they interact, how to manage them, and common use cases.

如何在SUSE系统用Python调用OpenSSL?-图1
(图片来源网络,侵删)

The Core Relationship: How Python, OpenSSL, and SUSE Connect

  1. OpenSSL (The Foundation): OpenSSL is a robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It's the cryptographic library that provides the fundamental building blocks for secure communication: creating certificates, encrypting data, and verifying identities. On SUSE systems, OpenSSL is a critical, low-level system library.

  2. Python (The User): Python is a high-level programming language. To perform secure network operations (like making HTTPS requests, creating an SSL server, or validating certificates), Python needs a way to "talk" to OpenSSL. It does this through a module.

  3. SUSE (The Platform): The SUSE operating system (openSUSE Tumbleweed, Leap, or SLES) provides the OpenSSL library and the Python interpreter. It's responsible for packaging and managing these components.


Part 1: Managing OpenSSL on SUSE

This is about the system-level OpenSSL, not the Python module.

如何在SUSE系统用Python调用OpenSSL?-图2
(图片来源网络,侵删)

Check the Installed OpenSSL Version

You can check the version of the OpenSSL library provided by your SUSE system.

# This shows the version of the OpenSSL library
openssl version
# This shows more detailed build information
openssl version -a

Install or Update OpenSSL

OpenSSL is a core system package. You should manage it using the standard SUSE package manager, zypper.

# Update all packages, including OpenSSL
sudo zypper update
# If you need to install OpenSSL development headers (for compiling Python from source)
sudo zypper install openssl-devel

⚠️ Important Security Note: Always keep your system's OpenSSL up-to-date to protect against vulnerabilities like Heartbleed or Log4j. The zypper update command is your primary tool for this.


Part 2: Python's Interaction with OpenSSL

Python interacts with OpenSSL in two primary ways:

如何在SUSE系统用Python调用OpenSSL?-图3
(图片来源网络,侵删)
  1. The Standard ssl Module: This is the built-in, recommended way for Python to handle SSL/TLS. It's a wrapper around the system's OpenSSL library.
  2. The cryptography Library: A more modern, powerful, and easier-to-use third-party library that also uses OpenSSL under the hood but provides a much friendlier API.

Method 1: Using the Built-in ssl Module

The ssl module is part of Python's standard library. It directly uses the OpenSSL version installed on your SUSE system.

Example: Making a secure HTTPS request

This code uses urllib.request (which uses the ssl module under the hood) to fetch a URL. It will automatically use the system's trusted certificate store.

import urllib.request
import ssl
# Create a default SSL context, which will use the system's CA certificates
# and verify the server's certificate.
context = ssl.create_default_context()
try:
    # The context is passed to the opener
    with urllib.request.urlopen('https://www.openssl.org', context=context) as response:
        html = response.read()
        print(f"Successfully fetched {len(html)} bytes from OpenSSL.org.")
except urllib.error.URLError as e:
    print(f"An error occurred: {e.reason}")
except ssl.SSLCertVerificationError as e:
    print(f"Certificate verification failed: {e}")

Example: Creating a simple TLS server

This is a more advanced example showing how Python can use OpenSSL to create a server.

import socket
import ssl
import os
# Server configuration
HOST = '0.0.0.0'
PORT = 8443
CERTFILE = 'server.crt'
KEYFILE = 'server.key'
# --- Prerequisites: You need a certificate and key ---
# Generate a self-signed certificate for testing:
# openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes
# Make sure these files are in the same directory as your script.
if not os.path.exists(CERTFILE) or not os.path.exists(KEYFILE):
    print(f"Error: Please generate a certificate ({CERTFILE}) and key ({KEYFILE}).")
    exit(1)
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(5)
print(f"Server listening on {HOST}:{PORT}...")
# Wrap the socket with SSL
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
while True:
    try:
        # Accept a new connection
        client_sock, addr = sock.accept()
        print(f"Connection from {addr}")
        # Wrap the client socket with SSL
        with context.wrap_socket(client_sock, server_side=True) as secure_sock:
            data = secure_sock.recv(1024)
            print(f"Received: {data.decode('utf-8')}")
            secure_sock.sendall(b"Hello from the SUSE Python SSL Server!")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        client_sock.close()

Method 2: Using the cryptography Library (Recommended)

For new projects, the cryptography library is often preferred because its API is cleaner and less error-prone than the low-level ssl module.

First, install it:

# Use pip to install the library
pip install cryptography

Example: Verifying a Certificate with cryptography

This shows how to load a certificate and extract information using the cryptography library, which uses your SUSE system's OpenSSL.

from cryptography import x509
from cryptography.hazmat.backends import default_backend
import datetime
# You can get a server's certificate like this:
# openssl s_client -connect www.openssl.org:443 -showcerts
# Let's load a certificate from a file (or you can fetch one from a socket)
# For this example, let's assume you have 'server.crt' from the previous example.
try:
    with open("server.crt", "rb") as f:
        cert_data = f.read()
    # Parse the certificate
    cert = x509.load_pem_x509_certificate(cert_data, default_backend())
    print("--- Certificate Information ---")
    print(f"Subject: {cert.subject}")
    print(f"Issuer: {cert.issuer}")
    print(f"Serial Number: {cert.serial_number}")
    print(f"Valid From: {cert.not_valid_before_utc}")
    print(f"Valid To: {cert.not_valid_after_utc}")
    print(f"Signature Algorithm: {cert.signature_algorithm_oid._name}")
except FileNotFoundError:
    print("Error: 'server.crt' not found.")
except ValueError as e:
    print(f"Error parsing certificate: {e}")

Part 3: Common Problems and Solutions on SUSE

Problem 1: ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]

This is the most common error. It means Python's ssl module tried to verify a server's certificate but failed. The root cause is almost always that the system's trusted certificate store (on SUSE, located in /etc/ssl/ca-bundle.pem) is missing the necessary Certificate Authority (CA) certificate.

Solution:

  1. Check your system's CA bundle:

    # This file should contain trusted root certificates
    ls -l /etc/ssl/ca-bundle.pem
  2. Install the ca-certificates package: This package provides the most common root certificates and is essential for browsing and secure communication.

    sudo zypper install ca-certificates
  3. For Python-specific issues: Sometimes, especially in virtual environments, the system's certificates aren't found. You can tell Python where to look by setting the REQUESTS_CA_BUNDLE or SSL_CERT_FILE environment variable.

    # Tell Python to use the system's CA bundle
    export SSL_CERT_FILE=/etc/ssl/ca-bundle.pem
    # Or for the 'requests' library
    export REQUESTS_CA_BUNDLE=/etc/ssl/ca-bundle.pem

Problem 2: Python was compiled against a different version of OpenSSL

This happens if you install a Python version from source (e.g., via pyenv) that doesn't match the OpenSSL headers on your SUSE system. You'll see errors like library not found for -lssl or versionOPENSSL_3.0.0' not found`.

Solution:

When compiling Python from source, you must explicitly tell it where to find your SUSE system's OpenSSL.

# First, ensure development headers are installed
sudo zypper install openssl-devel
# Compile Python, pointing it to the correct OpenSSL
# The paths are typical for SUSE systems
./configure --with-openssl=/usr
make
make install

Summary

Component Role on SUSE Key Commands
OpenSSL System cryptographic library. Provides the core TLS/SSL functionality. openssl version, sudo zypper install/update openssl
Python ssl Built-in module. A direct, low-level interface to the system's OpenSSL. import ssl, ssl.create_default_context()
Python cryptography Third-party library. A high-level, user-friendly wrapper around OpenSSL. pip install cryptography, from cryptography import x509
SUSE zypper Package manager. Ensures OpenSSL and its dependencies are correctly installed and updated. sudo zypper install ca-certificates, sudo zypper update
分享:
扫描分享到社交APP
上一篇
下一篇