Connect to secure web servive with pfx certificate using python - python-2.7

Hi i need help to get info from web service on secure site with pfx certificate with password.
i tried more then one example..
code example:
import requests
wsdl_url = 'blabla'
requests.get(wsdl_url, cert='cert.pfx', verify=True)
other example:
import urllib3
import certifi
wsdl_url = 'blabla'
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', # Force certificate check.
ca_certs=certifi.where() # Path to the Certifi bundle.
)
certifi.where()
# You're ready to make verified HTTPS requests.
try:
r = http.request('GET', wsdl_url)
print r
except urllib3.exceptions.SSLError as e:
print "wrong"
# Handle incorrect certificate error.
Error type:
connection aborted
an existing connection was forcibly closed by the remote host
help please

Related

How can I save the SSL keys for https when I use `urllib2`?

I need to save the SSL keys in a file, in order to decrypt the TCP packet via Wireshark later.
What should I do?
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import urllib2
import json
data={}
data_json = json.dumps(data, encoding='UTF-8', ensure_ascii=False)
requrl = "https://52.31.41.56/test" # look, the protocol is https
req = urllib2.Request(url=requrl, data=data_json)
req.add_header('Content-Type', 'application/json')
# how can I record the SSL keys in a file, for Wireshark decryption
rsp_fp = urllib2.urlopen(req)
rsp_data = rsp_fp.read()
print(rsp_data)
Use sslkeylogfile
Example Usage
Use sslkeylog, which is compatible with both Python2 and Python3. I'm modifying your code to save the SSL key logs while making a connection to Stack Overflow.
import urllib2
import sslkeylog
# Save SSL keys to "sslkeylog.txt" in this directory
# Note that you only have to do this once while this is in scope
sslkeylog.set_keylog("sslkeylog.txt")
# Make an HTTPS connection to Stack Overflow
requrl = "https://stackoverflow.com"
req = urllib2.Request(url=requrl)
rsp_fp = urllib2.urlopen(req)
Verification
Then if we check sslkeylog.txt, we can see that there is now an entry:
bash$ cat sslkeylogfile.txt
CLIENT_RANDOM a655a2e200ddc96c1571fe29af1962013ccbab1b9e9b865db112a9c1492c449a 3280c9fbee32df623074f80519f278420971aaa6eb91ab0f1f973d505a03ddbcc4fba2ca83f6d733addebdb0358e606d

Urllib2 through proxy and trust untrusted SSL certificates

I've read the various posts such as:
urllib2 won't use my proxy
https://stackoverflow.com/a/11130306/413180
python ignore certificate validation urllib2
https://stackoverflow.com/a/1450154/413180
etc, etc, however, nothing will work for me. I want to proxy everything through my intercepting proxy (Burp Suite Pro), so I can see and edit the requests my Python 2 script makes, but I don't want it to error on the Burp CA cert being invalid. My code:
proxy={'http': '127.0.0.1:8081', 'https': '127.0.0.1:8081'}
proxy_handler = urllib2.ProxyHandler(proxy)
opener = urllib2.build_opener(proxy_handler)
context = ssl._create_unverified_context()
opener.context = context
urllib2.install_opener(opener)
url_request = urllib2.Request("https://example.com")
response = opener.open(url_request)
Also tried
import ssl
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
I've also tried copying the Burp cacert.der file to /etc/pki/ca-trust/source/anchors/ and running update-ca-trust. All give the error
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)>

How to ignore SSL certificate validation in pysimplesoap

I'm trying to access a web service that uses a self-generated certificate using pysimplesoap and python 2.7.9
from pysimplesoap.client import SoapClient
import base64
username = 'webuser'
password = 'webpassword'
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
# real address / login removed
client = SoapClient(wsdl='https://url:port/webservice.asmx?WSDL',
http_headers={'Authorization': 'Basic %s'%base64string}, sessions=True,
cacert=None)
response = client.StatusInfo(... removed ...)
print(response)
Trying this throws the error message
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
There are tips on how to bypass the problem by fixing urllib2, but is there a simpler way that allows me to tell pysimplesoap to ignore all SSL certificate client side errors. I'm using Windows7 and plan to port the code to a Raspian/Debian Linux, so a solution should not depend on the operating system.
Answering my own question here,
adding the 1st & 3rd line will ignore certification verification
import ssl
from pysimplesoap.client import SoapClient
ssl._create_default_https_context = ssl._create_unverified_context
There's a longer discussion about this here where you can learn why this is not a good idea...

build_opener vs. urlopen for self-signed SSL cert

I'm trying to get the opener in urllib to work with a self-signed SSL cert in Python 2.7.9. It works perfectly with simple, direct urlopen, like so:
import urllib2
req = urllib2.Request('https://myurl.com')
r = urllib2.urlopen(req,cafile='/my/certs.pem')
r.read()
... But when I use (what I think is) effectively the same thing setting a handler instead ...
import ssl
import urllib2
s = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
s.load_verify_locations(cafile='/my/certs.pem')
sh = urllib2.HTTPSHandler(s)
o = urllib2.build_opener(sh)
r = o.open('https://myurl.com')
r.read()
... I get an error on the cert:
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
EDIT: I've simplified my example for the purposes of the question, but I need to use the second version, because I need to add another handler (for digest authentication) before opening the connection. So, if there's an alternative option for using self-signed certs with digest authentication, I'm all ears!
Been a while since I've been on here ... Thanks in advance for your help.

How can I create https connection on python 2.7?

The situation
I'm trying to connect to a server on https protocol with python script. Could someone give me the working example that sends a GET request to https server, or web resource to how to create https connection with python?
An attempt so far
I have learned that the module httplib on python supports creation of http connection, but not https connection?
import httplib
conn = httplib.HTTPConnection('https://adsche.skplanet.com/api/startNewTurn')
header = {"Content-type" : "application/json"}
conn.request('GET', '/announce?info_hash=%da', '', header)
r1 = conn.getresponse()
print r1.status, r1.reason
data1 = r1.read()
print data1