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 -*- #-*- coding: utf-8 -*-
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org # Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org

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

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

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

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

@ -14,8 +14,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import urllib2 as u2 import urllib.request as u2
if hasattr(u2, "ssl"): if hasattr(u2, "ssl"):
u2.ssl._create_default_https_context = u2.ssl._create_unverified_context u2.ssl._create_default_https_context = u2.ssl._create_unverified_context
import os import os
@ -25,23 +24,18 @@ import ssl
import OpenSSL import OpenSSL
import hashlib import hashlib
import M2Crypto import M2Crypto
import calculate.contrib
from calculate.core.datavars import DataVarsCore from calculate.core.datavars import DataVarsCore
from calculate.lib.datavars import DataVars from calculate.lib.datavars import DataVars
import calculate.contrib import calculate.contrib
from suds.client import Client from suds.client import Client
from cert_verify import verify, get_CRL from .cert_verify import verify, get_CRL
import httplib import http.client as httplib
from suds.transport.http import HttpTransport from suds.transport.http import HttpTransport
try: from .pyopenssl_wrapper import PyOpenSSLSocket
from pyopenssl_wrapper import PyOpenSSLSocket
except ImportError:
PYOPENSSL_AVAILABLE = False
else:
PYOPENSSL_AVAILABLE = True
from suds.transport import Transport from suds.transport import Transport
from suds.properties import Unskin from suds.properties import Unskin
from http.cookiejar import CookieJar, DefaultCookiePolicy
from cookielib import CookieJar, DefaultCookiePolicy
from logging import getLogger from logging import getLogger
from calculate.console.datavars import DataVarsConsole from calculate.console.datavars import DataVarsConsole
from calculate.lib.cl_lang import setLocalTranslate from calculate.lib.cl_lang import setLocalTranslate
@ -80,94 +74,58 @@ class SUDSHTTPRedirectHandler(u2.HTTPRedirectHandler):
else: else:
raise u2.HTTPError(req.get_full_url(), code, msg, headers, fp) raise u2.HTTPError(req.get_full_url(), code, msg, headers, fp)
class MyHTTPResponse(httplib.HTTPResponse):
# class CheckingHTTPSConnection(httplib.HTTPSConnection):
def __init__(self, sock, debuglevel=0, strict=0, method=None): # """based on httplib.HTTPSConnection code - extended to support
# server certificate verification and client certificate authorization"""
httplib.HTTPResponse.__init__(self, sock, debuglevel, strict, method)
# response_class = MyHTTPResponse
class CheckingHTTPSConnection(httplib.HTTPSConnection):
"""based on httplib.HTTPSConnection code - extended to support # FORCE_SSL_VERSION = None
server certificate verification and client certificate authorization""" # SERVER_CERT_CHECK = True # might be turned off when a workaround is needed
response_class = MyHTTPResponse
# def __init__(self, host, ca_certs=None, cert_verifier=None,
FORCE_SSL_VERSION = None # keyobj=None, certobj=None, **kw):
SERVER_CERT_CHECK = True # might be turned off when a workaround is needed # """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
def __init__(self, host, ca_certs=None, cert_verifier=None, # the key and certificate respectively.
keyobj=None, certobj=None, **kw): # """
"""cert_verifier is a function returning either True or False # httplib.HTTPSConnection.__init__(self, host, **kw)
based on whether the certificate was found to be OK, # self.ca_certs = ca_certs
keyobj and certobj represent internal PyOpenSSL structures holding # self.cert_verifier = cert_verifier
the key and certificate respectively. # self.keyobj = keyobj
""" # self.certobj = certobj
httplib.HTTPSConnection.__init__(self, host, **kw)
self.ca_certs = ca_certs # def connect(self):
self.cert_verifier = cert_verifier # sock = socket.create_connection((self.host, self.port), self.timeout)
self.keyobj = keyobj # if hasattr(self, '_tunnel_host') and self._tunnel_host:
self.certobj = certobj # self.sock = sock
# self._tunnel()
def connect(self): # if self.FORCE_SSL_VERSION:
sock = socket.create_connection((self.host, self.port), self.timeout) # add = {'ssl_version': self.FORCE_SSL_VERSION}
if hasattr(self, '_tunnel_host') and self._tunnel_host: # else:
self.sock = sock # add = {}
self._tunnel() # if self.SERVER_CERT_CHECK and self.ca_certs:
if self.FORCE_SSL_VERSION: # add['cert_reqs'] = ssl.CERT_REQUIRED
add = {'ssl_version': self.FORCE_SSL_VERSION} # else:
else: # add['cert_reqs'] = ssl.CERT_NONE
add = {} # # try to use PyOpenSSL by default
if self.SERVER_CERT_CHECK and self.ca_certs: # if PYOPENSSL_AVAILABLE:
add['cert_reqs'] = ssl.CERT_REQUIRED # wrap_class = PyOpenSSLSocket
else: # add['keyobj'] = self.keyobj
add['cert_reqs'] = ssl.CERT_NONE # add['certobj'] = self.certobj
# try to use PyOpenSSL by default # add['keyfile'] = self.key_file
if PYOPENSSL_AVAILABLE: # add['certfile'] = self.cert_file
wrap_class = PyOpenSSLSocket # else:
add['keyobj'] = self.keyobj # wrap_class = ssl.SSLSocket
add['certobj'] = self.certobj # self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
add['keyfile'] = self.key_file # #if self.cert_verifier and self.SERVER_CERT_CHECK:
add['certfile'] = self.cert_file # # if not self.cert_verifier(self.sock.getpeercert()):
else: # # raise Exception("Server certificate did not pass security check.",
wrap_class = ssl.SSLSocket # # self.sock.getpeercert())
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 Client_suds(SessionId, Client): class Client_suds(SessionId, Client):
@ -187,9 +145,12 @@ class Client_suds(SessionId, Client):
class CheckingClientHTTPSConnection(CheckingHTTPSConnection): class CheckingClientHTTPSConnection(httplib.HTTPSConnection):
"""based on httplib.HTTPSConnection code - extended to support """based on httplib.HTTPSConnection code"""
server certificate verification and client certificate authorization""" 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, def __init__(self, cert_path, host, ca_certs=None, cert_verifier=None,
keyobj=None, certobj=None, wait_thread=None, **kw): keyobj=None, certobj=None, wait_thread=None, **kw):
@ -198,11 +159,12 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
keyobj and certobj represent internal PyOpenSSL structures holding keyobj and certobj represent internal PyOpenSSL structures holding
the key and certificate respectively. the key and certificate respectively.
""" """
CheckingHTTPSConnection.__init__(self, host, ca_certs, cert_verifier, httplib.HTTPSConnection.__init__(self, host, **kw)
keyobj, certobj, **kw)
# self.ClientObj = ClientObj
self.cert_path = cert_path
self.ca_certs = ca_certs 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.CRL_PATH = os.path.join(cert_path, 'ca/crl/')
self.wait_thread = wait_thread self.wait_thread = wait_thread
@ -233,7 +195,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
if not filename: if not filename:
return None return None
except: except:
print _("Certificate not found on the client`s side") print(_("Certificate not found on the client`s side"))
return None return None
try: try:
fd = open(self.trusted_path + filename, 'r') fd = open(self.trusted_path + filename, 'r')
@ -242,7 +204,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
if store_cert == server_cert: if store_cert == server_cert:
return filename return filename
except: except:
print _("Failed to open the file"), self.trusted_path, filename print(_("Failed to open the file"), self.trusted_path, filename)
return None return None
def add_all_ca_cert(self, list_ca_certs): def add_all_ca_cert(self, list_ca_certs):
@ -276,8 +238,8 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
md5 = hashlib.md5() md5 = hashlib.md5()
md5.update(cert) md5.update(cert)
md5sum = md5.hexdigest() md5sum = md5.hexdigest()
print "\n=================================================" print("\n=================================================")
print "md5sum = ", md5sum print("md5sum = ", md5sum)
if not os.path.exists(root_cert_md5): if not os.path.exists(root_cert_md5):
fc = open(root_cert_md5, "w") fc = open(root_cert_md5, "w")
@ -305,7 +267,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
fc.close() fc.close()
if not filename: if not filename:
print _('Field "CN" not found in the certificate!') print(_('Field "CN" not found in the certificate!'))
return 1 return 1
fd = open(os.path.join(cl_client_cert_dir, 'ca/', filename), 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 = open(user_root_cert, 'a')
fa.write(cert) fa.write(cert)
fa.close() fa.close()
print _("filename = "), filename print(_("filename = "), filename)
print _("Certificate added") print(_("Certificate added"))
else: 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) get_CRL(cl_client_cert_dir)
def add_ca_cert(self, cert, list_ca_certs): def add_ca_cert(self, cert, list_ca_certs):
@ -329,55 +291,55 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
client.wsdl.services[0].setlocation(url) client.wsdl.services[0].setlocation(url)
cert = client.service.get_ca() cert = client.service.get_ca()
if cert == '1': if cert == '1':
print _("Invalid server certificate!") print(_("Invalid server certificate!"))
raise Exception(1) raise Exception(1)
if cert == '2': if cert == '2':
print _("CA certificate not found on the server") print(_("CA certificate not found on the server"))
raise Exception(1) raise Exception(1)
try: try:
certobj = OpenSSL.crypto.load_certificate( certobj = OpenSSL.crypto.load_certificate(
OpenSSL.SSL.FILETYPE_PEM, cert) OpenSSL.SSL.FILETYPE_PEM, cert)
except: except:
print _("Error. Certificate not added to trusted") print(_("Error. Certificate not added to trusted"))
raise Exception(1) raise Exception(1)
print '\n', _("Fingerprint = %s") % certobj.digest('SHA1') print('\n', _("Fingerprint = %s") % certobj.digest('SHA1'))
print _("Serial Number = "), certobj.get_serial_number() print(_("Serial Number = "), certobj.get_serial_number())
Issuer = certobj.get_issuer().get_components() Issuer = certobj.get_issuer().get_components()
print '\n', _("Issuer") print('\n', _("Issuer"))
for i in 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() Subject = certobj.get_subject().get_components()
print '\n', _("Subject") print('\n', _("Subject"))
for subj in 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]:")) ans = raw_input(_("Add the CA certificate to trusted? y/[n]:"))
if ans.lower() in ['y', 'yes']: if ans.lower() in ['y', 'yes']:
list_ca_certs.append(cert) list_ca_certs.append(cert)
self.add_all_ca_cert(list_ca_certs) self.add_all_ca_cert(list_ca_certs)
else: else:
print _("Certificate not added to trusted") print(_("Certificate not added to trusted"))
# add certificate server in trusted # add certificate server in trusted
def add_server_cert(self, cert): def add_server_cert(self, cert):
self.wait_thread.stop() self.wait_thread.stop()
print _("Untrusted server certificate!") print(_("Untrusted server certificate!"))
certobj = OpenSSL.crypto.load_certificate( certobj = OpenSSL.crypto.load_certificate(
OpenSSL.SSL.FILETYPE_PEM, cert) OpenSSL.SSL.FILETYPE_PEM, cert)
print '\n' + _("Fingerprint = %s") % certobj.digest('SHA1') print('\n' + _("Fingerprint = %s") % certobj.digest('SHA1'))
print _("Serial Number = "), certobj.get_serial_number() print(_("Serial Number = "), certobj.get_serial_number())
Issuer = certobj.get_issuer().get_components() Issuer = certobj.get_issuer().get_components()
print '\n' + _("Issuer") print('\n' + _("Issuer"))
for i in 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() Subject = certobj.get_subject().get_components()
print '\n' + _("Subject") print('\n' + _("Subject"))
for item in Subject: for item in Subject:
print "%s : %s" % (item[0], item[1]) print("%s : %s" % (item[0], item[1]))
print '\n' + _('Add this server certificate to trusted (s) or') print('\n' + _('Add this server certificate to trusted (s) or'))
print _('Try to add the CA and root certificates to trusted (c) or') print(_('Try to add the CA and root certificates to trusted (c) or'))
choice = raw_input(_("Quit (q)? s/c/[q]: ")) choice = raw_input(_("Quit (q)? s/c/[q]: "))
if choice.lower() in ['s', 'c']: if choice.lower() in ['s', 'c']:
# self.sock = ssl.wrap_socket(sock) # self.sock = ssl.wrap_socket(sock)
@ -424,10 +386,10 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
try: try:
os.makedirs(root_cert_dir) os.makedirs(root_cert_dir)
except OSError: except OSError:
print _("Failed to create directory %s") % root_cert_dir print(_("Failed to create directory %s") % root_cert_dir)
raise Exception(1) raise Exception(1)
print '\n' + _("Add the CA and root certificates") print('\n' + _("Add the CA and root certificates"))
self.list_ca_certs = [] self.list_ca_certs = []
self.add_ca_cert(cert, self.list_ca_certs) self.add_ca_cert(cert, self.list_ca_certs)
return 3 return 3
@ -456,16 +418,11 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
else: else:
add = {} add = {}
add['cert_reqs'] = ssl.CERT_REQUIRED add['cert_reqs'] = ssl.CERT_REQUIRED
# try to use PyOpenSSL by default add['keyobj'] = self.keyobj
if PYOPENSSL_AVAILABLE: add['certobj'] = self.certobj
wrap_class = PyOpenSSLSocket add['keyfile'] = self.key_file
add['keyobj'] = self.keyobj add['certfile'] = self.cert_file
add['certobj'] = self.certobj self.sock = PyOpenSSLSocket(sock, ca_certs=self.ca_certs, **add)
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)
return 0 return 0
except: except:
return 1 return 1
@ -492,17 +449,11 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
else: else:
add = {} add = {}
add['cert_reqs'] = ssl.CERT_NONE add['cert_reqs'] = ssl.CERT_NONE
# try to use PyOpenSSL by default add['keyobj'] = self.keyobj
if PYOPENSSL_AVAILABLE: add['certobj'] = self.certobj
wrap_class = PyOpenSSLSocket add['keyfile'] = self.key_file
add['keyobj'] = self.keyobj add['certfile'] = self.cert_file
add['certobj'] = self.certobj self.sock = PyOpenSSLSocket(sock, ca_certs=None, **add)
add['keyfile'] = self.key_file
add['certfile'] = self.cert_file
else:
wrap_class = ssl.SSLSocket
self.sock = wrap_class(sock, ca_certs=None, **add)
return 0 return 0
except Exception: except Exception:
HTTPSClientCertTransport.filename = None HTTPSClientCertTransport.filename = None
@ -556,7 +507,7 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
elif result_server_con == 3: elif result_server_con == 3:
continue continue
elif result_server_con == 4: elif result_server_con == 4:
print _('This server is not trusted') print(_('This server is not trusted'))
self.wait_thread.stop() self.wait_thread.stop()
sys.exit(1) sys.exit(1)
elif result_root_con == 2: elif result_root_con == 2:
@ -566,19 +517,24 @@ class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
break break
class CheckingClientHTTPSHandler(CheckingHTTPSHandler):
class CheckingClientHTTPSHandler(u2.HTTPSHandler):
def __init__(self, cert_path, ca_certs=None, cert_verifier=None, def __init__(self, cert_path, ca_certs=None, cert_verifier=None,
client_certfile=None, client_keyfile=None, client_certfile=None, client_keyfile=None,
client_keyobj=None, client_certobj=None, wait_thread=None, client_keyobj=None, client_certobj=None,
*args, **kw): *args, **kw):
"""cert_verifier is a function returning either True or False """cert_verifier is a function returning either True or False
based on whether the certificate was found to be OK""" based on whether the certificate was found to be OK"""
CheckingHTTPSHandler.__init__(self, ca_certs, cert_verifier, u2.HTTPSHandler.__init__(self, *args, **kw)
client_keyfile, client_certfile, self.ca_certs = ca_certs
client_keyobj, client_certobj) self.cert_verifier = cert_verifier
# self.ClientObj = ClientObj 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)
self.cert_path = cert_path self.cert_path = cert_path
self.wait_thread = wait_thread
def https_open(self, req): def https_open(self, req):
def open(*args, **kw): def open(*args, **kw):
@ -586,12 +542,10 @@ class CheckingClientHTTPSHandler(CheckingHTTPSHandler):
cert_verifier=self.cert_verifier, cert_verifier=self.cert_verifier,
cert_file=self.client_certfile, cert_file=self.client_certfile,
key_file=self.client_keyfile, key_file=self.client_keyfile,
keyobj=self.keyobj, certobj=self.certobj, keyobj=self.keyobj,
wait_thread=self.wait_thread) certobj=self.certobj)
new_kw.update(kw) new_kw.update(kw)
return CheckingClientHTTPSConnection(self.cert_path, return CheckingClientHTTPSConnection(self.cert_path, *args, **new_kw)
*args, **new_kw)
return self.do_open(open, req) return self.do_open(open, req)
https_request = u2.AbstractHTTPHandler.do_request_ https_request = u2.AbstractHTTPHandler.do_request_
@ -605,60 +559,68 @@ class HTTPSClientCertTransport(HttpTransport):
cookie_callback=None, user_agent_string=None, cookie_callback=None, user_agent_string=None,
wait_thread=None, **kwargs): wait_thread=None, **kwargs):
Transport.__init__(self) Transport.__init__(self)
# self.ClientObj = parent
self.key = key self.key = key
self.cert = cert self.cert = cert
self.cert_path = path_to_cert self.cert_path = path_to_cert
if key: if key:
client_certobj = OpenSSL.crypto.load_certificate( with open(cert) as cert_file:
OpenSSL.SSL.FILETYPE_PEM, file(cert).read()) client_certobj = OpenSSL.crypto.load_certificate \
if password: (OpenSSL.SSL.FILETYPE_PEM, cert_file.read())
client_keyobj = OpenSSL.crypto.load_privatekey( if password:
OpenSSL.SSL.FILETYPE_PEM, file(key).read(), str(password)) with open(key) as key_file:
else: client_keyobj = OpenSSL.crypto.load_privatekey \
bio = M2Crypto.BIO.openfile(key) (OpenSSL.SSL.FILETYPE_PEM, key_file.read(),
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(), lambda *unused: "") password)
if not rsa: else:
raise OpenSSL.crypto.Error import M2Crypto
client_keyobj = OpenSSL.crypto.load_privatekey( bio = M2Crypto.BIO.openfile(key)
OpenSSL.SSL.FILETYPE_PEM, file(key).read()) rsa = M2Crypto.m2.rsa_read_key(bio._ptr(),lambda *unused: b"")
if not rsa:
raise OpenSSL.crypto.Error
with open(key) as key_file:
client_keyobj = OpenSSL.crypto.load_privatekey(OpenSSL.SSL.FILETYPE_PEM,
key_file.read())
Unskin(self.options).update(kwargs) Unskin(self.options).update(kwargs)
self.cookiejar = CookieJar(DefaultCookiePolicy()) self.cookiejar = CookieJar(DefaultCookiePolicy())
self.cookie_callback = cookie_callback self.cookie_callback = cookie_callback
self.user_agent_string = user_agent_string self.user_agent_string = user_agent_string
log.debug("Proxy: %s", self.options.proxy) log.debug("Proxy: %s", self.options.proxy)
#TODO to be removed:
# artifacts from old times:
if ca_certs or (client_keyfile and client_certfile) \
or (client_keyobj and client_certobj):
https_handler = CheckingClientHTTPSHandler(cert_path=path_to_cert,
ca_certs=ca_certs,
cert_verifier=cert_verifier,
client_keyfile=client_keyfile,
client_certfile=client_certfile,
client_keyobj=client_keyobj,
client_certobj=client_certobj)
else:
https_handler = u2.HTTPSHandler()
self.urlopener = u2.build_opener(SUDSHTTPRedirectHandler(),
u2.HTTPCookieProcessor(self.cookiejar),
https_handler)
# relic from old times:
# from dslib.network import ProxyManager # from dslib.network import ProxyManager
# proxy_handler = ProxyManager.HTTPS_PROXY.create_proxy_handler() # proxy_handler = ProxyManager.HTTPS_PROXY.create_proxy_handler()
# proxy_auth_handler = ProxyManager.HTTPS_PROXY.create_proxy_auth_handler() # proxy_auth_handler = ProxyManager.HTTPS_PROXY.create_proxy_auth_handler()
# apparently, dslib simply returned None on create_proxy_auth_handler # apparently, dslib simply returned None on create_proxy_auth_handler
# if this is ever needed, probably use urllib2.ProxyBasicAuthHandler # if this is ever needed, probably use urllib2.ProxyBasicAuthHandler
proxy_auth_handler = None # proxy_auth_handler = None
# and create_proxy_handler SHOULD HAVE eval'd to this: # and create_proxy_handler SHOULD HAVE eval'd to this:
# proxy_handler = urllib2.ProxyHandler({"https" : "https://hostname"}) # proxy_handler = urllib2.ProxyHandler({"https" : "https://hostname"})
# but because no hostname was given, it also just returned None # but because no hostname was given, it also just returned None
proxy_handler = None # proxy_handler = None
if (ca_certs or (client_keyfile and client_certfile)
or (client_keyobj and client_certobj)): #these two literally do nothing right now
https_handler = CheckingClientHTTPSHandler( # if proxy_handler:
cert_path=path_to_cert, # self.urlopener.add_handler(proxy_handler)
ca_certs=ca_certs, # if proxy_auth_handler:
cert_verifier=cert_verifier, # self.urlopener.add_handler(proxy_auth_handler)
client_keyfile=client_keyfile,
client_certfile=client_certfile, self.urlopener.addheaders = [('User-agent', str(self.user_agent_string))]
client_keyobj=client_keyobj,
client_certobj=client_certobj,
wait_thread=wait_thread)
else:
https_handler = u2.HTTPSHandler()
self.urlopener = u2.build_opener(SUDSHTTPRedirectHandler(),
u2.HTTPCookieProcessor(self.cookiejar),
https_handler)
if proxy_handler:
self.urlopener.add_handler(proxy_handler)
if proxy_auth_handler:
self.urlopener.add_handler(proxy_auth_handler)
self.urlopener.addheaders = [('User-agent', self.user_agent_string)]

@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import time import time
import os import os
import sys import sys
@ -34,7 +35,7 @@ setLocalTranslate('cl_console3', sys.modules[__name__])
def _print(*args): def _print(*args):
print " ".join(map(lambda x: unicode(x).encode('utf-8'), args)) print(" ".join(map(lambda x: unicode(x).encode('utf-8'), args)))
# get list of certificate and session id # get list of certificate and session id
@ -51,12 +52,12 @@ def clear():
except OSError as e: except OSError as e:
_print(e.message) _print(e.message)
except Exception: except Exception:
print _("Failed to clear the cache! ") print(_("Failed to clear the cache! "))
return 1 return 1
def get_ip_global(): def get_ip_global():
import urllib2 import urllib.request as urllib2
strURL = 'http://api.wipmania.com/' strURL = 'http://api.wipmania.com/'
f = urllib2.urlopen(urllib2.Request(strURL)) f = urllib2.urlopen(urllib2.Request(strURL))

@ -14,16 +14,19 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# from __future__ import print_function
# from __future__ import absolute_import
import argparse import argparse
import sys import sys
from calculate.core.server.api_types import ViewInfoAdapter from calculate.core.server.api_types import ViewInfoAdapter
from calculate.core.server.local_call import Methods, has_force_arg from calculate.core.server.local_call import Methods, has_force_arg
from function import _create_obj, get_view_params, print_brief, _print from .function import _create_obj, get_view_params, print_brief, _print
from calculate.lib.cl_lang import setLocalTranslate from calculate.lib.cl_lang import setLocalTranslate
from urllib.error import URLError
_ = lambda x: x _ = lambda x: x
setLocalTranslate('cl_console3', sys.modules[__name__]) setLocalTranslate('cl_console3', sys.modules[__name__])
import urllib2 import urllib.request as urllib2
from calculate.core.server.methods_func import get_method_argparser, \ from calculate.core.server.methods_func import get_method_argparser, \
collect_object, RawAndDefaultsHelpFormatter, \ collect_object, RawAndDefaultsHelpFormatter, \
@ -99,7 +102,7 @@ def parse():
def get_view(client, method, sid, view_params): def get_view(client, method, sid, view_params):
try: try:
view = client.service[0][method + '_view'](client.sid, view_params) view = client.service[0][method + '_view'](client.sid, view_params)
except urllib2.URLError, e: except URLError as e:
_print(_('Failed to connect') + ':', e) _print(_('Failed to connect') + ':', e)
raise Exception(1) raise Exception(1)
return view return view
@ -167,7 +170,7 @@ def call_method(client, args, unknown_args, wait_thread):
method_result = client.service[0][method](client.sid, method_result = client.service[0][method](client.sid,
param_object) param_object)
if not method_result: if not method_result:
print _('Method not available') print(_('Method not available'))
return None return None
if (method_result.ReturnedMessage[0].type and if (method_result.ReturnedMessage[0].type and
method_result.ReturnedMessage[0].type != "pid"): method_result.ReturnedMessage[0].type != "pid"):
@ -204,7 +207,7 @@ def call_method(client, args, unknown_args, wait_thread):
param_object = {} param_object = {}
method_result = client.service[0][method](client.sid, param_object) method_result = client.service[0][method](client.sid, param_object)
if not method_result: if not method_result:
print _('Method not available') print(_('Method not available'))
return None return None
if (method_result.ReturnedMessage[0].type and if (method_result.ReturnedMessage[0].type and
method_result.ReturnedMessage[0].type != "pid"): method_result.ReturnedMessage[0].type != "pid"):

@ -13,6 +13,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
from calculate.console.application.function import _print from calculate.console.application.function import _print
import sys import sys
@ -35,14 +36,14 @@ def pid_inf(client, sid, pids, wait_thread=None):
sys.stdout.write("\b") sys.stdout.write("\b")
sys.stdout.flush() sys.stdout.flush()
if s == "": if s == "":
print _("PID not found") print(_("PID not found"))
return 1 return 1
if s[0][0] == "Permission denied": if s[0][0] == "Permission denied":
print _("Permission denied") print(_("Permission denied"))
return 1 return 1
_print(_(u"Process name: %s") % s[0][4]) _print(_(u"Process name: %s") % s[0][4])
print _(u"ID: %s") % s[0][0] print(_(u"ID: %s") % s[0][0])
_print(_(u"Start time: %s") % s[0][2].partition(".")[0]) _print(_(u"Start time: %s") % s[0][2].partition(".")[0])
if s[0][1] == '1': if s[0][1] == '1':
status = _(u"Active") status = _(u"Active")
@ -50,9 +51,9 @@ def pid_inf(client, sid, pids, wait_thread=None):
status = _(u"Completed") status = _(u"Completed")
else: else:
status = _(u"Killed") status = _(u"Killed")
print _(u"Status: %s") % status print(_(u"Status: %s") % status)
if not mark.last: if not mark.last:
print print()
return 0 return 0
@ -65,13 +66,13 @@ def client_list_pid(client):
try: try:
list_pid = client.service.list_pid(sid=sid) list_pid = client.service.list_pid(sid=sid)
if list_pid[0][0] == 0: if list_pid[0][0] == 0:
print red + _("PIDs not found for this session!") print(red + _("PIDs not found for this session!"))
return 0 return 0
else: else:
for i in list_pid[0]: for i in list_pid[0]:
print green + "pid - %d" % i print(green + "pid - %d" % i)
except Exception: except Exception:
print red + _("Error fetching the PID list from the server") print(red + _("Error fetching the PID list from the server"))
return 1 return 1
return len(list_pid[0]) return len(list_pid[0])
@ -83,13 +84,13 @@ def gen_pid_ls(client):
try: try:
list_pid = client.service.list_pid(sid=sid) list_pid = client.service.list_pid(sid=sid)
if list_pid[0][0] == 0: if list_pid[0][0] == 0:
print _("PIDs not found for this session!") print(_("PIDs not found for this session!"))
return 0 return 0
else: else:
for i in list_pid[0]: for i in list_pid[0]:
pid_ls.append(i) pid_ls.append(i)
except Exception: except Exception:
print _("Error fetching the PID list from the server") print(_("Error fetching the PID list from the server"))
return 0 return 0
return pid_ls return pid_ls
@ -115,25 +116,25 @@ def client_list_methods(client):
TR_METH = 3 # Translate method name TR_METH = 3 # Translate method name
results = client.service.get_methods(client.sid, client_types) results = client.service.get_methods(client.sid, client_types)
if not results: if not results:
print _('No methods available') print(_('No methods available'))
return 1 return 1
try: try:
if results[DAT][RES][RES][COM] == '0': if results[DAT][RES][RES][COM] == '0':
print _('No methods available') print(_('No methods available'))
return 1 return 1
except: except:
pass pass
print _("Available methods:") print(_("Available methods:"))
group_dict = {} group_dict = {}
for group in results.stringArray: for group in results.stringArray:
if len(group.string) == 4: if len(group.string) == 4:
group_dict[group.string[METH]] = group.string[TR_METH] group_dict[group.string[METH]] = group.string[TR_METH]
if len(group.string) == 3: if len(group.string) == 3:
group_dict[group.string[METH]] = group.string[TR_METH - 1] group_dict[group.string[METH]] = group.string[TR_METH - 1]
sort_keys = group_dict.keys() sort_keys = list(group_dict.keys())
sort_keys.sort() sort_keys.sort()
for key in sort_keys: for key in sort_keys:
print " %s - %s" % (key, group_dict[key]) print(" %s - %s" % (key, group_dict[key]))
def client_pid_kill(client, pid): def client_pid_kill(client, pid):
@ -141,15 +142,15 @@ def client_pid_kill(client, pid):
result = client.service.pid_kill(pid, sid) result = client.service.pid_kill(pid, sid)
if result == 0: if result == 0:
print _("Process completed") print(_("Process completed"))
elif result == 2: elif result == 2:
print _("Process killed") print(_("Process killed"))
elif result == 3: elif result == 3:
print _("Process not found") print(_("Process not found"))
elif result == -1: elif result == -1:
print _("Certificate not found on the server") print(_("Certificate not found on the server"))
elif result == -2: elif result == -2:
print _("Session not matching your certificate") print(_("Session not matching your certificate"))
elif result == 1: elif result == 1:
print _("Failed to terminate the process") print(_("Failed to terminate the process"))
return 0 return 0

@ -1,35 +1,28 @@
""" #-*- coding: utf-8 -*-
This is just a simple copy of the ssl.py module contained in the Python
standard library. It was modified to work with PyOpenSSL and only to the # Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
extent that it works with the DS server. It might not work for any other #
purpose. # Licensed under the Apache License, Version 2.0 (the "License");
""" # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.
import textwrap
import _ssl # if we can't import it, let the error propagate
from _ssl import SSLError
from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1 from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_2
from _ssl import RAND_status, RAND_add
from _ssl import \
SSL_ERROR_ZERO_RETURN, \
SSL_ERROR_WANT_READ, \
SSL_ERROR_WANT_WRITE, \
SSL_ERROR_WANT_X509_LOOKUP, \
SSL_ERROR_SYSCALL, \
SSL_ERROR_SSL, \
SSL_ERROR_WANT_CONNECT, \
SSL_ERROR_EOF, \
SSL_ERROR_INVALID_ERROR_CODE
from socket import socket, _fileobject # from socket import socket
from socket import getnameinfo as _getnameinfo from socket import SocketIO
import base64 # for DER-to-PEM translation import io
# the OpenSSL stuff # the OpenSSL stuff
import OpenSSL import OpenSSL
_ssl_to_openssl_cert_op_remap = { _ssl_to_openssl_cert_op_remap = {
@ -40,313 +33,114 @@ _ssl_to_openssl_cert_op_remap = {
_ssl_to_openssl_version_remap = { _ssl_to_openssl_version_remap = {
PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
PROTOCOL_TLSv1_2 : OpenSSL.SSL.TLSv1_2_METHOD
} }
class PyOpenSSLSocket (socket): class PyOpenSSLSocket(OpenSSL.SSL.Connection):
"""This class implements a subtype of socket.socket that wraps
the underlying OS socket in an SSL context when necessary, and
provides read and write methods over that channel."""
def __init__(self, sock, keyfile=None, certfile=None, def __init__(self, sock, keyfile=None, certfile=None,
server_side=False, cert_reqs=CERT_NONE, server_side=False, cert_reqs=CERT_NONE,
ssl_version=PROTOCOL_SSLv23, ca_certs=None, ssl_version=PROTOCOL_TLSv1_2, ca_certs=None,
do_handshake_on_connect=True, do_handshake_on_connect=True,
suppress_ragged_eofs=True,
keyobj=None, certobj=None): keyobj=None, certobj=None):
socket.__init__(self, _sock=sock._sock)
# the initializer for socket trashes the methods (tsk, tsk), so...
self.send = lambda data, flags=0: PyOpenSSLSocket.send(self, data, flags)
self.sendto = lambda data, addr, flags=0: PyOpenSSLSocket.sendto(self, data, addr, flags)
self.recv = lambda buflen=1024, flags=0: PyOpenSSLSocket.recv(self, buflen, flags)
self.recvfrom = lambda addr, buflen=1024, flags=0: PyOpenSSLSocket.recvfrom(self, addr, buflen, flags)
self.recv_into = lambda buffer, nbytes=None, flags=0: PyOpenSSLSocket.recv_into(self, buffer, nbytes, flags)
self.recvfrom_into = lambda buffer, nbytes=None, flags=0: PyOpenSSLSocket.recvfrom_into(self, buffer, nbytes, flags)
if certfile and not keyfile: context = PyOpenSSLSocket.make_context(
keyfile = certfile keyfile = keyfile,
# see if it's connected certfile = certfile,
try: cert_reqs = cert_reqs,
socket.getpeername(self) ssl_version = ssl_version,
except: ca_certs = ca_certs,
# no, no connection yet keyobj = keyobj,
self._sslobj = None certobj = certobj)
else: super().__init__(context, sock)
# yes, create the SSL object self.setblocking(True)
self._sslobj = sslwrap(self._sock, server_side, self.set_connect_state()
keyfile, certfile, if do_handshake_on_connect:
cert_reqs, ssl_version, ca_certs, timeout = self.gettimeout()
keyobj=keyobj, certobj=certobj) try:
if do_handshake_on_connect: self.settimeout(None)
timeout = self.gettimeout() self.do_handshake()
try: finally:
self.settimeout(None) self.settimeout(timeout)
self.do_handshake()
finally: self._io_refs = 0
self.settimeout(timeout)
self.keyfile = keyfile
self.certfile = certfile
self.cert_reqs = cert_reqs
self.ssl_version = ssl_version
self.ca_certs = ca_certs
self.do_handshake_on_connect = do_handshake_on_connect self.do_handshake_on_connect = do_handshake_on_connect
self.suppress_ragged_eofs = suppress_ragged_eofs
self._makefile_refs = 0
self.keyobj = keyobj
self.certobj = certobj
def read(self, len=1024):
"""Read up to LEN bytes and return them.
Return zero-length string on EOF."""
try:
return self._sslobj.read(len)
except SSLError, x:
if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return ''
else:
raise
def write(self, data):
"""Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted."""
return self._sslobj.write(data)
def getpeercert(self, binary_form=False):
"""Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated."""
return self._sslobj.get_peer_certificate()
def cipher (self):
if not self._sslobj:
return None
else:
return self._sslobj.cipher()
def send (self, data, flags=0):
if self._sslobj:
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to send() on %s" %
self.__class__)
while True:
try:
v = self._sslobj.write(data)
except SSLError, x:
if x.args[0] == SSL_ERROR_WANT_READ:
return 0
elif x.args[0] == SSL_ERROR_WANT_WRITE:
return 0
else:
raise
else:
return v
else:
return socket.send(self, data, flags)
def sendto (self, data, addr, flags=0):
if self._sslobj:
raise ValueError("sendto not allowed on instances of %s" %
self.__class__)
else:
return socket.sendto(self, data, addr, flags)
def sendall (self, data, flags=0):
if self._sslobj:
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to sendall() on %s" %
self.__class__)
amount = len(data)
count = 0
while (count < amount):
v = self.send(data[count:])
count += v
return amount
else:
return socket.sendall(self, data, flags)
def recv (self, buflen=1024, flags=0):
if self._sslobj:
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to sendall() on %s" %
self.__class__)
while True:
try:
return self.read(buflen)
except SSLError, x:
if x.args[0] == SSL_ERROR_WANT_READ:
continue
else:
raise x
else:
return socket.recv(self, buflen, flags)
def recv_into (self, buffer, nbytes=None, flags=0):
if buffer and (nbytes is None):
nbytes = len(buffer)
elif nbytes is None:
nbytes = 1024
if self._sslobj:
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to recv_into() on %s" %
self.__class__)
while True:
try:
tmp_buffer = self.read(nbytes)
v = len(tmp_buffer)
buffer[:v] = tmp_buffer
return v
except SSLError, x:
if x.args[0] == SSL_ERROR_WANT_READ:
continue
else:
raise x
else:
return socket.recv_into(self, buffer, nbytes, flags)
def recvfrom (self, addr, buflen=1024, flags=0):
if self._sslobj:
raise ValueError("recvfrom not allowed on instances of %s" %
self.__class__)
else:
return socket.recvfrom(self, addr, buflen, flags)
def recvfrom_into (self, buffer, nbytes=None, flags=0):
if self._sslobj:
raise ValueError("recvfrom_into not allowed on instances of %s" %
self.__class__)
else:
return socket.recvfrom_into(self, buffer, nbytes, flags)
def pending (self):
if self._sslobj:
return self._sslobj.pending()
else:
return 0
def unwrap (self):
if self._sslobj:
s = self._sslobj.shutdown()
self._sslobj = None
return s
else:
raise ValueError("No SSL wrapper around " + str(self))
def shutdown (self, how):
self._sslobj = None
socket.shutdown(self, how)
def close (self):
if self._makefile_refs < 1:
self._sslobj = None
socket.close(self)
else:
self._makefile_refs -= 1
def do_handshake (self):
"""Perform a TLS/SSL handshake."""
self._sslobj.do_handshake()
def connect(self, addr): def connect(self, addr):
print("PYOPENSSL CONNECT")
"""Connects to remote ADDR, and then wraps the connection in super().connect(addr)
an SSL channel."""
# Here we assume that the socket is client-side, and not
# connected at the time of the call. We connect it, then wrap it.
if self._sslobj:
raise ValueError("attempt to connect already-connected PyOpenSSLSocket!")
socket.connect(self, addr)
self._sslobj = sslwrap(self._sock, False, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs,
keyobj=self.keyobj, certobj=self.certobj)
if self.do_handshake_on_connect: if self.do_handshake_on_connect:
self.do_handshake() self.do_handshake()
def accept(self): def close (self):
if self._io_refs < 1:
"""Accepts a new connection from a remote client, and returns self._socket.close()
a tuple containing that new connection wrapped with a server-side else:
SSL channel, and the address of the remote client.""" self._io_refs -= 1
newsock, addr = socket.accept(self) def makefile(self, mode="r", buffering=None, *,
return (PyOpenSSLSocket(newsock, encoding=None, errors=None, newline=None):
keyfile=self.keyfile, """makefile(...) -> an I/O stream connected to the socket
certfile=self.certfile,
server_side=True, The arguments are as for io.open() after the filename, except the only
cert_reqs=self.cert_reqs, supported mode values are 'r' (default), 'w' and 'b'.
ssl_version=self.ssl_version, """
ca_certs=self.ca_certs, if not set(mode) <= {"r", "w", "b"}:
do_handshake_on_connect=self.do_handshake_on_connect, raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
suppress_ragged_eofs=self.suppress_ragged_eofs), writing = "w" in mode
addr) reading = "r" in mode or not writing
assert reading or writing
def makefile(self, mode='r', bufsize=-1): binary = "b" in mode
rawmode = ""
"""Make and return a file-like object that if reading:
works with the SSL connection. Just use the code rawmode += "r"
from the socket module.""" if writing:
rawmode += "w"
self._makefile_refs += 1 raw = SocketIO(self, rawmode)
return _fileobject(self, mode, bufsize) self._io_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
def wrap_socket(sock, keyfile=None, certfile=None, buffering = io.DEFAULT_BUFFER_SIZE
server_side=False, cert_reqs=CERT_NONE, if buffering == 0:
ssl_version=PROTOCOL_SSLv23, ca_certs=None, if not binary:
do_handshake_on_connect=True, raise ValueError("unbuffered streams must be binary")
suppress_ragged_eofs=True): return raw
if reading and writing:
return PyOpenSSLSocket(sock, keyfile=keyfile, certfile=certfile, buffer = io.BufferedRWPair(raw, raw, buffering)
server_side=server_side, cert_reqs=cert_reqs, elif reading:
ssl_version=ssl_version, ca_certs=ca_certs, buffer = io.BufferedReader(raw, buffering)
do_handshake_on_connect=do_handshake_on_connect, else:
suppress_ragged_eofs=suppress_ragged_eofs) assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text
@staticmethod
def make_context(keyfile=None, certfile=None,
cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLSv1_2,
ca_certs=None, keyobj=None, certobj=None):
ctx = OpenSSL.SSL.Context(_ssl_to_openssl_version_remap[ssl_version])
if ca_certs:
ctx.load_verify_locations(ca_certs)
ctx.set_verify(_ssl_to_openssl_cert_op_remap[cert_reqs], verify_connection)
if keyobj:
ctx.use_privatekey(keyobj)
elif keyfile:
ctx.use_privatekey_file(keyfile)
if certobj:
ctx.use_certificate(certobj)
elif certfile:
ctx.use_certificate_file(certfile)
ctx.set_options(0x4000) # THIS IS THE KEY TO SUCCESS OF DS
return ctx
def verify_connection(conn, x509, error_code, depth, ret_code): def verify_connection(conn, x509, error_code, depth, ret_code):
# no extra validation - just return whatever OpenSSL already # no extra validation - just return whatever OpenSSL already
# decided during its check # decided during its check
return bool(ret_code) return bool(ret_code)
def sslwrap(sock, server_side=False, keyfile=None, certfile=None,
cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23,
ca_certs=None, keyobj=None, certobj=None):
"""this is modification of _ssl.sslwrap that uses PyOpenSSL,
keyobj and certobj are new parameters allowing setting the
key and cert not by filename, but from internal PyOpenSSL
structures.
"""
ctx = OpenSSL.SSL.Context(_ssl_to_openssl_version_remap[ssl_version])
if ca_certs:
ctx.load_verify_locations(ca_certs)
ctx.set_verify(_ssl_to_openssl_cert_op_remap[cert_reqs], verify_connection)
if keyobj:
ctx.use_privatekey(keyobj)
elif keyfile:
ctx.use_privatekey_file(keyfile)
if certobj:
ctx.use_certificate(certobj)
elif certfile:
ctx.use_certificate_file(certfile)
ctx.set_options(0x4000) # THIS IS THE KEY TO SUCCESS OF DS
ssl_sock = OpenSSL.SSL.Connection(ctx, sock)
ssl_sock.setblocking(True)
ssl_sock.set_connect_state()
return ssl_sock

@ -13,6 +13,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import os import os
import sys import sys
@ -31,21 +32,21 @@ def sid_inf(client, sid):
green = '\033[32m * \033[0m' green = '\033[32m * \033[0m'
s = client.service.sid_info(sid) s = client.service.sid_info(sid)
if s[0][0] == "-1": if s[0][0] == "-1":
print red + _("Session non registered on the server!") print(red + _("Session non registered on the server!"))
return -1 return -1
if s[0][0] == "-2": if s[0][0] == "-2":
print red + _("Failed to obtain certificate data!") print(red + _("Failed to obtain certificate data!"))
return -2 return -2
if s[0][0] == "Permission denied": if s[0][0] == "Permission denied":
print red + _("%s: permission denied") % s[0][1] print(red + _("%s: permission denied") % s[0][1])
return -3 return -3
print _('Session information: ') print(_('Session information: '))
print green + _(u"ID: %s") % sid print(green + _(u"ID: %s") % sid)
print green + _(u"Certificate number: %s") % s[0][0] print(green + _(u"Certificate number: %s") % s[0][0])
print green + _(u"Certificate issued: %s") % s[0][1].partition(".")[0] print(green + _(u"Certificate issued: %s") % s[0][1].partition(".")[0])
print green + "IP: %s" % s[0][2] print(green + "IP: %s" % s[0][2])
print green + "MAC: %s\n" % s[0][3] print(green + "MAC: %s\n" % s[0][3])
return 0 return 0
@ -54,12 +55,12 @@ def client_session_info(client, sid=None):
try: try:
select_sid = sid if sid else client.sid select_sid = sid if sid else client.sid
sid_inf(client, select_sid) sid_inf(client, select_sid)
except Exception, e: except Exception as e:
if type(e.message) == tuple and len(e.message) == 2 \ if type(e.message) == tuple and len(e.message) == 2 \
and e.message[1] == 'Forbidden': and e.message[1] == 'Forbidden':
print _("Access forbidden!") print(_("Access forbidden!"))
else: else:
print e print(e)
return 1 return 1
@ -68,36 +69,36 @@ def client_session_list(client):
green = '\033[32m * \033[0m' green = '\033[32m * \033[0m'
try: try:
res = client.service.get_sessions(client.sid) res = client.service.get_sessions(client.sid)
except Exception, e: except Exception as e:
if type(e.message) == tuple and len(e.message) == 2 \ if type(e.message) == tuple and len(e.message) == 2 \
and e.message[1] == 'Forbidden': and e.message[1] == 'Forbidden':
print _("Access forbidden!") print(_("Access forbidden!"))
else: else:
print e print(e)
return 1 return 1
if hasattr(res, 'string'): if hasattr(res, 'string'):
if res.string: if res.string:
print _('Active sessions on the server: ') print(_('Active sessions on the server: '))
for session_id in res.string: for session_id in res.string:
print green + session_id print(green + session_id)
print print()
return 0 return 0
print red + _('No active sessions on the server') print(red + _('No active sessions on the server'))
def session_clean(client): def session_clean(client):
try: try:
res = client.service.clear_session_cache(client.sid) res = client.service.clear_session_cache(client.sid)
if res: if res:
print _('Error clearing the session cache') print(_('Error clearing the session cache'))
else: else:
print _('Session cache cleared') print(_('Session cache cleared'))
except Exception as e: except Exception as e:
if type(e.message) == tuple and len(e.message) == 2 \ if type(e.message) == tuple and len(e.message) == 2 \
and e.message[1] == 'Forbidden': and e.message[1] == 'Forbidden':
print _("Access forbidden!") print(_("Access forbidden!"))
else: else:
print e print(e)
class SessionId(object): class SessionId(object):

@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org # Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
@ -14,16 +14,16 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from importlib import reload
def console_main(): def console_main():
import sys import sys
from calculate.console.application.cl_client import main, StoppableThread from .application.cl_client import main, StoppableThread
from calculate.console.application.function import _print from .application.function import _print
reload(sys) reload(sys)
sys.setdefaultencoding("utf-8") # sys.setdefaultencoding("utf-8")
import __builtin__ import builtins as __builtin__
from calculate.lib.cl_lang import setLocalTranslate from calculate.lib.cl_lang import setLocalTranslate
_ = lambda x: x _ = lambda x: x
@ -36,5 +36,5 @@ def console_main():
except KeyboardInterrupt: except KeyboardInterrupt:
wait_thread.stop() wait_thread.stop()
red = '\033[31m * \033[0m' red = '\033[31m * \033[0m'
print '\n' + red + _('Manually interrupted') print('\n' + red + _('Manually interrupted'))
sys.exit(1) sys.exit(1)

@ -14,6 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import console from . import console
section = "console" section = "console"

Loading…
Cancel
Save