import ssl, socket, time

if __name__ == "__main__":

context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    #context.load_cert_chain(certfile=‘key_pub.pem’, keyfile=‘key_priv.pem')   #可以分开定义公钥和私钥文件,也可以合并成一个文件
    context.load_cert_chain(certfile=’cert.pem')
    
    bindsocket = socket.socket()
    bindsocket.bind(('127.0.0.1', 443))
    bindsocket.listen(5)
    
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    
    try:
        data = connstream.recv(1024)
        print(data)
        buf = 'Hi NN%f\n\n\n\n'%time.time()
        buf = buf.encode()
        connstream.send(buf)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()
        bindsocket.close()

此例没有使用socketserver框架,目的在于测试ssl模块的用法。

继续,用框架实现HTTPS服务

import socketserver, ssl, time
class MyHTTPSHandler_socket(socketserver.BaseRequestHandler):
    def handle(self):
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.load_cert_chain(certfile="cert.pem")
        SSLSocket = context.wrap_socket(self.request, server_side=True)
        self.data = SSLSocket.recv(1024)
        print(self.data)
        buf = 'test HTTPS Server Handler<br>%f'%time.time()
        buf = buf.encode()
        SSLSocket.send(buf)

if __name__ == "__main__":
    port = 443
    httpd = socketserver.TCPServer(('localhost‘, port), MyHTTPSHandler_socket)
    print(’https serving at port', port)
    httpd.serve_forever()

说明:handle()函数负责所有与客户端的通信。客户端连接过来之后,ssl模块载入证书,并用SSLSocket对socket进行封装,屏蔽底层的加密通信细节。

下面再给出HTTPS文件服务器代码,文件访问功能由SimpleHTTPRequestHandler实现,数据加密传输由ssl实现。

import socketserver, ssl, time, http.server
class MyHTTPS_SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def setup(self):
        print('setup')
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.load_cert_chain(certfile=‘cert.pem’)
        SSLSocket = context.wrap_socket(self.request, server_side=True)
        self.rfile = SSLSocket.makefile('rb', self.rbufsize)
        self.wfile = SSLSocket.makefile('wb', self.wbufsize)
        
if __name__ == "__main__":
    port = 443
    httpd = socketserver.TCPServer(("localhost", port), MyHTTPS_SimpleHTTPRequestHandler)
    print('https serving at port', port)
    httpd.serve_forever()

最后,要指出的是setup()和handle()都是在客户端开始连接之后才被调用,从顺序上来说setup()先于handle()。

HTTPS Client in python with SSL Authentication

import ssl, socket

key = mykeyfile
cert = mycertfile
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,keyfile=key,certfile=cert,server_side=False)
ssl_sock.connect(("www.xxx.xxx", 443))
# This is where I call a method the server has exposed
ssl_sock.callServerMethod(arg1,arg2)

How
to do mutual certificate authentication with httplib2

Here's the code my co-worker Dave St. Germain wrote to solve the problem:

import ssl
import socket
from httplib2 import has_timeout
import httplib2
import socks class CertificateValidationError(httplib2.HttpLib2Error):
pass def validating_sever_factory(ca_cert_file):
# we need to define a closure here because we don't control
# the arguments this class is instantiated with
class ValidatingHTTPSConnection(httplib2.HTTPSConnectionWithTimeout): def connect(self):
# begin copypasta from HTTPSConnectionWithTimeout
"Connect to a host on a given (SSL) port." if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
# end copypasta try:
self.sock = ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=ca_cert_file
)
except ssl.SSLError:
# we have to capture the exception here and raise later because
# httplib2 tries to ignore exceptions on connect
import sys
self._exc_info = sys.exc_info()
raise
else:
self._exc_info = None # this might be redundant
server_cert = self.sock.getpeercert()
if not server_cert:
raise CertificateValidationError(repr(server_cert)) def getresponse(self):
if not self._exc_info:
return httplib2.HTTPSConnectionWithTimeout.getresponse(self)
else:
raise self._exc_info[1], None, self._exc_info[2]
return ValidatingHTTPSConnection def do_request(url,
method='GET',
body=None,
headers=None,
keyfile=None,
certfile=None,
ca_certs=None,
proxy_info=None,
timeout=30):
"""
makes an http/https request, with optional client certificate and server
certificate verification.
returns response, content
"""
kwargs = {}
h = httplib2.Http(proxy_info=proxy_info, timeout=timeout)
is_ssl = url.startswith('https')
if is_ssl and ca_certs:
kwargs['connection_type'] = validating_sever_factory(ca_certs) if is_ssl and keyfile and certfile:
h.add_certificate(keyfile, certfile, '')
return h.request(url, method=method, body=body, headers=headers, **kwargs)

perhaps things have changed since your question, I am able to do mutual authentication withhttplib2 v0.7, as below:

import httplib2

h=httplib2.Http(ca_certs='ca.crt')
h.add_certificate(key='client_private_key.pem', cert='cert_client.pem', domain='')
try: resp, cont = h.request('https://mytest.com/cgi-bin/test.cgi')
except Exception as e: print e

ssl
certificate authentication in python

   s = socket.socket()
print "connecting..."
logging.debug("Connecting")
# Connect with SSL mutual authentication
# We only trust our server's CA, and it only trusts user certificates signed by it
c = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_SSLv3, ca_certs='ca.crt',
certfile='user.crt', keyfile='user.key')
c.connect((constants.server_addr, constants.port))
Generally, you've acquired the CA certificate via some out-of-band method, then saved it locally. Linux systems generally have a bundle of certificates for well-known, trusted CAs available under  or similar.
#!/usr/bin/env python

import httplib

CERTFILE = '/home/robr/mycert'
HOSTNAME = 'localhost' conn = httplib.HTTPSConnection(
HOSTNAME,
key_file = CERTFILE,
cert_file = CERTFILE
)
conn.putrequest('GET', '/ssltest/')
conn.endheaders()
response = conn.getresponse()
print response.read()

"mycert" is a PEM formatted certificate file that includes both the public certificate and the private key. If you read the code, you will notice that you can keep the public and private in seperate files if you care to.

SSL authentication generally requires that you set up your own certificate authority. You want to make sure you are the only one giving out keys to your empire.

Apache needs to be set up to require SSL client authentication. In my httpd.conf file I have the following:

SSLCACertificatePath /etc/httpd/conf/ssl.crt SSLCACertificateFile /etc/httpd/conf/ssl.crt/myCA.crt SSLVerifyClient require SSLVerifyDepth 2 SSLRequireSSL

If you have SSLCACertificateFile defined elsewhere in your config file, you'll need to resolve the conflict. It seems that Apache cannot refer to more than one SSLCACertificateFile. Multiple CA certs can exist in one file, but you may not want everyone with certs from all of your accepted CAs access to all of your content.

So why use SSL client authentication? It's a convenient way to do client authentication between web-enabled applications. It's good for SOAP or XML-RPC implementations, or custom apps that communicate via HTTP/HTTPS.

References: http://httpd.apache.org/docs-2.0/ssl/ssl_howto.html http://www.pseudonym.org/ssl/ssl_cook.html

class HTTPSConnection( host[, port, key_file, cert_file]) A subclass of HTTPConnection that uses SSL for communication with secure servers. Default port is 443. key_file is the name of a PEM formatted file that contains your private key. cert_file is a PEM formatted certificate chain file.

Warning: This does not do any certificate verification!

New in version 2.0.

If this doesn't do certificate verification, it seems to be very incomplete. Is there anyway to verify the certs or is this planned in a future release? The article/code snippet should state this defiency.


SSL Client Authentication over HTTPS (Python recipe)

A 16-line python application that demonstrates SSL client authentication over HTTPS. We also explain the basics of how to set up Apache to require
SSL client authentication. This assumes at least Python-2.2 compiled with SSL support, and Apache with mod_ssl



On the server, I'm initializing the SSLContext with my private key, the certfile provided by the CA that I'm loading from the caroot.crt file. Now, when I initialize this with something like node, everything works fine (for example: Setting
up SSL with node.js
). My intentions were to set everything up the same way. My assumption is that during the handshake, the server is providing the client with a CA, just like my node server would. It seems like that's not the case. What am I doing wrong?

If ssl.CERT_REQUIRED isn't used, everything works perfectly, but I'm wanting to validate that the endpoint (server) is who they say they are.

# Server
import socket
import ssl context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile='./path/to/certfile.crt',
keyfile='./path/to/keyfile.pem')
context.load_verify_locations('./path/to/caroot.crt')
context.set_default_verify_paths() server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', 23000))
server_socket.listen(socket.SOMAXCONN) def handle_client(ssl_socket):
data = ssl_socket.read()
while data:
print("%s" % (str(data)))
data = ssl_socket.read() while True:
client_socket, addr = server_socket.accept()
ssl_client_socket = context.wrap_socket(client_socket, server_side=True)
handle_client(ssl_client_socket) # Client
import socket
import ssl context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
# I'm assuming this is not necessary, but I'd like to load the system provided CAs
context.set_default_verify_paths()
# Require CA validation to prevent MITM.
context.verify_mode = ssl.CERT_REQUIRED client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_client = context.wrap_socket(client_socket)
ssl_client.connect(('', 23000))
ssl_client.send(bytes('hello, world!', 'UTF-8'))

As it turns out, my CA provided 3 different crt files. My solution was to append them in a specific order to generate the correct CA chain that was being passed to  For anyone using COMODO as a provider, here is a blog post:http://billpatrianakos.me/blog/2014/04/04/installing-comodo-positive-ssl-certs-on-apache-and-openssl/

Granted, that post is Apache specific, the premise is still the same. The command in question is:

cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt  > yourdomain.com.cer

You then do:

context.load_verify_locations('yourdomain.com.cer')

Everything now works as expected.

创建一个自签名的 SSL 证书

  1. #### 使用 OpenSSL 创建自签名证书
  2. ## 1.创建根证书的私钥
  3. openssl genrsa -out ca.key 1024
  4. ## 2.使用私钥创建根证书
  5. openssl req -new -x509 -days 36500 -key ca.key -out ca.crt
    -subj "/C=CN/ST=Fujian/L=Xiamen/O=Your Company Name/OU=Your Root CA"
  6. ## 3.创建服务器私钥
  7. openssl genrsa -out server.key 1024
  8. ## 4.使用服务器私钥创建证书请求文件
  9. openssl req -new -key server.key -out server.csr -subj "/C=CN/ST=Fujian/L=Xiamen/O=Your Company Name/OU=youwebsite.org/CN=yourwebsite.org"
  10. ## 5.准备工作
  11. mkdir -p demoCA/newcerts
  12. touch demoCA/index.txt
  13. echo '01' > demoCA/serial
  14. ## 6.创建服务器证书并使用ca根证书签名
  15. openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key
  16. ## ---查看不同格式文件的内容命令语法
  17. # openssl rsa -noout -text -in ca.key
  18. # openssl x509 -noout -text -in ca.crt
  19. # openssl rsa -noout -text -in server.key
  20. # openssl req -noout -text -in server.csr
  21. # openssl x509 -noout -text -in server.crt
  22. ## 创建证书最简单方式
  23. # openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.key

python server

  1. import socket, ssl
  2. import time
  3. cacrtf="ca/ca.crt"
  4. crtf="ca/server.crt"
  5. keyf="ca/server.key"
  6. server_sc = socket.socket()
  7. server_sc.bind(('', 10023))
  8. server_sc.listen(5)
  9. newsocket, addr = server_sc.accept()
  10. sc = ssl.wrap_socket(newsocket,
  11. server_side=True,
  12. certfile=crtf,
  13. keyfile=keyf,
  14. ca_certs=cacrtf)
  15. data = sc.read()
  16. print data
  17. sc.write('Back time: ' + str(time.time()))
  18. sc.close()
  19. server_sc.close()

python client

  1. import socket, ssl, pprint
  2. import time
  3. cacrtf="ca/ca.crt"
  4. crtf="ca/server.crt"
  5. keyf="ca/server.key"
  6. socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. ssl_socket = ssl.wrap_socket(socket, ca_certs=cacrtf, cert_reqs=ssl.CERT_REQUIRED)
  8. ssl_socket.connect(('127.0.0.1', 10023))
  9. print repr(ssl_socket.getpeername())
  10. print ssl_socket.cipher()
  11. print pprint.pformat(ssl_socket.getpeercert())
  12. ssl_socket.write("Time: %s\r\n" % time.time())
  13. data = ssl_socket.read()
  14. print data
  15. ssl_socket.close()

python ssl socket 的使用(服务器+客户端)

首先,使用如下命令生成证书和key:

openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout key.pem

接下来实现服务器:

import socket, ssl,time

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")

bindsocket = socket.socket()
bindsocket.bind(('191.8.1.235', 10023))
bindsocket.listen(5)

def do_something(connstream, data):
    #print("data length:",len(data))

return True

def deal_with_client(connstream):
    t_recv=0
    t_send=0
    n = 0
    t1=time.clock()
    data = connstream.recv(1024)
    t2=time.clock()
    print("receive time:",t2-t1)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        n = n + 1
        t1=time.clock()
        connstream.send(b'b'*1024)
        t2=time.clock()
        t_send += t2-t1
        print("send time:",t2-t1)
        t1=time.clock()
        data = connstream.recv(1024)
        t2=time.clock()
        t_recv +=t2-t1
        print("receive time:",t2-t1)
    print("avg send time:",t_send/n,"avg receive time:",t_recv/n)
    # finished with client

while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()

客户端:

import socket, ssl, pprint,time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="cert.pem",
                           cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('191.8.1.235', 10023))

pprint.pprint(ssl_sock.getpeercert())
# note that closing the SSLSocket will also close the underlying socket
n=0
t_send=0
t_recv=0
while n <1000:
    n = n+1
    t1=time.clock()
    ssl_sock.send(b'a'*100)
    t2=time.clock()
    t_send += t2-t1 
    print("send time:",t2-t1)
    t1=time.clock()
    data=ssl_sock.recv(1024)
    t2=time.clock()
    t_recv += t2-t1
    print("receive time:",t2-t1)
    #print(len(data))
print("avg send time:",t_send/n,"avg receive time:",t_recv/n)
#ssl_sock.send(b'')
ssl_sock.close()

网络服务器之HTTPS服务的更多相关文章

  1. backup服务器之rsync服务

    backup服务器之rsync服务   rsync是开源的.快速的.多功能的可实现全量及增量的本地或远程数据同步备份的优秀工具.它拥有scp.cp的全量复制功能,同时比scp.cp命令更优秀.更强大. ...

  2. iredmail邮件服务器之修改默认的web服务端口号

    安装iredmail之后,由于需要在路由器上做端口映射以便在外网访问webmail,因此端口不能和WEB服务的端口好冲突,所以需要修改邮件服务器的httpd服务的端口. 一.apache/httpd的 ...

  3. nginx配置SSL证书实现https服务

    在前面一篇文章中,使用openssl生成了免费证书 后,我们现在使用该证书来实现我们本地node服务的https服务需求.假如我现在node基本架构如下: |----项目 | |--- static ...

  4. Web服务器之iis,apache,tomcat三者之间的比较

    IIS-Apache-Tomcat的区别 IIS与Tomcat的区别 IIS是微软公司的Web服务器.主要支持ASP语言环境. Tomcat是Java Servlet 2.2和JavaServer P ...

  5. 搭建VPN服务器之PPTP

    搭建VPN服务器之PPTP 1. 查看系统是否支持PPP 一般自己的系统支持,VPS需要验证. [root@oldboyedu ~]# cat /dev/ppp cat: /dev/ppp: No s ...

  6. linux下维护服务器之常用命令

    linux下维护服务器之常用命令! 第1套如下: 正则表达式: 1.如何不要文件中的空白行和注释语句: [root@localhost ~]# grep -v '^$' 文件名 |grep -v '^ ...

  7. Nginx设置Https反向代理,指向Docker Gitlab11.3.9 Https服务

    目录 目录 1.GitLab11.3.9的安装 2.域名在阿里云托管,申请免费的1年证书 3.Gitlab 的 https 配置 4.Nginx 配置 https,反向代理指向 Gitlab 配置 目 ...

  8. Web服务器之Nginx详解(操作部分)

    大纲 一.前言 二.Nginx 安装与配置 三.Nginx 配置文件详解 四.Nginx 命令参数 五.配置Nginx提供Web服务 六.配置Nginx的虚拟主机 七.配置Nginx的用户认证 八.配 ...

  9. 阿里云服务器配置免费https服务

    过程总述 购买服务器,购买域名,备案 申请ssl证书 DNS验证 上传证书,配置nginx 很关键,打开端口!!!阿里云的443端口默认是不打开的 1.购买服务器,域名,备案 服务器我是买的阿里云的, ...

随机推荐

  1. iOS之tabBar随tableView的滑动而隐藏/显现

    ` @property(nonatomic,assign)CGFloat historyY; #pragma mark Delegate //设置滑动的判定范围 - (void)scrollViewW ...

  2. 自动换行 lable换行 div换行 span换行 label换行

    label  word-break: break-all; white-space: normal;

  3. MVC 好记星不如烂笔头之 ---> 全局异常捕获以及ACTION捕获

    public class BaseController : Controller { /// <summary> /// Called after the action method is ...

  4. Java整型与字符串相互转换

    >>>>>>>>>>>>>>>>>>>> 1如何将字串 String 转换成整数 ...

  5. 新的篇章--Python

    这周已经开始Python的学习了,感觉Python类似于Powershell, 但又有不同点.在此总结一下新学到的资料: 简单的使用变量的方法: name= input("input you ...

  6. Codeforces Round #375 (Div. 2)

    A. The New Year: Meeting Friends 水 #include <set> #include <map> #include <stack> ...

  7. wpf,离线状态下部分功能不可用。

    离线状态下,设置按钮的不可用.通过改变资源字典的值. App.xaml 文件下添加如下 xmlns:sys="clr-namespace:System;assembly=mscorlib&q ...

  8. 【转】Java内存管理:深入Java内存区域

    转自:http://www.cnblogs.com/gw811/archive/2012/10/18/2730117.html 本文引用自:深入理解Java虚拟机的第2章内容 Java与C++之间有一 ...

  9. 修改Windows Server 2008密码策略,设置简单密码

    最长使用期限为0表示密码永不过期. 如果是VBOX虚拟机安装,在使用共享文件夹功能时候,需要打开控制面板--网络和共享中心--共享设置--启动网络发现.然后才能映射共享文件夹

  10. 提高C#代码质量-规范

    [规范习惯]命名规范1-命名空间 使用<Company>.<Component>2-程序集不必与命名空间同名3-命名空间使用附复数4-避免与FCL的类型重名5-类型名称用名词6 ...