py3 changes

py3_forced
idziubenko 3 years ago
parent cdf5b87807
commit 6b83135f72

5
.gitignore vendored

@ -0,0 +1,5 @@
revert_changes_to_vmachine
push_to_vmachine*
.vscode
*.pyc
*.pyo

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org

@ -15,6 +15,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import socket
import sys, pwd, os
import random, string, datetime
@ -63,7 +64,7 @@ def start():
passwd_list = []
error_num = 0
print 'password daemon start'
print('password daemon start')
time_last = datetime.datetime.now()
find_flag = False
while 1:
@ -73,7 +74,7 @@ def start():
fd = open(file_path, 'w')
fd.write("%d %s" %(port, hash_val))
fd.close()
os.chmod(file_path, 0600)
os.chmod(file_path, 0o600)
if error_num:
return 1
@ -82,10 +83,10 @@ def start():
try:
client, address = s.accept()
except KeyboardInterrupt:
print
print()
return 1
print "server: got connection from %s port %d" \
%(address[0], address[1])
print("server: got connection from %s port %d" \
%(address[0], address[1]))
# получаем данные от клиента с размером size=1024
data = client.recv(size)
@ -102,7 +103,7 @@ def start():
if hash_val != userhash:
error_msg = 'Error: incorrect hash'
print error_msg
print(error_msg)
client.send(error_msg)
error_num += 1
break
@ -119,7 +120,7 @@ def start():
find_flag = False
break
error_msg = 'Error: password not found'
print error_msg
print(error_msg)
client.send(error_msg)
msg = client.recv(size)
@ -132,7 +133,7 @@ def start():
break
if r_host != s_host or r_port != s_port:
error_msg = 'Error: mismatch destination hosts'
print error_msg
print(error_msg)
client.send(error_msg)
data = ''
break
@ -147,7 +148,7 @@ def start():
delete, s_host, s_port, username, userhash = data.split(',')
if hash_val != userhash:
error_msg = 'Error: incorrect hash'
print error_msg
print(error_msg)
client.send(error_msg)
error_num += 1
break
@ -162,7 +163,7 @@ def start():
break
else:
error_msg = 'Error: incorrect data'
print error_msg
print(error_msg)
client.send(error_msg)
error_num += 1
break
@ -173,7 +174,7 @@ def stop():
username = pwd.getpwuid(os.getuid()).pw_name
for run_commands in filter(lambda x:'cl-consoled' in \
x[0],getRunProc()):
x[0], getRunProc()):
if 'python' in run_commands[0]:
if username == owner(run_commands[1]) and \
str(os.getpid()) != run_commands[1]:
@ -186,7 +187,7 @@ if __name__=='__main__':
stop()
if not args.stop:
while True:
print 'start'
print('start')
res = start()
if res != 408:
sys.exit(res)

@ -14,19 +14,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from __future__ import absolute_import
import os
import pwd
import sys
import subprocess
import socket
import time
import urllib2
import urllib.request as urllib2
from urllib.error import URLError
from calculate.console.application.function import _print
from function import get_ip_mac_type
from .function import get_ip_mac_type
import OpenSSL
import hashlib
from client_class import HTTPSClientCertTransport
from cert_verify import VerifyError
from .client_class import HTTPSClientCertTransport
from .cert_verify import VerifyError
from calculate.core.datavars import DataVarsCore
from calculate.core.server.methods_func import get_password
from calculate.lib.cl_lang import setLocalTranslate
@ -48,32 +51,32 @@ def client_post_cert(client, clVars, show_info=False):
result_sid = _result_sid[1].integer
if os.environ.get("DEBUG"):
print _("The client uses certificate {certfile} "
print(_("The client uses certificate {certfile} "
"(server ID {cert_id})").format(
certfile=client.CERT_FILE, cert_id=result_post_cert[0])
certfile=client.CERT_FILE, cert_id=result_post_cert[0]))
if result_post_cert[0] == -4:
print _("Certificate not found on the server")
print _("the client uses certificate %s") % client.CERT_FILE
print _('You can generate a new certificate '
print(_("Certificate not found on the server"))
print(_("the client uses certificate %s") % client.CERT_FILE)
print(_('You can generate a new certificate '
'using options --gen-cert-by and '
'--get-cert-from')
'--get-cert-from'))
raise Exception(3)
# client_sid(sid, client, cert_id = results[0][0], clVars = clVars)
if result_post_cert[0] == -3:
print _("Certificate not sent!")
print(_("Certificate not sent!"))
elif result_post_cert[0] == -2:
print _("Using the upstream certificate")
print(_("Using the upstream certificate"))
else:
if show_info:
print _(" Your certifitate ID = %d") % (result_post_cert[0])
print(_(" Your certifitate ID = %d") % (result_post_cert[0]))
try:
if result_post_cert[1] == -2:
print _("The certificate has expired")
print(_("The certificate has expired"))
elif result_post_cert[1] > 0:
if show_info:
print _("The certificate expires after %d days") % (
result_post_cert[1])
print(_("The certificate expires after %d days") % (
result_post_cert[1]))
except:
pass
@ -82,16 +85,16 @@ def client_post_cert(client, clVars, show_info=False):
if show_info:
if result_sid[1] == 1:
print _(" New Session")
print(_(" New Session"))
else:
print _(" Old Session")
print _(" Your session ID = %s") % sid
print(_(" Old Session"))
print(_(" Your session ID = %s") % sid)
# Creation of secret key of the client
def new_key_req(key, cert_path, server_host_name, private_key_passwd=None,
auto=False):
from create_cert import generateRSAKey, makePKey, makeRequest, \
from .create_cert import generateRSAKey, makePKey, makeRequest, \
passphrase_callback
rsa = generateRSAKey()
@ -114,11 +117,11 @@ def new_key_req(key, cert_path, server_host_name, private_key_passwd=None,
user_name = pwd.getpwuid(os.getuid()).pw_name
try:
pwdObj = pwd.getpwnam(user_name)
except KeyError, e:
except KeyError as e:
_print(e)
return None
os.chown(key, pwdObj.pw_uid, pwdObj.pw_gid)
os.chmod(key, 0600)
os.chmod(key, 0o600)
return req_file
@ -129,14 +132,13 @@ def delete_old_cert(client):
os.unlink(client.REQ_FILE)
os.unlink(client.PKEY_FILE)
os.unlink(client.PubKEY_FILE)
except OSError, e:
except OSError as e:
_print(e.message)
def client_post_request(cert_path, args):
if os.path.exists(cert_path + 'req_id'):
print \
_("You already sent a certificate signature request.")
print(_("You already sent a certificate signature request."))
_print(_("Request ID = %s") % readFile(cert_path + 'req_id'))
ans = raw_input(_("Send a new request? y/[n]: "))
if not ans.lower() in ['y', 'yes']:
@ -148,14 +150,14 @@ def client_post_request(cert_path, args):
port = args.port or clVars.Get('core.cl_core_port')
url = "https://%s:%s/?wsdl" % (args.by_host, port)
print '%s\n' % url, _("connecting...")
from client_class import Client_suds
print('%s\n' % url, _("connecting..."))
from .client_class import Client_suds
try:
client = Client_suds(url, transport=HTTPSClientCertTransport \
(None, None, cert_path))
except (KeyboardInterrupt, urllib2.URLError), e:
print '\n' + _("Closing. Connection error.")
except (KeyboardInterrupt, URLError) as e:
print('\n' + _("Closing. Connection error."))
_print(_("Error: %s") % e)
return 0
client.wsdl.services[0].setlocation(url)
@ -165,7 +167,7 @@ def client_post_request(cert_path, args):
key = os.path.join(cert_path, server_host_name + '.key')
csr_file = os.path.join(cert_path, server_host_name + '.csr')
if os.path.exists(key) and os.path.exists(csr_file):
print _("the private key and request now exist")
print(_("the private key and request now exist"))
ask = raw_input(_("Create a new private key and request? y/[n]: "))
if ask.lower() in ['y', 'yes']:
passwd = get_password()
@ -181,7 +183,7 @@ def client_post_request(cert_path, args):
res = client.service.post_client_request(request=data, ip=ip,
mac=mac, client_type=client_type)
if int(res) < 0:
print _("The server has not signed the certificate!")
print(_("The server has not signed the certificate!"))
return 1
fc = open(os.path.join(cert_path, 'req_id'), 'w')
fc.write(res)
@ -198,8 +200,8 @@ def client_get_cert(cert_path, args):
clVars.flIniFile()
if not os.path.exists(os.path.join(cert_path, 'req_id')):
print _("Request not sent or file %s deleted") \
% (os.path.join(cert_path, 'req_id'))
print(_("Request not sent or file %s deleted") \
% (os.path.join(cert_path, 'req_id')))
return 1
fc = open(os.path.join(cert_path, 'req_id'), 'r')
req_id = fc.read()
@ -207,24 +209,24 @@ def client_get_cert(cert_path, args):
port = args.port or clVars.Get('core.cl_core_port')
url = "https://%s:%s/?wsdl" % (args.from_host, port)
print '%s\n' % url, _("connecting...")
print('%s\n' % url, _("connecting..."))
from client_class import Client_suds
from .client_class import Client_suds
try:
client = Client_suds(url,
transport=HTTPSClientCertTransport(None, None,
cert_path))
except KeyboardInterrupt:
print _("Closing. Connection error.")
print(_("Closing. Connection error."))
return 1
client.wsdl.services[0].setlocation(url)
server_host_name = client.service.get_server_host_name()
if not os.path.exists(os.path.join(cert_path, server_host_name + '.csr')):
print _("Request %s not found on the client's side") \
% (os.path.join(cert_path, server_host_name + '.csr'))
print(_("Request %s not found on the client's side") \
% (os.path.join(cert_path, server_host_name + '.csr')))
return 1
request = readFile(os.path.join(cert_path, server_host_name + '.csr'))
md5 = hashlib.md5()
@ -238,19 +240,19 @@ def client_get_cert(cert_path, args):
except IndexError:
ca_root = None
if cert == '1':
print _("Signature request rejected!")
print(_("Signature request rejected!"))
return 1
elif cert == '2':
print _("Signature request not examined yet.")
print _("Your request ID = %s") % req_id + '.\n', \
print(_("Signature request not examined yet."))
print(_("Your request ID = %s") % req_id + '.\n', \
_("To submit the certificate request on the server use command") + \
'\n' + 'cl-core --sign-client ID_CLIENT_REQUEST'
'\n' + 'cl-core --sign-client ID_CLIENT_REQUEST')
return 1
elif cert == '3':
print _("Request or signature not matching earlier data.")
print(_("Request or signature not matching earlier data."))
return 1
elif cert == '4':
print _("The request was sent from another IP.")
print(_("The request was sent from another IP."))
return 1
cert_file = os.path.join(cert_path, server_host_name + '.crt')
fc = open(cert_file, 'w')
@ -258,17 +260,17 @@ def client_get_cert(cert_path, args):
fc.close()
try:
os.unlink(cert_path + 'req_id')
except OSError, e:
except OSError as e:
_print(e.message)
print _('Certificate saved. Your certificate ID: %s') % req_id
print(_('Certificate saved. Your certificate ID: %s') % req_id)
user_name = pwd.getpwuid(os.getuid()).pw_name
try:
pwdObj = pwd.getpwnam(user_name)
except KeyError, e:
except KeyError as e:
_print(e)
return None
os.chown(cert_file, pwdObj.pw_uid, pwdObj.pw_gid)
os.chmod(cert_file, 0600)
os.chmod(cert_file, 0o600)
if ca_root:
system_ca_db = clVars.Get('core.cl_glob_root_cert')
@ -285,8 +287,8 @@ def client_get_cert(cert_path, args):
md5 = hashlib.md5()
md5.update(ca_root)
md5sum = md5.hexdigest()
print "\n================================================="
print "md5sum = ", md5sum
print("\n=================================================")
print("md5sum = ", md5sum)
if not os.path.exists(root_cert_md5):
fc = open(root_cert_md5, "w")
@ -314,7 +316,7 @@ def client_get_cert(cert_path, args):
fc.close()
if not filename:
print _('Field "CN" not found in the certificate!')
print(_('Field "CN" not found in the certificate!'))
return 1
fd = open(os.path.join(cl_client_cert_dir, 'ca', filename), 'w')
@ -326,10 +328,10 @@ def client_get_cert(cert_path, args):
fa = open(user_root_cert, 'a')
fa.write(ca_root)
fa.close()
print _("filename = "), filename
print _("Certificate added")
print(_("filename = "), filename)
print(_("Certificate added"))
else:
print _("The file containing the CA certificate now exists")
print(_("The file containing the CA certificate now exists"))
return 0
@ -342,12 +344,12 @@ def client_post_auth(client):
pass # client_post_cert(client)
else:
# client_post_request(client)
print _(
"You do not have a certificate. Use option --gen-cert-by HOST to generate a new request or --get-cert-from HOST to get a new certificate from the server.")
print(_(
"You do not have a certificate. Use option --gen-cert-by HOST to generate a new request or --get-cert-from HOST to get a new certificate from the server."))
raise Exception(1)
# print client.service.versions(sid, VERSION)
except VerifyError, e:
print e.value
except VerifyError as e:
print(e.value)
raise Exception(1)
@ -367,8 +369,8 @@ def getRunProc():
if not os.access('/proc', os.R_OK):
return []
return map(getCmd,
filter(lambda x: x.isdigit(),
listDirectory('/proc')))
list(filter(lambda x: x.isdigit(),
listDirectory('/proc'))))
def owner(pid):
@ -399,7 +401,7 @@ def create_socket(file_path, username):
if not find_proc:
try:
os.unlink(file_path)
except OSError, e:
except OSError as e:
_print(e.message)
cmd = ['cl-consoled']

@ -14,6 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from __future__ import absolute_import
import os
import re
import sys
@ -57,12 +59,12 @@ def verify(server_cert, crl_path, flag):
host = L.split(':')[0]
except:
if not flag:
print _("fields CN and L in the CA certificate are incorrect!")
print(_("fields CN and L in the CA certificate are incorrect!"))
return 0
crl_file = crl_path + host
else:
if not flag:
print _("fields CN and L in the CA certificate are incorrect!")
print(_("fields CN and L in the CA certificate are incorrect!"))
return 0
if not os.path.exists(crl_file):
@ -82,16 +84,16 @@ def verify(server_cert, crl_path, flag):
for rvk in revoked_objects:
if serverSerial == int(rvk.get_serial(), 16):
print _("This certificate has been revoked!")
print _("Serial") + _(': %s\n') % rvk.get_serial() + _(
"Revoke date") + _(': %s') % rvk.get_rev_date()
print(_("This certificate has been revoked!"))
print(_("Serial") + _(': %s\n') % rvk.get_serial() + _(
"Revoke date") + _(': %s') % rvk.get_rev_date())
raise VerifyError('CRL Exception')
return 0
def get_CRL(path_to_cert):
print 'update CRL'
print('update CRL')
""" get new CRL (Certificate Revocation List) from all CA """
# local CRL
CRL_path = os.path.join(path_to_cert, 'ca/crl/')
@ -101,13 +103,13 @@ def get_CRL(path_to_cert):
try:
os.makedirs(path_to_cert)
except OSError:
print _("Failed to create directory %s") % path_to_cert
print(_("Failed to create directory %s") % path_to_cert)
raise Exception(1)
try:
os.makedirs(os.path.join(path_to_cert, 'ca'))
except OSError:
print _("Failed to create directory %s") % (
os.path.join(path_to_cert, 'ca'))
print(_("Failed to create directory %s") % (
os.path.join(path_to_cert, 'ca')))
raise Exception(1)
os.makedirs(CRL_path)
@ -153,8 +155,8 @@ def get_CRL(path_to_cert):
if url:
new_crl = None
from client_class import Client_suds
from client_class import HTTPSClientCertTransport
from .client_class import Client_suds
from .client_class import HTTPSClientCertTransport
# connect to ca server (url get from certificates)
client = None
try:
@ -164,7 +166,7 @@ def get_CRL(path_to_cert):
client.set_parameters(path_to_cert, None, None, None)
new_crl = client.service.get_crl()
except VerifyError, e:
except VerifyError as e:
_print(e.value)
# rm_ca_from_trusted(ca)
raise Exception(1)
@ -188,7 +190,7 @@ def get_CRL(path_to_cert):
with open(CRL_file, 'w') as fd:
fd.write(new_crl)
print _("CRL added")
print(_("CRL added"))
find_ca_in_crl(CRL_path, all_ca_certs_list)
@ -260,7 +262,7 @@ def rm_ca_from_trusted(ca_cert):
if ca_cert == readFile(filename):
try:
os.unlink(filename)
except OSError, e:
except OSError as e:
_print(e.message)
else:
newfile += (line + '\n')
@ -284,8 +286,8 @@ def rm_ca_from_trusted(ca_cert):
if ca_cert != cert:
new_user_ca_certs.append(cert)
else:
print _("CA certificate deleted from the list of user "
"trusted certificates")
print(_("CA certificate deleted from the list of user "
"trusted certificates"))
fd = open(user_ca_db, 'w')
for cert in new_user_ca_certs:
@ -304,8 +306,8 @@ def rm_ca_from_trusted(ca_cert):
if ca_cert != cert:
new_system_ca_certs.append(cert)
else:
print _("CA certificate deleted from the list of system "
"trusted certificates")
print(_("CA certificate deleted from the list of system "
"trusted certificates"))
fd = open(system_ca_db, 'w')
for cert in new_system_ca_certs:

@ -13,33 +13,36 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from __future__ import absolute_import
from calculate.core.server.local_call import Display, Methods, has_force_arg
from calculate.lib.utils.tools import unpack_single_opts
import calculate.contrib
from suds import WebFault
from suds.transport import TransportError
from client_class import Client_suds
from .client_class import Client_suds
import traceback as tb
import time
import logging
import os
import sys
import threading
import urllib2
from pid_information import client_list_methods
from cert_func import (client_post_auth, client_post_request, client_get_cert,
import urllib.request as urllib2
from urllib.error import URLError
from .pid_information import client_list_methods
from .cert_func import (client_post_auth, client_post_request, client_get_cert,
client_post_cert, get_password_from_daemon,
clear_password)
from sid_func import session_clean, client_session_info, client_session_list
from cert_verify import get_CRL, VerifyError
from .sid_func import session_clean, client_session_info, client_session_list
from .cert_verify import get_CRL, VerifyError
import M2Crypto
import OpenSSL
from calculate.core.datavars import DataVarsCore
from client_class import HTTPSClientCertTransport
from methods_func import call_method, get_method_argparser, parse, get_view
from function import (MessageReceiver, MessageDispatcher, clear, _print,
from .client_class import HTTPSClientCertTransport
from .methods_func import call_method, get_method_argparser, parse, get_view
from .function import (MessageReceiver, MessageDispatcher, clear, _print,
get_view_params)
from calculate.lib.utils.files import makeDirectory, readLinesFile
from calculate.lib.cl_lang import setLocalTranslate
@ -70,7 +73,7 @@ def client_signal(client):
try:
client.service.active_client(sid)
except:
print _('no connection to the server!')
print(_('no connection to the server!'))
raise Exception(1)
time.sleep(float(client_active))
@ -78,7 +81,7 @@ def client_signal(client):
class StoppableThread(threading.Thread):
def __init__(self):
super(StoppableThread, self).__init__()
self._stop = threading.Event()
self._thread_stopped = threading.Event()
self._pause = threading.Event()
self._paused = threading.Event()
@ -107,10 +110,10 @@ class StoppableThread(threading.Thread):
self._pause.clear()
def stop(self):
self._stop.set()
self._thread_stopped.set()
def stopped(self):
return self._stop.isSet()
return self._thread_stopped.isSet()
def paused(self):
return self._pause.isSet()
@ -141,7 +144,7 @@ def connect_with_cert(cert, path_to_cert, url, args, wait_thread, clVarsCore,
url, transport=HTTPSClientCertTransport(
CERT_KEY, CERT_FILE, path_to_cert, password=key_passwd,
ca_certs=ca_certs, wait_thread=wait_thread))
if not wait_thread.isAlive():
if not wait_thread.is_alive():
wait_thread = StoppableThread()
flag_thread_start = True
wait_thread.start()
@ -150,14 +153,14 @@ def connect_with_cert(cert, path_to_cert, url, args, wait_thread, clVarsCore,
wait_thread.stop()
client_post_cert(client, clVarsCore)
Connect_Error = 0
except VerifyError, e:
except VerifyError as e:
Connect_Error = 1
er = e
except OpenSSL.crypto.Error, e:
except OpenSSL.crypto.Error as e:
Connect_Error = 1
crypto_Error = 1
er = e
except urllib2.URLError, e:
except URLError as e:
Connect_Error = 1
er = e
except Exception as e:
@ -205,8 +208,8 @@ def add_server_hostname(host, path_to_cert, server_hostname):
fd.write(temp_file)
fd.close()
return True
except Exception, e:
print e
except Exception as e:
print(e)
return False
@ -233,7 +236,7 @@ def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
return 0
if args.pid_res == "list":
from pid_information import client_pid_info
from .pid_information import client_pid_info
wait_thread.stop()
client_pid_info(client, wait_thread)
return 0
@ -246,7 +249,7 @@ def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
if args.pid_res:
wait_thread.stop()
if not args.pid_res.isdigit():
print _("Wrong PID")
print(_("Wrong PID"))
return 1
mr = get_entire_message_receiver(client, int(args.pid_res))
if mr:
@ -259,7 +262,7 @@ def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
if args.pid_kill:
wait_thread.stop()
from pid_information import client_pid_kill
from .pid_information import client_pid_kill
return client_pid_kill(client, args.pid_kill)
@ -306,24 +309,24 @@ def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
try:
mr.analysis(method_result)
# analysis(client, client.sid, method_result)
except urllib2.URLError, e:
except URLError as e:
_print(e)
except KeyboardInterrupt:
try:
print
print()
mess = method_result[0][0]
pid = int(mess.message)
result = client.service.pid_kill(pid, client.sid)
if result in [0, 2]:
print _('Process terminated')
print(_('Process terminated'))
elif result == -1:
print _("Certificate not found on the server")
print(_("Certificate not found on the server"))
elif result == -2:
print _("Session not matching your certificate")
print(_("Session not matching your certificate"))
elif result == 1:
print _("Failed to terminate the process")
print(_("Failed to terminate the process"))
mr.analysis(method_result)
except Exception, e:
except Exception as e:
_print(e.message)
try:
@ -397,6 +400,7 @@ def main(wait_thread):
port = args.port or clVarsCore.GetInteger('core.cl_core_port')
host = args.host
path_to_cert = args.path_to_cert
if not path_to_cert:
path_to_cert = clVarsCore.Get('core.cl_client_cert_dir')
path_to_cert = path_to_cert.replace("~", homePath)
@ -408,7 +412,7 @@ def main(wait_thread):
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
print _("Failed to create directory %s") % dir_path
print(_("Failed to create directory %s") % dir_path)
return 1
if args.update_crl:
@ -416,7 +420,7 @@ def main(wait_thread):
getCRL = threading.Thread(target=get_CRL, args=(path_to_cert,))
getCRL.start()
getCRL.join()
print 'CRL updated'
print('CRL updated')
return 0
if args.by_host:
@ -429,7 +433,7 @@ def main(wait_thread):
return 0
url = "https://%s:%s/?wsdl" % (host, port)
try:
from calculate.lib.utils.dbus_tools import run_dbus_core
run_dbus_core(host, port)
@ -440,6 +444,7 @@ def main(wait_thread):
serv_hostname = get_server_hostname(host, path_to_cert)
get_name_flag = False
client = None
if serv_hostname:
Connect_Error = 1
crypto_Error = 0
@ -447,7 +452,7 @@ def main(wait_thread):
connect_with_cert(serv_hostname, path_to_cert, url, args,
wait_thread, clVarsCore, crypto_Error,
Connect_Error)
if not wait_thread.isAlive():
if not wait_thread.is_alive():
wait_thread = StoppableThread()
wait_thread.start()
get_name_flag = True
@ -456,13 +461,13 @@ def main(wait_thread):
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
print _('Invalid password')
print(_('Invalid password'))
# delete password from daemon list
clear_password(host, port)
elif e:
wait_thread.stop()
if type(e.message) != int:
print _('Error: '), e
print(_('Error: '), e)
get_name_flag = False
if get_name_flag:
@ -473,33 +478,33 @@ def main(wait_thread):
try:
return_val = https_server(client, args, unknown_args, url,
clVarsCore, wait_thread)
except urllib2.URLError, e:
print _('Error: '), e
except URLError as e:
print(_('Error: '), e)
except KeyboardInterrupt:
wait_thread.stop()
red = '\n' + '\033[31m * \033[0m'
print red + _("Manually interrupted")
except Exception, e:
print(red + _("Manually interrupted"))
except Exception as e:
wait_thread.stop()
if type(e.message) != int:
if e.message:
print e.message
print(e.message)
elif e.args:
print e
print(e)
return 1
wait_thread.stop()
return return_val
except WebFault, f:
print _("Exception: %s") % f
except WebFault as f:
print(_("Exception: %s") % f)
_print(f.fault)
except TransportError, te:
print _("Exception: %s") % te
except TransportError as te:
print(_("Exception: %s") % te)
except KeyboardInterrupt:
wait_thread.stop()
red = '\n' + '\033[31m * \033[0m'
print red + _("Manually interrupted")
except Exception, e:
print _("Exception: %s") % e
print(red + _("Manually interrupted"))
except Exception as e:
print(_("Exception: %s") % e)
tb.print_exc()
wait_thread.stop()
@ -510,16 +515,16 @@ def main(wait_thread):
client.wsdl.services[0].setlocation(url)
server_host_name = client.service.get_server_host_name()
if not add_server_hostname(host, path_to_cert, server_host_name):
print 'compliance_file write error!'
print('compliance_file write error!')
del client
except urllib2.URLError, e:
except URLError as e:
wait_thread.stop()
print '\b' + _('Failed to connect') + ':', e
print('\b' + _('Failed to connect') + ':', e)
return 1
except KeyboardInterrupt:
wait_thread.stop()
red = '\n' + '\033[31m * \033[0m'
print red + _("Manually interrupted")
print(red + _("Manually interrupted"))
try:
import glob
@ -543,7 +548,7 @@ def main(wait_thread):
connect_with_cert(cert_name, path_to_cert, url, args,
wait_thread, clVarsCore, crypto_Error,
Connect_Error)
if not wait_thread.isAlive():
if not wait_thread.is_alive():
wait_thread = StoppableThread()
wait_thread.start()
@ -556,14 +561,14 @@ def main(wait_thread):
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
print _('Invalid password')
print(_('Invalid password'))
# delete password from daemon list
clear_password(host, port)
return 1
elif e:
wait_thread.stop()
if type(e.message) != int:
print _('Error: '), e
print(_('Error: '), e)
return 1
CERT_FILE = None
@ -579,34 +584,34 @@ def main(wait_thread):
try:
return_val = https_server(client, args, unknown_args, url,
clVarsCore, wait_thread)
except urllib2.URLError, e:
print _('Error: '), e
except URLError as e:
print(_('Error: '), e)
except KeyboardInterrupt:
wait_thread.stop()
red = '\n' + '\033[31m * \033[0m'
print red + _("Manually interrupted")
except Exception, e:
print(red + _("Manually interrupted"))
except Exception as e:
wait_thread.stop()
if type(e.message) != int:
if e.message:
print e.message
print(e.message)
elif e.args:
print e
print(e)
# tb.print_exc()
return 1
wait_thread.stop()
return return_val
# ----------------------------------------------------
except WebFault, f:
print _("Exception: %s") % f
except WebFault as f:
print(_("Exception: %s") % f)
_print(f.fault)
except TransportError, te:
print _("Exception: %s") % te
except TransportError as te:
print(_("Exception: %s") % te)
except KeyboardInterrupt:
wait_thread.stop()
red = '\n' + '\033[31m * \033[0m'
print red + _("Manually interrupted")
except Exception, e:
print _("Exception: %s") % e
print(red + _("Manually interrupted"))
except Exception as e:
print(_("Exception: %s") % e)
tb.print_exc()
wait_thread.stop()

@ -14,8 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import urllib2 as u2
import urllib.request as u2
if hasattr(u2, "ssl"):
u2.ssl._create_default_https_context = u2.ssl._create_unverified_context
import os
@ -25,23 +24,18 @@ import ssl
import OpenSSL
import hashlib
import M2Crypto
import calculate.contrib
from calculate.core.datavars import DataVarsCore
from calculate.lib.datavars import DataVars
import calculate.contrib
from suds.client import Client
from cert_verify import verify, get_CRL
import httplib
from .cert_verify import verify, get_CRL
import http.client as httplib
from suds.transport.http import HttpTransport
try:
from pyopenssl_wrapper import PyOpenSSLSocket
except ImportError:
PYOPENSSL_AVAILABLE = False
else:
PYOPENSSL_AVAILABLE = True
from .pyopenssl_wrapper import PyOpenSSLSocket
from suds.transport import Transport
from suds.properties import Unskin
from cookielib import CookieJar, DefaultCookiePolicy
from http.cookiejar import CookieJar, DefaultCookiePolicy
from logging import getLogger
from calculate.console.datavars import DataVarsConsole
from calculate.lib.cl_lang import setLocalTranslate
@ -80,94 +74,58 @@ class SUDSHTTPRedirectHandler(u2.HTTPRedirectHandler):
else:
raise u2.HTTPError(req.get_full_url(), code, msg, headers, fp)
class MyHTTPResponse(httplib.HTTPResponse):
def __init__(self, sock, debuglevel=0, strict=0, method=None):
httplib.HTTPResponse.__init__(self, sock, debuglevel, strict, method)
class CheckingHTTPSConnection(httplib.HTTPSConnection):
"""based on httplib.HTTPSConnection code - extended to support
server certificate verification and client certificate authorization"""
response_class = MyHTTPResponse
FORCE_SSL_VERSION = None
SERVER_CERT_CHECK = True # might be turned off when a workaround is needed
def __init__(self, host, ca_certs=None, cert_verifier=None,
keyobj=None, certobj=None, **kw):
"""cert_verifier is a function returning either True or False
based on whether the certificate was found to be OK,
keyobj and certobj represent internal PyOpenSSL structures holding
the key and certificate respectively.
"""
httplib.HTTPSConnection.__init__(self, host, **kw)
self.ca_certs = ca_certs
self.cert_verifier = cert_verifier
self.keyobj = keyobj
self.certobj = certobj
def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if hasattr(self, '_tunnel_host') and self._tunnel_host:
self.sock = sock
self._tunnel()
if self.FORCE_SSL_VERSION:
add = {'ssl_version': self.FORCE_SSL_VERSION}
else:
add = {}
if self.SERVER_CERT_CHECK and self.ca_certs:
add['cert_reqs'] = ssl.CERT_REQUIRED
else:
add['cert_reqs'] = ssl.CERT_NONE
# try to use PyOpenSSL by default
if PYOPENSSL_AVAILABLE:
wrap_class = PyOpenSSLSocket
add['keyobj'] = self.keyobj
add['certobj'] = self.certobj
add['keyfile'] = self.key_file
add['certfile'] = self.cert_file
else:
wrap_class = ssl.SSLSocket
self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
#if self.cert_verifier and self.SERVER_CERT_CHECK:
# if not self.cert_verifier(self.sock.getpeercert()):
# raise Exception("Server certificate did not pass security check.",
# self.sock.getpeercert())
class CheckingHTTPSHandler(u2.HTTPSHandler):
def __init__(self, ca_certs=None, cert_verifier=None,
client_certfile=None, client_keyfile=None,
client_keyobj=None, client_certobj=None,
*args, **kw):
"""cert_verifier is a function returning either True or False
based on whether the certificate was found to be OK"""
u2.HTTPSHandler.__init__(self, *args, **kw)
self.ca_certs = ca_certs
self.cert_verifier = cert_verifier
self.client_keyfile = client_keyfile # filename
self.client_certfile = client_certfile # filename
self.keyobj = client_keyobj
self.certobj = client_certobj
# FOR DEBUG
# self.set_http_debuglevel(100)
def https_open(self, req):
def open(*args, **kw):
new_kw = dict(ca_certs=self.ca_certs,
cert_verifier=self.cert_verifier,
cert_file=self.client_certfile,
key_file=self.client_keyfile,
keyobj=self.keyobj,
certobj=self.certobj)
new_kw.update(kw)
return CheckingHTTPSConnection(*args, **new_kw)
return self.do_open(open, req)
https_request = u2.AbstractHTTPHandler.do_request_
# class CheckingHTTPSConnection(httplib.HTTPSConnection):
# """based on httplib.HTTPSConnection code - extended to support
# server certificate verification and client certificate authorization"""
# response_class = MyHTTPResponse
# FORCE_SSL_VERSION = None
# SERVER_CERT_CHECK = True # might be turned off when a workaround is needed
# def __init__(self, host, ca_certs=None, cert_verifier=None,
# keyobj=None, certobj=None, **kw):
# """cert_verifier is a function returning either True or False
# based on whether the certificate was found to be OK,
# keyobj and certobj represent internal PyOpenSSL structures holding
# the key and certificate respectively.
# """
# httplib.HTTPSConnection.__init__(self, host, **kw)
# self.ca_certs = ca_certs
# self.cert_verifier = cert_verifier
# self.keyobj = keyobj
# self.certobj = certobj
# def connect(self):
# sock = socket.create_connection((self.host, self.port), self.timeout)
# if hasattr(self, '_tunnel_host') and self._tunnel_host:
# self.sock = sock
# self._tunnel()
# if self.FORCE_SSL_VERSION:
# add = {'ssl_version': self.FORCE_SSL_VERSION}
# else:
# add = {}
# if self.SERVER_CERT_CHECK and self.ca_certs:
# add['cert_reqs'] = ssl.CERT_REQUIRED
# else:
# add['cert_reqs'] = ssl.CERT_NONE
# # try to use PyOpenSSL by default
# if PYOPENSSL_AVAILABLE:
# wrap_class = PyOpenSSLSocket
# add['keyobj'] = self.keyobj
# add['certobj'] = self.certobj
# add['keyfile'] = self.key_file
# add['certfile'] = self.cert_file
# else:
# wrap_class = ssl.SSLSocket
# self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
# #if self.cert_verifier and self.SERVER_CERT_CHECK:
# # if not self.cert_verifier(self.sock.getpeercert()):
# # raise Exception("Server certificate did not pass security check.",
# # self.sock.getpeercert())
class Client_suds(SessionId, Client):
@ -187,9 +145,12 @@ class Client_suds(SessionId, Client):
class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
"""based on httplib.HTTPSConnection code - extended to support
server certificate verification and client certificate authorization"""
class CheckingClientHTTPSConnection(httplib.HTTPSConnection):
"""based on httplib.HTTPSConnection code"""
response_class = httplib.HTTPResponse
FORCE_SSL_VERSION = None
SERVER_CERT_CHECK = True # might be turned off when a workaround is needed
def __init__(self, cert_path, host, ca_certs=None, cert_verifier=None,
keyobj=None, certobj=None, wait_thread=None, **kw):
@ -198,11 +159,12 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
keyobj and certobj represent internal PyOpenSSL structures holding
the key and certificate respectively.
"""
CheckingHTTPSConnection.__init__(self, host, ca_certs, cert_verifier,
keyobj, certobj, **kw)
# self.ClientObj = ClientObj
self.cert_path = cert_path
httplib.HTTPSConnection.__init__(self, host, **kw)
self.ca_certs = ca_certs
self.cert_verifier = cert_verifier
self.keyobj = keyobj
self.certobj = certobj
self.cert_path = cert_path
self.CRL_PATH = os.path.join(cert_path, 'ca/crl/')
self.wait_thread = wait_thread
@ -233,7 +195,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
if not filename:
return None
except:
print _("Certificate not found on the client`s side")
print(_("Certificate not found on the client`s side"))
return None
try:
fd = open(self.trusted_path + filename, 'r')
@ -242,7 +204,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
if store_cert == server_cert:
return filename
except:
print _("Failed to open the file"), self.trusted_path, filename
print(_("Failed to open the file"), self.trusted_path, filename)
return None
def add_all_ca_cert(self, list_ca_certs):
@ -276,8 +238,8 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
md5 = hashlib.md5()
md5.update(cert)
md5sum = md5.hexdigest()
print "\n================================================="
print "md5sum = ", md5sum
print("\n=================================================")
print("md5sum = ", md5sum)
if not os.path.exists(root_cert_md5):
fc = open(root_cert_md5, "w")
@ -305,7 +267,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
fc.close()
if not filename:
print _('Field "CN" not found in the certificate!')
print(_('Field "CN" not found in the certificate!'))
return 1
fd = open(os.path.join(cl_client_cert_dir, 'ca/', filename),
@ -316,10 +278,10 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
fa = open(user_root_cert, 'a')
fa.write(cert)
fa.close()
print _("filename = "), filename
print _("Certificate added")
print(_("filename = "), filename)
print(_("Certificate added"))
else:
print _("The file containing the CA certificate now exists")
print(_("The file containing the CA certificate now exists"))
get_CRL(cl_client_cert_dir)
def add_ca_cert(self, cert, list_ca_certs):
@ -329,55 +291,55 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
client.wsdl.services[0].setlocation(url)
cert = client.service.get_ca()
if cert == '1':
print _("Invalid server certificate!")
print(_("Invalid server certificate!"))
raise Exception(1)
if cert == '2':
print _("CA certificate not found on the server")
print(_("CA certificate not found on the server"))
raise Exception(1)
try:
certobj = OpenSSL.crypto.load_certificate(
OpenSSL.SSL.FILETYPE_PEM, cert)
except:
print _("Error. Certificate not added to trusted")
print(_("Error. Certificate not added to trusted"))
raise Exception(1)
print '\n', _("Fingerprint = %s") % certobj.digest('SHA1')
print _("Serial Number = "), certobj.get_serial_number()
print('\n', _("Fingerprint = %s") % certobj.digest('SHA1'))
print(_("Serial Number = "), certobj.get_serial_number())
Issuer = certobj.get_issuer().get_components()
print '\n', _("Issuer")
print('\n', _("Issuer"))
for i in Issuer:
print "%s : %s" % (i[0], i[1])
print("%s : %s" % (i[0], i[1]))
Subject = certobj.get_subject().get_components()
print '\n', _("Subject")
print('\n', _("Subject"))
for subj in Subject:
print "%s : %s" % (subj[0], subj[1])
print("%s : %s" % (subj[0], subj[1]))
ans = raw_input(_("Add the CA certificate to trusted? y/[n]:"))
if ans.lower() in ['y', 'yes']:
list_ca_certs.append(cert)
self.add_all_ca_cert(list_ca_certs)
else:
print _("Certificate not added to trusted")
print(_("Certificate not added to trusted"))
# add certificate server in trusted
def add_server_cert(self, cert):
self.wait_thread.stop()
print _("Untrusted server certificate!")
print(_("Untrusted server certificate!"))
certobj = OpenSSL.crypto.load_certificate(
OpenSSL.SSL.FILETYPE_PEM, cert)
print '\n' + _("Fingerprint = %s") % certobj.digest('SHA1')
print _("Serial Number = "), certobj.get_serial_number()
print('\n' + _("Fingerprint = %s") % certobj.digest('SHA1'))
print(_("Serial Number = "), certobj.get_serial_number())
Issuer = certobj.get_issuer().get_components()
print '\n' + _("Issuer")
print('\n' + _("Issuer"))