Compare commits
No commits in common. 'master' and 'develop' have entirely different histories.
@ -1,5 +0,0 @@
|
||||
revert_changes_to_vmachine
|
||||
push_to_vmachine*
|
||||
.vscode
|
||||
*.pyc
|
||||
*.pyo
|
@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 calculate.console.console_main as console_main
|
||||
|
||||
if __name__=='__main__':
|
||||
console_main.console_main()
|
@ -0,0 +1,568 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2013 Calculate Ltd. http://www.calculate-linux.org
|
||||
#
|
||||
# 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.
|
||||
from calculate.core.server.local_call import Display, Methods
|
||||
|
||||
from sudsds import WebFault
|
||||
from sudsds.transport import TransportError
|
||||
|
||||
from client_class import Client_suds
|
||||
import traceback as tb
|
||||
import time, logging
|
||||
import os, sys
|
||||
import threading, urllib2
|
||||
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
|
||||
|
||||
import M2Crypto, 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, \
|
||||
get_view_params
|
||||
from calculate.lib.utils.files import makeDirectory, readLinesFile
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('cl_console3',sys.modules[__name__])
|
||||
|
||||
|
||||
def get_message_receiver(client):
|
||||
return MessageReceiver(client, MessageDispatcher(Methods()), Display())
|
||||
|
||||
|
||||
def get_entire_message_receiver(client, pid):
|
||||
return MessageReceiver.from_entire(client, pid,
|
||||
MessageDispatcher(Methods()), Display())
|
||||
|
||||
def client_signal(client):
|
||||
Vars = DataVarsCore()
|
||||
Vars.importCore()
|
||||
Vars.flIniFile()
|
||||
try:
|
||||
client_active = Vars.Get('core.cl_core_client_active_period')
|
||||
except:
|
||||
client_active = 15
|
||||
while True:
|
||||
if os.path.exists(client.SID_FILE) :
|
||||
fi = open(client.SID_FILE, 'r')
|
||||
temp = fi.read()
|
||||
fi.close()
|
||||
sid = int(temp)
|
||||
else:
|
||||
sid = 0
|
||||
try:
|
||||
client.service.active_client(sid)
|
||||
except:
|
||||
print _('no connection to the server!')
|
||||
raise Exception(1)
|
||||
time.sleep(float(client_active))
|
||||
|
||||
class StoppableThread(threading.Thread):
|
||||
def __init__(self):
|
||||
super(StoppableThread, self).__init__()
|
||||
self._stop = threading.Event()
|
||||
self._pause = threading.Event()
|
||||
self._paused = threading.Event()
|
||||
|
||||
def run(self):
|
||||
l = ['|','/','-','\\','|','/','-','\\']
|
||||
i = 0
|
||||
while True:
|
||||
for i in l:
|
||||
sys.stdout.write("\r\r" + i)
|
||||
sys.stdout.flush()
|
||||
time.sleep(.1)
|
||||
while self.paused() and not self.stopped():
|
||||
self._paused.set()
|
||||
if self.stopped():
|
||||
sys.stdout.write("\b")
|
||||
sys.stdout.flush()
|
||||
return 0
|
||||
|
||||
|
||||
def pause(self):
|
||||
self._pause.set()
|
||||
while not self._paused.is_set():
|
||||
self._paused.clear()
|
||||
sys.stdout.write("\r")
|
||||
sys.stdout.flush()
|
||||
|
||||
def resume(self):
|
||||
self._pause.clear()
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
|
||||
def stopped(self):
|
||||
return self._stop.isSet()
|
||||
|
||||
def paused(self):
|
||||
return self._pause.isSet()
|
||||
|
||||
def connect_with_cert(cert, path_to_cert, url, args, wait_thread, clVarsCore,
|
||||
crypto_Error, Connect_Error):
|
||||
flag_thread_start = False
|
||||
cert_name = cert
|
||||
CERT_FILE = os.path.join(path_to_cert, cert_name + '.crt')
|
||||
CERT_KEY = os.path.join(path_to_cert, cert_name + '.key')
|
||||
if not os.path.isfile(CERT_FILE) or not os.path.isfile(CERT_KEY):
|
||||
Connect_Error = 1
|
||||
return (None, 1, crypto_Error, False, None)
|
||||
client = None
|
||||
|
||||
bio = M2Crypto.BIO.openfile(CERT_KEY)
|
||||
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(),lambda *unused: None)
|
||||
if not rsa:
|
||||
port = args.port or clVarsCore.Get('core.cl_core_port')
|
||||
store_passwd = get_password_from_daemon(args.host, args.port,
|
||||
wait_thread)
|
||||
if 'store_passwd' in locals():
|
||||
key_passwd = store_passwd
|
||||
else:
|
||||
key_passwd = None
|
||||
try:
|
||||
ca_certs = os.path.join(path_to_cert, 'ca/ca_root.crt')
|
||||
client = Client_suds(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():
|
||||
wait_thread = StoppableThread()
|
||||
flag_thread_start = True
|
||||
wait_thread.start()
|
||||
client.wsdl.services[0].setlocation(url)
|
||||
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
|
||||
wait_thread.stop()
|
||||
client_post_cert(client, clVarsCore)
|
||||
Connect_Error = 0
|
||||
except VerifyError, e:
|
||||
Connect_Error = 1
|
||||
except OpenSSL.crypto.Error, e:
|
||||
Connect_Error = 1
|
||||
crypto_Error = 1
|
||||
except urllib2.URLError, e:
|
||||
Connect_Error = 1
|
||||
except Exception, e:
|
||||
if e.message == 3:
|
||||
wait_thread.stop()
|
||||
sys.exit(1)
|
||||
Connect_Error = 1
|
||||
if flag_thread_start:
|
||||
wait_thread.stop()
|
||||
return (client, Connect_Error, crypto_Error,
|
||||
True if 'store_passwd' in locals() else False,
|
||||
e if 'e' in locals() else None)
|
||||
|
||||
def get_server_hostname(host, path_to_cert):
|
||||
compliance_file = os.path.join(path_to_cert, 'compliance_server_names')
|
||||
if not os.path.isfile(compliance_file):
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.close()
|
||||
for line in readLinesFile(compliance_file):
|
||||
adress, server_hostname = line.split(' ',1)
|
||||
if adress == host:
|
||||
return server_hostname
|
||||
return None
|
||||
|
||||
def add_server_hostname(host, path_to_cert, server_hostname):
|
||||
try:
|
||||
compliance_file = os.path.join(path_to_cert, 'compliance_server_names')
|
||||
if not os.path.isfile(compliance_file):
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.close()
|
||||
temp_file = ''
|
||||
find_flag = False
|
||||
for line in readLinesFile(compliance_file):
|
||||
adress, temp_server_hostname = line.split(' ',1)
|
||||
if adress == host:
|
||||
temp_file += "%s %s\n" %(adress, server_hostname)
|
||||
find_flag = True
|
||||
else:
|
||||
temp_file += line+'\n'
|
||||
if not find_flag:
|
||||
temp_file += "%s %s\n" %(host, server_hostname)
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.write(temp_file)
|
||||
fd.close()
|
||||
return True
|
||||
except Exception, e:
|
||||
print e
|
||||
return False
|
||||
|
||||
def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
|
||||
client_post_auth(client)
|
||||
|
||||
# sym_link = os.path.basename(sys.argv[0])
|
||||
# if sym_link != 'cl-console':
|
||||
# wait_thread.stop()
|
||||
# results = client.service.get_methods(client.sid, 'console')
|
||||
# find_flag = False
|
||||
# if hasattr (results, 'stringArray'):
|
||||
# for _array in results.stringArray:
|
||||
# if _array.string[0] == sym_link:
|
||||
# args.method = _array.string[1]
|
||||
# find_flag = True
|
||||
# break
|
||||
# if not find_flag:
|
||||
# _print (_('Method not found for %s') %sym_link)
|
||||
|
||||
if args.stop_consoled:
|
||||
wait_thread.stop()
|
||||
os.system('cl-consoled --stop')
|
||||
return 0
|
||||
|
||||
if args.session_clean:
|
||||
wait_thread.stop()
|
||||
session_clean(client)
|
||||
|
||||
if args.session_info or args.session_num_info:
|
||||
wait_thread.stop()
|
||||
client_session_info(client, args.session_num_info)
|
||||
return 0
|
||||
|
||||
if args.session_list:
|
||||
wait_thread.stop()
|
||||
client_session_list(client)
|
||||
return 0
|
||||
|
||||
if args.list_pid:
|
||||
wait_thread.stop()
|
||||
if args.dump:
|
||||
from pid_information import client_pid_info
|
||||
client_pid_info(client)
|
||||
else:
|
||||
from pid_information import client_list_pid
|
||||
client_list_pid(client)
|
||||
return 0
|
||||
|
||||
try:
|
||||
client.frame_period = clVarsCore.Get('core.cl_core_get_frame_period')
|
||||
except:
|
||||
client.frame_period = 2
|
||||
|
||||
if args.pid_res:
|
||||
wait_thread.stop()
|
||||
mr = get_entire_message_receiver(client, args.pid_res)
|
||||
if mr:
|
||||
mr.get_messages()
|
||||
if not args.keep_result:
|
||||
client.service.clear_pid_cache(client.sid, args.pid_res)
|
||||
return 0
|
||||
else:
|
||||
return 1
|
||||
|
||||
if args.pid_kill:
|
||||
wait_thread.stop()
|
||||
from pid_information import client_pid_kill
|
||||
return client_pid_kill(client, args.pid_kill)
|
||||
|
||||
retCode = 0
|
||||
if not args.method:
|
||||
wait_thread.stop()
|
||||
client_list_methods(client)
|
||||
return 1
|
||||
|
||||
elif args.method and args.help:
|
||||
view_params = get_view_params(client, args.method + '_view',
|
||||
step = None, expert = True,
|
||||
onlyhelp = True)
|
||||
view = get_view(client, args.method, client.sid, view_params)
|
||||
wait_thread.stop()
|
||||
sys.stdout.write("\b")
|
||||
sys.stdout.flush()
|
||||
method_parser = get_method_argparser(view, args)
|
||||
method_parser.print_help()
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
|
||||
else:
|
||||
method_result = call_method(client, args, unknown_args, wait_thread)
|
||||
mr = get_message_receiver(client)
|
||||
if method_result:
|
||||
client.no_progress = args.no_progress
|
||||
try:
|
||||
mr.analysis(method_result)
|
||||
#analysis(client, client.sid, method_result)
|
||||
except urllib2.URLError, e:
|
||||
_print (e)
|
||||
except KeyboardInterrupt:
|
||||
try:
|
||||
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')
|
||||
elif result == -1:
|
||||
print _("Certificate not found on the server")
|
||||
elif result == -2:
|
||||
print _("Session not matching your certificate")
|
||||
elif result == 1:
|
||||
print _("Failed to terminate the process")
|
||||
mr.analysis(method_result)
|
||||
except Exception, e:
|
||||
_print(e.message)
|
||||
|
||||
try:
|
||||
mess = method_result[0][0]
|
||||
pid = int(mess.message)
|
||||
except:
|
||||
return 1
|
||||
retCode = \
|
||||
1 if int(client.service.pid_info(client.sid,pid)[0][1]) else 0
|
||||
if not args.keep_result:
|
||||
client.service.clear_pid_cache(client.sid, pid)
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
wait_thread.stop()
|
||||
return retCode
|
||||
|
||||
def main(wait_thread):
|
||||
parser = parse()
|
||||
args, unknown_args = parser.parse_known_args()
|
||||
wait_thread.start()
|
||||
|
||||
# if os.path.basename(sys.argv[0]) != 'cl-console':
|
||||
# args.method = '_temp_'
|
||||
# args.host = 'localhost'
|
||||
|
||||
if not args.method and args.help:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
parser.print_help()
|
||||
return 0
|
||||
|
||||
if not args.method:
|
||||
if unknown_args:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.FATAL)
|
||||
logging.getLogger('sudsds.client').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.transport').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.transport.http').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.umx.typed').setLevel(logging.ERROR)
|
||||
|
||||
clVarsCore = DataVarsCore()
|
||||
clVarsCore.importCore()
|
||||
clVarsCore.flIniFile()
|
||||
|
||||
homePath = clVarsCore.Get('ur_home_path')
|
||||
|
||||
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)
|
||||
|
||||
for dirs in ['', 'ca', 'trusted']:
|
||||
dir_path = os.path.join(path_to_cert, dirs)
|
||||
if not os.path.isdir(dir_path):
|
||||
if not makeDirectory(dir_path):
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
print _("Failed to create directory %s") %dir_path
|
||||
return 1
|
||||
|
||||
if args.update_crl:
|
||||
wait_thread.stop()
|
||||
getCRL = threading.Thread(target=get_CRL, args = (path_to_cert, ))
|
||||
getCRL.start()
|
||||
getCRL.join()
|
||||
print 'GRL updated'
|
||||
return 0
|
||||
|
||||
if args.by_host:
|
||||
wait_thread.stop()
|
||||
client_post_request (path_to_cert, args)
|
||||
return 0
|
||||
if args.from_host:
|
||||
wait_thread.stop()
|
||||
client_get_cert (path_to_cert, args)
|
||||
return 0
|
||||
|
||||
url = "https://%s:%d/?wsdl" %(host, port)
|
||||
|
||||
clear()
|
||||
serv_hostname = get_server_hostname(host, path_to_cert)
|
||||
get_name_flag = False
|
||||
if serv_hostname:
|
||||
Connect_Error = 1
|
||||
crypto_Error = 0
|
||||
client, Connect_Error, crypto_Error, passwd_flag, e = \
|
||||
connect_with_cert (serv_hostname, path_to_cert, url, args,
|
||||
wait_thread, clVarsCore, crypto_Error, Connect_Error)
|
||||
if not wait_thread.isAlive():
|
||||
wait_thread = StoppableThread()
|
||||
wait_thread.start()
|
||||
get_name_flag = True
|
||||
if Connect_Error:
|
||||
if crypto_Error and passwd_flag:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
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
|
||||
get_name_flag = False
|
||||
|
||||
if get_name_flag:
|
||||
try:
|
||||
client.port = port
|
||||
return_val = 1
|
||||
try:
|
||||
return_val = https_server(client, args, unknown_args, url, \
|
||||
clVarsCore, wait_thread)
|
||||
except urllib2.URLError, e:
|
||||
print _('Error: '), e
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n'+'\033[31m * \033[0m'
|
||||
print red + _("Manually interrupted")
|
||||
except Exception, e:
|
||||
wait_thread.stop()
|
||||
if type(e.message) != int:
|
||||
if e.message:
|
||||
print e.message
|
||||
elif e.args:
|
||||
print e
|
||||
# tb.print_exc()
|
||||
return 1
|
||||
wait_thread.stop()
|
||||
return return_val
|
||||
except WebFault, f:
|
||||
print _("Exception: %s") %f
|
||||
_print (f.fault)
|
||||
except TransportError, 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
|
||||
tb.print_exc()
|
||||
wait_thread.stop()
|
||||
|
||||
try:
|
||||
client = Client_suds(url, \
|
||||
transport = HTTPSClientCertTransport(None,None, path_to_cert))
|
||||
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!'
|
||||
del (client)
|
||||
except urllib2.URLError, e:
|
||||
wait_thread.stop()
|
||||
print '\b' + _('Failed to connect')+':', e
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n'+'\033[31m * \033[0m'
|
||||
print red + _("Manually interrupted")
|
||||
|
||||
try:
|
||||
import glob
|
||||
all_cert_list = glob.glob(os.path.join(path_to_cert, '*.crt'))
|
||||
fit_cert_list = []
|
||||
for client_cert_path in all_cert_list:
|
||||
client_cert = client_cert_path.replace(path_to_cert, '')
|
||||
client_cert_name = client_cert.replace('.crt', '')
|
||||
if server_host_name.endswith(client_cert_name):
|
||||
fit_cert_list.append(client_cert_name)
|
||||
fit_cert_list.sort(key = len)
|
||||
Connect_Error = 1
|
||||
crypto_Error = 0
|
||||
e = None
|
||||
|
||||
for i in range (0, len(fit_cert_list)):
|
||||
cert_name = fit_cert_list.pop()
|
||||
client, Connect_Error, crypto_Error, passwd_flag, e = \
|
||||
connect_with_cert (cert_name, path_to_cert, url, args,
|
||||
wait_thread, clVarsCore, crypto_Error, Connect_Error)
|
||||
if not wait_thread.isAlive():
|
||||
wait_thread = StoppableThread()
|
||||
wait_thread.start()
|
||||
|
||||
if Connect_Error == 0:
|
||||
break
|
||||
|
||||
#If the certificate file misses
|
||||
if Connect_Error:
|
||||
if crypto_Error and passwd_flag:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
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
|
||||
return 1
|
||||
|
||||
CERT_FILE = None
|
||||
CERT_KEY = None
|
||||
client = Client_suds(url, transport = HTTPSClientCertTransport \
|
||||
(CERT_KEY, CERT_FILE, path_to_cert))
|
||||
client.wsdl.services[0].setlocation(url)
|
||||
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
|
||||
|
||||
client.port = port
|
||||
return_val = 1
|
||||
try:
|
||||
return_val = https_server(client, args, unknown_args, url, \
|
||||
clVarsCore, wait_thread)
|
||||
except urllib2.URLError, e:
|
||||
print _('Error: '), e
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n'+'\033[31m * \033[0m'
|
||||
print red + _("Manually interrupted")
|
||||
except Exception, e:
|
||||
wait_thread.stop()
|
||||
if type(e.message) != int:
|
||||
if e.message:
|
||||
print e.message
|
||||
elif e.args:
|
||||
print e
|
||||
# tb.print_exc()
|
||||
return 1
|
||||
wait_thread.stop()
|
||||
return return_val
|
||||
#----------------------------------------------------
|
||||
except WebFault, f:
|
||||
print _("Exception: %s") %f
|
||||
_print (f.fault)
|
||||
except TransportError, 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
|
||||
tb.print_exc()
|
||||
wait_thread.stop()
|
@ -0,0 +1,94 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2013 Calculate Ltd. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 sys
|
||||
import socket
|
||||
from M2Crypto import RSA, X509, EVP, m2
|
||||
from calculate.lib.datavars import DataVars
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('cl_console3',sys.modules[__name__])
|
||||
|
||||
def passphrase_callback(v):
|
||||
if type(v) == int or not v:
|
||||
return None
|
||||
return str(v)
|
||||
|
||||
def generateRSAKey():
|
||||
return RSA.gen_key(2048, m2.RSA_F4)
|
||||
|
||||
def makePKey(key):
|
||||
pkey = EVP.PKey()
|
||||
pkey.assign_rsa(key)
|
||||
return pkey
|
||||
|
||||
def makeRequest(pubkey, pkey, serv_host, auto = False):
|
||||
""" create query to the signing on server """
|
||||
req = X509.Request()
|
||||
# Seems to default to 0, but we can now set it as well, so just API test
|
||||
req.set_version(req.get_version())
|
||||
req.set_pubkey(pkey)
|
||||
name = X509.X509_Name()
|
||||
if auto:
|
||||
c = 'n'
|
||||
else:
|
||||
c = raw_input (_("Enter the certificate data manually? y/[n]: "))
|
||||
# Get HostName
|
||||
host_name = socket.getfqdn()
|
||||
list_host_name = host_name.split('.')
|
||||
result_host_name = list_host_name[0]+"@"+serv_host
|
||||
# Get username
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
username = clVars.Get('ur_fullname')
|
||||
# Get language
|
||||
lang = clVars.Get('os_locale_locale')[:2]
|
||||
if c.lower() in ['y', 'yes']:
|
||||
#if serv_host in host_name:
|
||||
#host_name = host_name.replace('.'+serv_host, '')
|
||||
#list_host_name = host_name.split('.')
|
||||
#result_host_name = \
|
||||
#list_host_name[len(list_host_name)-1]+"@"+serv_host
|
||||
#else:
|
||||
#host_name = socket.getfqdn()
|
||||
name.CN = raw_input (_('Host Name [%s]: ') %result_host_name)
|
||||
if name.CN in ['', None]:
|
||||
name.CN = result_host_name
|
||||
|
||||
name.OU = raw_input (_('User Name [%s]: ') %username)
|
||||
if name.OU in ['', None]:
|
||||
name.OU = username
|
||||
name.O = raw_input (_('Organization Name: '))
|
||||
name.L = raw_input (_('Network address (hostname or IP) [%s]: ')\
|
||||
%host_name)
|
||||
name.ST = raw_input (_('City: '))
|
||||
name.C = raw_input (_('Country (2 characters): [%s]') %lang)
|
||||
if not name.C:
|
||||
name.C = lang
|
||||
else:
|
||||
name.CN = result_host_name # Имя сертификата (Common Name);
|
||||
name.OU = username # Название отдела (Organization Unit);
|
||||
name.O = 'My Company'# Название организации (Organization Name);
|
||||
name.L = host_name # Название города (Locality Name);
|
||||
name.ST = 'My State'# Название региона (State Name);
|
||||
name.C = lang # Двухсимвольный код страны (Country);
|
||||
req.set_subject_name(name)
|
||||
|
||||
ext1 = X509.new_extension('Comment', 'Auto Generated')
|
||||
extstack = X509.X509_Extension_Stack()
|
||||
extstack.push(ext1)
|
||||
req.add_extensions(extstack)
|
||||
req.sign(pkey, 'md5')
|
||||
return req
|
@ -0,0 +1,139 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2013 Calculate Ltd. http://www.calculate-linux.org
|
||||
#
|
||||
# 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.
|
||||
|
||||
from function import get_sid
|
||||
import sys
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('cl_console3',sys.modules[__name__])
|
||||
client_types = "console"
|
||||
#client_types = "gui"
|
||||
|
||||
def pid_inf(client, sid, pids):
|
||||
""" get and show information about process """
|
||||
for pid in pids:
|
||||
s = client.service.pid_info(sid, pid)
|
||||
if s == "":
|
||||
print _("PID not found")
|
||||
return 1
|
||||
if s[0][0] == "Permission denied":
|
||||
print _("Permission denied")
|
||||
return 1
|
||||
|
||||
_print ('\n', _(u"Process name: %s") %s[0][4])
|
||||
print _(u"Process ID: %s") %s[0][0]
|
||||
_print (_(u"%s: process started") %s[0][2])
|
||||
if s[0][1] == '1':
|
||||
print _(u"Process active")
|
||||
elif s[0][1] == '0':
|
||||
print _(u"Process completed")
|
||||
else:
|
||||
print _(u"Process killed")
|
||||
return 0
|
||||
|
||||
def client_list_pid(client):
|
||||
""" get all process id for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid = sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print red + _("PIDs not found for this session!")
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
print green + "pid - %d" %i
|
||||
except:
|
||||
print red + _("Error fetching the PID list from the server")
|
||||
return 1
|
||||
return len(list_pid[0])
|
||||
|
||||
def gen_pid_ls(client):
|
||||
""" generation list with pid for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
pid_ls = []
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid = sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print _("PIDs not found for this session!")
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
pid_ls.append(i)
|
||||
except:
|
||||
print _("Error fetching the PID list from the server")
|
||||
return 0
|
||||
return pid_ls
|
||||
|
||||
def client_pid_info(client):
|
||||
""" get information about selected process (or about all) """
|
||||
# try:
|
||||
sid = get_sid(client.SID_FILE)
|
||||
pid_ls = gen_pid_ls(client)
|
||||
if pid_ls:
|
||||
pid_inf(client, sid, pid_ls)
|
||||
# except:
|
||||
# print _("Error get data")
|
||||
# return 1
|
||||
# return 0
|
||||
|
||||
def client_list_methods(client):
|
||||
""" get & show all available methods for this certificate """
|
||||
DAT = 0 # Access to data soap structure
|
||||
RES = 0 # Access to result
|
||||
COM = 0 # Getting command line
|
||||
METH = 1 # Getting method line
|
||||
TR_METH = 3 # Translate method name
|
||||
results = client.service.get_methods(client.sid, client_types)
|
||||
if not results:
|
||||
print _('No methods available')
|
||||
return 1
|
||||
try:
|
||||
if results[DAT][RES][RES][COM] == '0':
|
||||
print _('No methods available')
|
||||
return 1
|
||||
except:
|
||||
pass
|
||||
print _("You can execute:"), _('use option'), '--method'
|
||||
group_dict = {}
|
||||
for group in results.stringArray:
|
||||
if len (group.string) == 4:
|
||||
group_dict[group.string[METH]] = group.string[TR_METH]
|
||||
if len (group.string) == 3:
|
||||
group_dict[group.string[METH]] = group.string[TR_METH-1]
|
||||
sort_keys = group_dict.keys()
|
||||
sort_keys.sort()
|
||||
for key in sort_keys:
|
||||
print " %s - %s" % (key, group_dict[key])
|
||||
|
||||
def client_pid_kill(client, pid):
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
result = client.service.pid_kill(pid, sid)
|
||||
if result == 0:
|
||||
print _("Process completed")
|
||||
elif result == 2:
|
||||
print _("Process killed")
|
||||
elif result == 3:
|
||||
print _("Process not found")
|
||||
elif result == -1:
|
||||
print _("Certificate not found on the server")
|
||||
elif result == -2:
|
||||
print _("Session not matching your certificate")
|
||||
elif result == 1:
|
||||
print _("Failed to terminate the process")
|
||||
return 0
|
@ -0,0 +1,117 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2013 Calculate Ltd. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 sys
|
||||
from function import get_sid
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('cl_console3',sys.modules[__name__])
|
||||
|
||||
def client_del_sid(client):
|
||||
""" delete this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
try:
|
||||
s = client.service.del_sid(sid)
|
||||
|
||||
if s[0][0] == "-1":
|
||||
print _("No access to the file!")
|
||||
return -1
|
||||
if s[0][0] == "1":
|
||||
print _("Failed to obtain certificate data!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
_print (_("%s: permission denied") % s[1][1])
|
||||
return -3
|
||||
|
||||
if s[0][0] == '0':
|
||||
fi = open(client.SID_FILE, 'w')
|
||||
fi.write('0')
|
||||
fi.close()
|
||||
print _("SID deleted!")
|
||||
except:
|
||||
print _("SID deletion error on the server")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def sid_inf(client, sid):
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
""" get information about selected session """
|
||||
s = client.service.sid_info(sid)
|
||||
if s[0][0] == "-1":
|
||||
print red + _("Session non registered on the server!")
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print red + _("Failed to obtain certificate data!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print red + _("%s: permission denied") % s[0][1]
|
||||
return -3
|
||||
|
||||
print _('Session information: ')
|
||||
print green + _(u"Session number: %s") %sid
|
||||
print green + _(u"Certificate number: %s") %s[0][0]
|
||||
_print (green + _(u"Certificate issued on %s") %s[0][1])
|
||||
print green + "ip - %s" %s[0][2]
|
||||
print green + "MAC - %s\n" %s[0][3]
|
||||
return 0
|
||||
|
||||
def client_session_info(client, sid = None):
|
||||
""" select session for get information """
|
||||
try:
|
||||
select_sid = sid if sid else client.sid
|
||||
sid_inf(client, select_sid)
|
||||
except Exception, e:
|
||||
if type (e.message) == tuple and len(e.message) == 2 \
|
||||
and e.message[1] == 'Forbidden':
|
||||
print _("Access forbidden!")
|
||||
else:
|
||||
print e
|
||||
return 1
|
||||
|
||||
def client_session_list(client):
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
try:
|
||||
res = client.service.get_sessions(client.sid)
|
||||
except Exception, e:
|
||||
if type (e.message) == tuple and len(e.message) == 2 \
|
||||
and e.message[1] == 'Forbidden':
|
||||
print _("Access forbidden!")
|
||||
else:
|
||||
print e
|
||||
return 1
|
||||
if hasattr (res, 'string'):
|
||||
if res.string:
|
||||
print _('Active sessions on the server: ')
|
||||
for session_id in res.string:
|
||||
print green + session_id
|
||||
print
|
||||
return 0
|
||||
print red + _('No active sessions on the server')
|
||||
|
||||
def session_clean(client):
|
||||
try:
|
||||
res = client.service.clear_session_cache(client.sid)
|
||||
except Exception, e:
|
||||
if type (e.message) == tuple and len(e.message) == 2 \
|
||||
and e.message[1] == 'Forbidden':
|
||||
print _("Access forbidden!")
|
||||
else:
|
||||
print e
|
||||
if res:
|
||||
print _('Error clearing the session cache')
|
||||
else:
|
||||
print _('Session cache cleared')
|
@ -1,629 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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.
|
||||
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
|
||||
import traceback as tb
|
||||
import time
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
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
|
||||
|
||||
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,
|
||||
get_view_params, parse_error)
|
||||
from calculate.lib.utils.files import makeDirectory, readLinesFile
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
from M2Crypto import BIO
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_console3', sys.modules[__name__])
|
||||
|
||||
|
||||
def get_message_receiver(client):
|
||||
return MessageReceiver(client, MessageDispatcher(Methods()), Display())
|
||||
|
||||
|
||||
def get_entire_message_receiver(client, pid):
|
||||
return MessageReceiver.from_entire(client, pid,
|
||||
MessageDispatcher(Methods()), Display())
|
||||
|
||||
|
||||
def client_signal(client):
|
||||
Vars = DataVarsCore()
|
||||
Vars.importCore()
|
||||
Vars.flIniFile()
|
||||
try:
|
||||
client_active = Vars.Get('core.cl_core_client_active_period')
|
||||
except:
|
||||
client_active = 15
|
||||
while True:
|
||||
sid = int(client.get_sid())
|
||||
try:
|
||||
client.service.active_client(sid)
|
||||
except:
|
||||
print(_('no connection to the server!'))
|
||||
raise Exception(1)
|
||||
time.sleep(float(client_active))
|
||||
|
||||
|
||||
class StoppableThread(threading.Thread):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._thread_stopped = threading.Event()
|
||||
self._pause = threading.Event()
|
||||
self._paused = threading.Event()
|
||||
|
||||
def run(self):
|
||||
l = ['|', '/', '-', '\\', '|', '/', '-', '\\']
|
||||
while True:
|
||||
for i in l:
|
||||
sys.stdout.write("\r\r" + i)
|
||||
sys.stdout.flush()
|
||||
time.sleep(.1)
|
||||
while self.paused() and not self.stopped():
|
||||
self._paused.set()
|
||||
if self.stopped():
|
||||
sys.stdout.write("\b")
|
||||
sys.stdout.flush()
|
||||
return 0
|
||||
|
||||
def pause(self):
|
||||
self._pause.set()
|
||||
while not self._paused.is_set():
|
||||
self._paused.clear()
|
||||
sys.stdout.write("\r")
|
||||
sys.stdout.flush()
|
||||
|
||||
def resume(self):
|
||||
self._pause.clear()
|
||||
|
||||
def stop(self):
|
||||
self._thread_stopped.set()
|
||||
|
||||
def stopped(self):
|
||||
return self._thread_stopped.isSet()
|
||||
|
||||
def paused(self):
|
||||
return self._pause.isSet()
|
||||
|
||||
|
||||
def connect_with_cert(cert, path_to_cert, url, args, wait_thread, clVarsCore,
|
||||
crypto_Error, Connect_Error):
|
||||
flag_thread_start = False
|
||||
cert_name = cert
|
||||
CERT_FILE = os.path.join(path_to_cert, cert_name + '.crt')
|
||||
CERT_KEY = os.path.join(path_to_cert, cert_name + '.key')
|
||||
if not os.path.isfile(CERT_FILE) or not os.path.isfile(CERT_KEY):
|
||||
Connect_Error = 1
|
||||
return None, 1, crypto_Error, False, None
|
||||
client = None
|
||||
|
||||
rsa_password = args.cert_passwd or ""
|
||||
with open(CERT_KEY) as inf:
|
||||
if 'ENCRYPTED' in inf.readline():
|
||||
if not args.cert_passwd:
|
||||
Connect_Error = 1
|
||||
return None, 1, crypto_Error, False, _("RSA key contain ENCRYPTED. Use '--cert-passwd' to provide password")
|
||||
try:
|
||||
bio = M2Crypto.BIO.openfile(CERT_KEY)
|
||||
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(), lambda *unused: bytes(rsa_password, 'utf-8'))
|
||||
except SystemError as e:
|
||||
Connect_Error = 1
|
||||
return None, 1, crypto_Error, False, _("Failed to read rsa key")
|
||||
store_passwd = None
|
||||
if not rsa:
|
||||
try:
|
||||
port = args.port or clVarsCore.Get('core.cl_core_port')
|
||||
store_passwd = get_password_from_daemon(args.host, port, wait_thread)
|
||||
except TypeError:
|
||||
return None, 1, crypto_Error, False, _("Failed to get password from daemon or provided password is incorrect")
|
||||
key_passwd = store_passwd
|
||||
er = None
|
||||
try:
|
||||
ca_certs = os.path.join(path_to_cert, 'ca/ca_root.crt')
|
||||
client = Client_suds(
|
||||
url, transport=HTTPSClientCertTransport(
|
||||
CERT_KEY, CERT_FILE, path_to_cert, password=key_passwd,
|
||||
ca_certs=ca_certs, wait_thread=wait_thread, rsa_password=bytes(rsa_password, 'utf-8')))
|
||||
if not wait_thread.is_alive():
|
||||
wait_thread = StoppableThread()
|
||||
flag_thread_start = True
|
||||
wait_thread.start()
|
||||
client.wsdl.services[0].setlocation(url)
|
||||
client.set_parameters(path_to_cert, CERT_FILE, CERT_KEY, args.host)
|
||||
wait_thread.stop()
|
||||
client_post_cert(client, clVarsCore)
|
||||
Connect_Error = 0
|
||||
except VerifyError as e:
|
||||
Connect_Error = 1
|
||||
er = e
|
||||
except OpenSSL.crypto.Error as e:
|
||||
Connect_Error = 1
|
||||
crypto_Error = 1
|
||||
er = e
|
||||
except URLError as e:
|
||||
Connect_Error = 1
|
||||
er = e
|
||||
except Exception as e:
|
||||
er = e
|
||||
if e == 3:
|
||||
wait_thread.stop()
|
||||
sys.exit(1)
|
||||
Connect_Error = 1
|
||||
if flag_thread_start:
|
||||
wait_thread.stop()
|
||||
return (client, Connect_Error, crypto_Error,
|
||||
True if store_passwd is not None else False, er)
|
||||
|
||||
|
||||
def get_server_hostname(host, path_to_cert):
|
||||
compliance_file = os.path.join(path_to_cert, 'compliance_server_names')
|
||||
if not os.path.isfile(compliance_file):
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.close()
|
||||
for line in readLinesFile(compliance_file):
|
||||
adress, server_hostname = line.split(' ', 1)
|
||||
if adress == host:
|
||||
return server_hostname
|
||||
return None
|
||||
|
||||
|
||||
def add_server_hostname(host, path_to_cert, server_hostname):
|
||||
try:
|
||||
compliance_file = os.path.join(path_to_cert, 'compliance_server_names')
|
||||
if not os.path.isfile(compliance_file):
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.close()
|
||||
temp_file = ''
|
||||
find_flag = False
|
||||
for line in readLinesFile(compliance_file):
|
||||
adress, temp_server_hostname = line.split(' ', 1)
|
||||
if adress == host:
|
||||
temp_file += "%s %s\n" % (adress, server_hostname)
|
||||
find_flag = True
|
||||
else:
|
||||
temp_file += line + '\n'
|
||||
if not find_flag:
|
||||
temp_file += "%s %s\n" % (host, server_hostname)
|
||||
fd = open(compliance_file, 'w')
|
||||
fd.write(temp_file)
|
||||
fd.close()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return False
|
||||
|
||||
|
||||
def https_server(client, args, unknown_args, url, clVarsCore, wait_thread):
|
||||
client_post_auth(client)
|
||||
|
||||
if args.stop_consoled:
|
||||
wait_thread.stop()
|
||||
os.system('cl-consoled --stop')
|
||||
return 0
|
||||
|
||||
if args.session_clean:
|
||||
wait_thread.stop()
|
||||
session_clean(client)
|
||||
|
||||
if args.session_info or args.session_num_info:
|
||||
wait_thread.stop()
|
||||
client_session_info(client, args.session_num_info)
|
||||
return 0
|
||||
|
||||
if args.session_list:
|
||||
wait_thread.stop()
|
||||
client_session_list(client)
|
||||
return 0
|
||||
|
||||
if args.pid_res == "list":
|
||||
from .pid_information import client_pid_info
|
||||
wait_thread.stop()
|
||||
client_pid_info(client, wait_thread)
|
||||
return 0
|
||||
|
||||
try:
|
||||
client.frame_period = clVarsCore.Get('core.cl_core_get_frame_period')
|
||||
except:
|
||||
client.frame_period = 2
|
||||
|
||||
if args.pid_res:
|
||||
wait_thread.stop()
|
||||
if not args.pid_res.isdigit():
|
||||
print(_("Wrong PID"))
|
||||
return 1
|
||||
mr = get_entire_message_receiver(client, int(args.pid_res))
|
||||
if mr:
|
||||
mr.get_messages()
|
||||
if not args.keep_result:
|
||||
client.service.clear_pid_cache(client.sid, int(args.pid_res))
|
||||
return 0
|
||||
else:
|
||||
return 1
|
||||
|
||||
if args.pid_kill:
|
||||
wait_thread.stop()
|
||||
from .pid_information import client_pid_kill
|
||||
|
||||
return client_pid_kill(client, args.pid_kill)
|
||||
|
||||
retCode = 0
|
||||
if not args.method:
|
||||
wait_thread.stop()
|
||||
client_list_methods(client)
|
||||
return 1
|
||||
|
||||
elif args.method and args.help:
|
||||
# вычислить наличие флага --force
|
||||
method_parser = None
|
||||
try:
|
||||
dispatch_usenew = has_force_arg(unknown_args)
|
||||
while True:
|
||||
view_params = get_view_params(client, args.method + '_view',
|
||||
step=None, expert=True,
|
||||
onlyhelp=True,
|
||||
dispatch_usenew=dispatch_usenew)
|
||||
view = get_view(client, args.method, client.sid, view_params)
|
||||
method_parser = get_method_argparser(view, args)
|
||||
|
||||
_unknown_args = method_parser.fixBoolVariables(unknown_args)
|
||||
|
||||
_args, _unknown_args = method_parser.parse_known_args(
|
||||
_unknown_args)
|
||||
|
||||
if dispatch_usenew == _args.no_questions:
|
||||
break
|
||||
else:
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
dispatch_usenew = _args.no_questions
|
||||
finally:
|
||||
wait_thread.stop()
|
||||
# sys.stdout.write("\b")
|
||||
# sys.stdout.flush()
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
method_parser.print_help()
|
||||
else:
|
||||
method_result = call_method(client, args, unknown_args, wait_thread)
|
||||
mr = get_message_receiver(client)
|
||||
if method_result:
|
||||
client.no_progress = args.no_progress
|
||||
try:
|
||||
mr.analysis(method_result)
|
||||
# analysis(client, client.sid, method_result)
|
||||
except URLError as e:
|
||||
_print(parse_error(e))
|
||||
except KeyboardInterrupt:
|
||||
try:
|
||||
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'))
|
||||
elif result == -1:
|
||||
print(_("Certificate not found on the server"))
|
||||
elif result == -2:
|
||||
print(_("Session not matching your certificate"))
|
||||
elif result == 1:
|
||||
print(_("Failed to terminate the process"))
|
||||
mr.analysis(method_result)
|
||||
except Exception as e:
|
||||
_print(parse_error(e))
|
||||
|
||||
try:
|
||||
mess = method_result[0][0]
|
||||
pid = int(mess.message)
|
||||
except:
|
||||
return 1
|
||||
retCode = 1 if int(
|
||||
client.service.pid_info(client.sid, pid)[0][1]) else 0
|
||||
if not args.keep_result:
|
||||
client.service.clear_pid_cache(client.sid, pid)
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
wait_thread.stop()
|
||||
return retCode
|
||||
|
||||
|
||||
def main(wait_thread):
|
||||
parser = parse()
|
||||
args, unknown_args = parser.parse_known_args(
|
||||
list(unpack_single_opts(sys.argv[1:])))
|
||||
wait_thread.start()
|
||||
|
||||
sym_link = os.path.basename(sys.argv[0])
|
||||
if sym_link != 'cl-console':
|
||||
import calculate.core.server.loaded_methods as loaded_methods
|
||||
|
||||
ob = DataVarsCore()
|
||||
ob.importCore()
|
||||
|
||||
# set var env
|
||||
if not ob.flIniFile():
|
||||
sys.exit(1)
|
||||
# cl_wsdl = ob.Get('cl_wsdl')
|
||||
cl_wsdl = ob.Get('cl_wsdl_available')
|
||||
# создать симлинки на команды
|
||||
from calculate.core.server.func import initialization
|
||||
|
||||
initialization(cl_wsdl)
|
||||
ob.close()
|
||||
if sym_link in loaded_methods.LoadedMethods.conMethods.keys():
|
||||
args.method = loaded_methods.LoadedMethods.conMethods[sym_link][0]
|
||||
args.host = 'localhost'
|
||||
|
||||
if not args.method and args.help:
|
||||
wait_thread.stop()
|
||||
# sys.stdout.write('\r')
|
||||
# sys.stdout.flush()
|
||||
parser.print_help()
|
||||
return 0
|
||||
|
||||
if not args.method:
|
||||
if unknown_args:
|
||||
wait_thread.stop()
|
||||
# sys.stdout.write('\r')
|
||||
# sys.stdout.flush()
|
||||
args = parser.parse_args(
|
||||
list(unpack_single_opts(sys.argv[1:])))
|
||||
|
||||
logging.basicConfig(level=logging.FATAL)
|
||||
logging.getLogger('suds.client').setLevel(logging.FATAL)
|
||||
logging.getLogger('suds.transport').setLevel(logging.FATAL)
|
||||
logging.getLogger('suds.transport.http').setLevel(logging.FATAL)
|
||||
logging.getLogger('suds.umx.typed').setLevel(logging.ERROR)
|
||||
|
||||
clVarsCore = DataVarsCore()
|
||||
clVarsCore.importCore()
|
||||
clVarsCore.flIniFile()
|
||||
|
||||
homePath = clVarsCore.Get('ur_home_path')
|
||||
|
||||
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)
|
||||
|
||||
for dirs in ['', 'ca', 'trusted']:
|
||||
dir_path = os.path.join(path_to_cert, dirs)
|
||||
if not os.path.isdir(dir_path):
|
||||
if not makeDirectory(dir_path):
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
print(_("Failed to create directory %s") % dir_path)
|
||||
return 1
|
||||
|
||||
if args.update_crl:
|
||||
wait_thread.stop()
|
||||
getCRL = threading.Thread(target=get_CRL, args=(path_to_cert,))
|
||||
getCRL.start()
|
||||
getCRL.join()
|
||||
print('CRL updated')
|
||||
return 0
|
||||
|
||||
if args.by_host:
|
||||
wait_thread.stop()
|
||||
client_post_request(path_to_cert, args)
|
||||
return 0
|
||||
if args.from_host:
|
||||
wait_thread.stop()
|
||||
client_get_cert(path_to_cert, args)
|
||||
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)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
clear()
|
||||
serv_hostname = get_server_hostname(host, path_to_cert)
|
||||
get_name_flag = False
|
||||
client = None
|
||||
|
||||
if serv_hostname:
|
||||
Connect_Error = 1
|
||||
crypto_Error = 0
|
||||
client, Connect_Error, crypto_Error, passwd_flag, e = \
|
||||
connect_with_cert(serv_hostname, path_to_cert, url, args,
|
||||
wait_thread, clVarsCore, crypto_Error,
|
||||
Connect_Error)
|
||||
if not wait_thread.is_alive():
|
||||
wait_thread = StoppableThread()
|
||||
wait_thread.start()
|
||||
get_name_flag = True
|
||||
if Connect_Error:
|
||||
if crypto_Error and passwd_flag:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write('\r')
|
||||
sys.stdout.flush()
|
||||
print(_('Invalid password'))
|
||||
# delete password from daemon list
|
||||
clear_password(host, port)
|
||||
elif e:
|
||||
wait_thread.stop()
|
||||
if type(e) != int:
|
||||
print(_('Error: '), e)
|
||||
get_name_flag = False
|
||||
|
||||
if get_name_flag:
|
||||
if client:
|
||||
try:
|
||||
client.port = port
|
||||
return_val = 1
|
||||
try:
|
||||
return_val = https_server(client, args, unknown_args, url,
|
||||
clVarsCore, wait_thread)
|
||||
except URLError as e:
|
||||
print(_('Error: '), e)
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n' + '\033[31m * \033[0m'
|
||||
print(red + _("Manually interrupted"))
|
||||
except Exception as e:
|
||||
wait_thread.stop()
|
||||
if type(e) != int:
|
||||
if e:
|
||||
print(e)
|
||||
elif e.args:
|
||||
print(e)
|
||||
return 1
|
||||
wait_thread.stop()
|
||||
return return_val
|
||||
except WebFault as f:
|
||||
print(_("Exception: %s") % f)
|
||||
_print(f.fault)
|
||||
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 as e:
|
||||
print(_("Exception: %s") % e)
|
||||
tb.print_exc()
|
||||
wait_thread.stop()
|
||||
|
||||
server_host_name = ""
|
||||
try:
|
||||
client = Client_suds(
|
||||
url, transport=HTTPSClientCertTransport(None, None, path_to_cert))
|
||||
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!')
|
||||
del client
|
||||
except URLError as e:
|
||||
wait_thread.stop()
|
||||
print('\b' + _('Failed to connect') + ':', e)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n' + '\033[31m * \033[0m'
|
||||
print(red + _("Manually interrupted"))
|
||||
|
||||
try:
|
||||
import glob
|
||||
|
||||
all_cert_list = glob.glob(os.path.join(path_to_cert, '*.crt'))
|
||||
fit_cert_list = []
|
||||
for client_cert_path in all_cert_list:
|
||||
client_cert = client_cert_path.replace(path_to_cert, '')
|
||||
client_cert_name = client_cert.replace('.crt', '')
|
||||
if server_host_name.endswith(client_cert_name):
|
||||
fit_cert_list.append(client_cert_name)
|
||||
fit_cert_list.sort(key=len)
|
||||
Connect_Error = 1
|
||||
crypto_Error = 0
|
||||
e = None
|
||||
passwd_flag = False
|
||||
|
||||
for i in range(0, len(fit_cert_list)):
|
||||
cert_name = fit_cert_list.pop()
|
||||
client, Connect_Error, crypto_Error, passwd_flag, e = \
|
||||
connect_with_cert(cert_name, path_to_cert, url, args,
|
||||
wait_thread, clVarsCore, crypto_Error,
|
||||
Connect_Error)
|
||||
if not wait_thread.is_alive():
|
||||
wait_thread = StoppableThread()
|
||||
wait_thread.start()
|
||||
|
||||
if Connect_Error == 0:
|
||||
break
|
||||
|
||||
# If the certificate file misses
|
||||
if Connect_Error:
|
||||
if crypto_Error and passwd_flag:
|
||||
wait_thread.stop()
|
||||
# sys.stdout.write('\r')
|
||||
# sys.stdout.flush()
|
||||
print(_('Invalid password'))
|
||||
# delete password from daemon list
|
||||
clear_password(host, port)
|
||||
return 1
|
||||
elif e:
|
||||
wait_thread.stop()
|
||||
if type(e) != int:
|
||||
print(_('Error: '), e)
|
||||
return 1
|
||||
|
||||
CERT_FILE = None
|
||||
CERT_KEY = None
|
||||
client = Client_suds(
|
||||
url, transport=HTTPSClientCertTransport(CERT_KEY, CERT_FILE,
|
||||
path_to_cert))
|
||||
client.wsdl.services[0].setlocation(url)
|
||||
client.set_parameters(path_to_cert, CERT_FILE, CERT_KEY, args.host)
|
||||
|
||||
client.port = port
|
||||
return_val = 1
|
||||
try:
|
||||
return_val = https_server(client, args, unknown_args, url,
|
||||
clVarsCore, wait_thread)
|
||||
except URLError as e:
|
||||
print(_('Error: '), e)
|
||||
except KeyboardInterrupt:
|
||||
wait_thread.stop()
|
||||
red = '\n' + '\033[31m * \033[0m'
|
||||
print(red + _("Manually interrupted"))
|
||||
except Exception as e:
|
||||
wait_thread.stop()
|
||||
if type(e) != int:
|
||||
if e:
|
||||
print(e)
|
||||
elif e.args:
|
||||
print(e)
|
||||
# tb.print_exc()
|
||||
return 1
|
||||
wait_thread.stop()
|
||||
return return_val
|
||||
# ----------------------------------------------------
|
||||
except WebFault as f:
|
||||
print(_("Exception: %s") % f)
|
||||
_print(f.fault)
|
||||
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 as e:
|
||||
print(_("Exception: %s") % e)
|
||||
tb.print_exc()
|
||||
wait_thread.stop()
|
@ -1,628 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 urllib.request as u2
|
||||
if hasattr(u2, "ssl"):
|
||||
u2.ssl._create_default_https_context = u2.ssl._create_unverified_context
|
||||
import os
|
||||
import sys
|
||||
import socket
|
||||
import ssl
|
||||
import OpenSSL
|
||||
import hashlib
|
||||
import M2Crypto
|
||||
from M2Crypto import BIO
|
||||
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 http.client as httplib
|
||||
from suds.transport.http import HttpTransport
|
||||
from .pyopenssl_wrapper import PyOpenSSLSocket
|
||||
from suds.transport import Transport
|
||||
from suds.properties import Unskin
|
||||
from http.cookiejar import CookieJar, DefaultCookiePolicy
|
||||
from logging import getLogger
|
||||
from ..datavars import DataVarsConsole
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
from .sid_func import SessionId
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_console3', sys.modules[__name__])
|
||||
log = getLogger(__name__)
|
||||
flag = 0
|
||||
|
||||
class SUDSHTTPRedirectHandler(u2.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
"""Return a Request or None in response to a redirect.
|
||||
|
||||
This is called by the http_error_30x methods,
|
||||
it was taken from the original Python version and modified
|
||||
to use POST when redirection takes place.
|
||||
This allows a SOAP message to be redirected without a loss
|
||||
of content.
|
||||
"""
|
||||
m = req.get_method()
|
||||
if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
|
||||
or code in (301, 302, 303) and m == "POST"):
|
||||
newurl = newurl.replace(' ', '%20')
|
||||
newheaders = dict((k,v) for k,v in req.headers.items()
|
||||
if k.lower() not in ("content-length", "content-type")
|
||||
)
|
||||
log.debug("Redirecting to %s", newurl)
|
||||
return u2.Request(newurl,
|
||||
data=req.data, # here we pass the original data
|
||||
headers=newheaders,
|
||||
origin_req_host=req.get_origin_req_host(),
|
||||
unverifiable=True,
|
||||
)
|
||||
else:
|
||||
raise u2.HTTPError(req.get_full_url(), code, msg, headers, fp)
|
||||
|
||||
|
||||
# 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):
|
||||
def set_parameters(self, path_to_cert, CERT_FILE, PKEY_FILE, HOST):
|
||||
self.path_to_cert = path_to_cert
|
||||
if not CERT_FILE:
|
||||
CERT_FILE = ''
|
||||
self.CERT_FILE = CERT_FILE
|
||||
self.REQ_FILE = path_to_cert + 'client.csr'
|
||||
self.PKEY_FILE = PKEY_FILE
|
||||
self.SID_FILE = path_to_cert + 'sids'
|
||||
self.SID_LOCK = path_to_cert + 'sids.lock'
|
||||
self.CRL_PATH = path_to_cert + 'ca/crl/'
|
||||
self.HOST = HOST
|
||||
if not os.path.exists(self.CRL_PATH):
|
||||
os.makedirs(self.CRL_PATH)
|
||||
|
||||
|
||||
|
||||
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):
|
||||
"""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
|
||||
self.cert_path = cert_path
|
||||
self.CRL_PATH = os.path.join(cert_path, 'ca/crl/')
|
||||
self.wait_thread = wait_thread
|
||||
|
||||
# get filename store cert server
|
||||
def cert_list(self, host, ca_certs, server_cert):
|
||||
if host == '127.0.0.1':
|
||||
host = 'localhost'
|
||||
if not os.path.exists(self.trusted_path):
|
||||
try:
|
||||
os.makedirs(self.trusted_path)
|
||||
except OSError:
|
||||
pass
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs, "w")
|
||||
fc.close()
|
||||
filename = None
|
||||
try:
|
||||
with open(ca_certs) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split()
|
||||
if len(words) > 1:
|
||||
# if first word...
|
||||
if words[0] == host:
|
||||
filename = words[1]
|
||||
if not filename:
|
||||
return None
|
||||
except:
|
||||
print(_("Certificate not found on the client`s side"))
|
||||
return None
|
||||
try:
|
||||
fd = open(self.trusted_path + filename, 'r')
|
||||
store_cert = fd.read()
|
||||
fd.close()
|
||||
if store_cert == server_cert:
|
||||
return filename
|
||||
except:
|
||||
print(_("Failed to open the file"), self.trusted_path, filename)
|
||||
return None
|
||||
|
||||
def add_all_ca_cert(self, list_ca_certs):
|
||||
# so root cert be first, ca after
|
||||
clVarsCore = DataVarsCore()
|
||||
clVarsCore.importCore()
|
||||
clVarsCore.flIniFile()
|
||||
|
||||
list_ca_certs.reverse()
|
||||
system_ca_db = clVarsCore.Get('core.cl_glob_root_cert')
|
||||
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = clVarsCore.Get('core.cl_client_cert_dir')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_md5 = os.path.join(cl_client_cert_dir, "ca/cert_list")
|
||||
|
||||
user_root_cert = clVarsCore.Get('core.cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
|
||||
for cert in list_ca_certs:
|
||||
if os.path.exists(system_ca_db):
|
||||
if cert in readFile(system_ca_db):
|
||||
continue
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
if cert in readFile(user_root_cert):
|
||||
continue
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(cert.encode("UTF-8"))
|
||||
md5sum = md5.hexdigest()
|
||||
print("\n=================================================")
|
||||
print("md5sum = ", md5sum)
|
||||
|
||||
if not os.path.exists(root_cert_md5):
|
||||
fc = open(root_cert_md5, "w")
|
||||
fc.close()
|
||||
|
||||
filename = None
|
||||
with open(root_cert_md5) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split(' ', 1)
|
||||
if words[0] == md5sum:
|
||||
filename = words[1]
|
||||
if not filename:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
for item in Issuer:
|
||||
if item[0] == b'CN':
|
||||
filename = item[1].decode("UTF-8")
|
||||
|
||||
fc = open(root_cert_md5, "a")
|
||||
fc.write('%s %s\n' % (md5sum, filename))
|
||||
fc.close()
|
||||
|
||||
if not filename:
|
||||
print(_('Field "CN" not found in the certificate!'))
|
||||
return 1
|
||||
|
||||
fd = open(os.path.join(cl_client_cert_dir, 'ca/', filename),
|
||||
'w')
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
|
||||
fa = open(user_root_cert, 'a')
|
||||
fa.write(cert)
|
||||
fa.close()
|
||||
print(_("filename = "), filename)
|
||||
print(_("Certificate added"))
|
||||
else:
|
||||
print(_("The file containing the CA certificate now exists"))
|
||||
get_CRL(cl_client_cert_dir)
|
||||
|
||||
def add_ca_cert(self, cert, list_ca_certs):
|
||||
url = 'https://%s:%s/?wsdl' % (self.host, self.port)
|
||||
client = Client_suds(
|
||||
url, transport=HTTPSClientCertTransport(None, None, self.cert_path))
|
||||
client.wsdl.services[0].setlocation(url)
|
||||
cert = client.service.get_ca()
|
||||
if cert == '1':
|
||||
print(_("Invalid server certificate!"))
|
||||
raise Exception(1)
|
||||
|
||||
if cert == '2':
|
||||
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"))
|
||||
raise Exception(1)
|
||||
print('\n', _("Fingerprint = %s") % certobj.digest('SHA1'))
|
||||
print(_("Serial Number = "), certobj.get_serial_number())
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
print('\n', _("Issuer"))
|
||||
for i in Issuer:
|
||||
print("%s : %s" % (i[0], i[1]))
|
||||
Subject = certobj.get_subject().get_components()
|
||||
print('\n', _("Subject"))
|
||||
for subj in Subject:
|
||||
print("%s : %s" % (subj[0], subj[1]))
|
||||
ans = 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"))
|
||||
|
||||
# add certificate server in trusted
|
||||
def add_server_cert(self, cert):
|
||||
self.wait_thread.stop()
|
||||
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())
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
print('\n' + _("Issuer"))
|
||||
for i in Issuer:
|
||||
print("%s : %s" % (i[0], i[1]))
|
||||
Subject = certobj.get_subject().get_components()
|
||||
print('\n' + _("Subject"))
|
||||
for item in Subject:
|
||||
print("%s : %s" % (item[0], item[1]))
|
||||
|
||||
print('\n' + _('Add this server certificate to trusted (s) or'))
|
||||
print(_('Try to add the CA and root certificates to trusted (c) or'))
|
||||
choice = input(_("Quit (q)? s/c/[q]: "))
|
||||
if choice.lower() in ['s', 'c']:
|
||||
# self.sock = ssl.wrap_socket(sock)
|
||||
ca_certs = os.path.join(self.trusted_path, "cert.list")
|
||||
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs, "w")
|
||||
fc.close()
|
||||
|
||||
if self.host == '127.0.0.1':
|
||||
host = 'localhost'
|
||||
else:
|
||||
host = self.host
|
||||
filename = host
|
||||
fc = open(self.trusted_path + filename, "w")
|
||||
fc.write(cert)
|
||||
fc.close()
|
||||
with open(ca_certs) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split()
|
||||
if len(words) > 1:
|
||||
# if first word...
|
||||
if words[0] == host:
|
||||
return 0
|
||||
# Open file with compliance server certificates and server hostname
|
||||
fcl = open(ca_certs, "a")
|
||||
fcl.write(host + ' ' + filename + '\n')
|
||||
fcl.close()
|
||||
if choice.lower() != 'c':
|
||||
return 3
|
||||
if choice.lower() == 'c':
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
cl_client_cert_dir = clVars.Get('core.cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_dir = os.path.join(cl_client_cert_dir, "ca")
|
||||
|
||||
if not os.path.exists(root_cert_dir):
|
||||
try:
|
||||
os.makedirs(root_cert_dir)
|
||||
except OSError:
|
||||
print(_("Failed to create directory %s") % root_cert_dir)
|
||||
raise Exception(1)
|
||||
|
||||
print('\n' + _("Add the CA and root certificates"))
|
||||
self.list_ca_certs = []
|
||||
self.add_ca_cert(cert, self.list_ca_certs)
|
||||
return 3
|
||||
elif not choice.lower() in ['c', 's']:
|
||||
return 4
|
||||
|
||||
def connect_trusted_root(self, sock, root_cert, crl_certs):
|
||||
self.ca_path = self.cert_path + "ca/"
|
||||
server_cert = ssl.get_server_certificate(addr=(self.host, self.port))
|
||||
global flag
|
||||
|
||||
if self.cert_file:
|
||||
f = verify(server_cert, crl_certs, flag)
|
||||
if not f:
|
||||
flag = 1
|
||||
elif f == 1:
|
||||
raise Exception(1)
|
||||
else:
|
||||
import time
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
try:
|
||||
if self.FORCE_SSL_VERSION:
|
||||
add = {'ssl_version': self.FORCE_SSL_VERSION}
|
||||
else:
|
||||
add = {}
|
||||
add['cert_reqs'] = ssl.CERT_REQUIRED
|
||||
add['keyobj'] = self.keyobj
|
||||
add['certobj'] = self.certobj
|
||||
add['keyfile'] = self.key_file
|
||||
add['certfile'] = self.cert_file
|
||||
self.sock = PyOpenSSLSocket(sock, ca_certs=self.ca_certs, **add)
|
||||
return 0
|
||||
except:
|
||||
return 1
|
||||
|
||||
def connect_trusted_server(self, sock, crl_certs):
|
||||
self.trusted_path = self.cert_path + "trusted/"
|
||||
ca_cert_list = self.trusted_path + "cert.list"
|
||||
server_cert = ssl.get_server_certificate(addr=(self.host, self.port))
|
||||
global flag
|
||||
if self.cert_file:
|
||||
f = verify(server_cert, crl_certs, flag)
|
||||
if not f:
|
||||
flag = 1
|
||||
elif f == 1:
|
||||
raise Exception(1)
|
||||
# if not hasattr(HTTPSClientCertTransport, 'filename') or \
|
||||
# HTTPSClientCertTransport.filename == None:
|
||||
HTTPSClientCertTransport.filename = self.cert_list(
|
||||
self.host, ca_cert_list, server_cert)
|
||||
if HTTPSClientCertTransport.filename:
|
||||
try:
|
||||
if self.FORCE_SSL_VERSION:
|
||||
add = {'ssl_version': self.FORCE_SSL_VERSION}
|
||||
else:
|
||||
add = {}
|
||||
add['cert_reqs'] = ssl.CERT_NONE
|
||||
add['keyobj'] = self.keyobj
|
||||
add['certobj'] = self.certobj
|
||||
add['keyfile'] = self.key_file
|
||||
add['certfile'] = self.cert_file
|
||||
self.sock = PyOpenSSLSocket(sock, ca_certs=None, **add)
|
||||
return 0
|
||||
except Exception:
|
||||
HTTPSClientCertTransport.filename = None
|
||||
return 1
|
||||
else:
|
||||
return self.add_server_cert(server_cert)
|
||||
|
||||
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()
|
||||
|
||||
self.Vars = DataVarsConsole()
|
||||
self.Vars.importConsole()
|
||||
self.Vars.flIniFile()
|
||||
user_root_cert = self.Vars.Get('core.cl_user_root_cert')
|
||||
homePath = self.Vars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
result_user_root = 1
|
||||
|
||||
while True:
|
||||
if os.path.exists(user_root_cert):
|
||||
result_user_root = self.connect_trusted_root(sock,
|
||||
user_root_cert,
|
||||
self.CRL_PATH)
|
||||
if result_user_root == 1:
|
||||
glob_root_cert = self.Vars.Get('core.cl_glob_root_cert')
|
||||
result_root_con = 1
|
||||
if os.path.exists(glob_root_cert):
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout,
|
||||
self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
result_root_con = self.connect_trusted_root(sock,
|
||||
glob_root_cert,
|
||||
self.CRL_PATH)
|
||||
if result_root_con == 1:
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout,
|
||||
self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
result_server_con = self.connect_trusted_server(
|
||||
sock, self.CRL_PATH)
|
||||
if result_server_con in [1, 2]:
|
||||
raise Exception(1)
|
||||
elif result_server_con == 3:
|
||||
continue
|
||||
elif result_server_con == 4:
|
||||
print(_('This server is not trusted'))
|
||||
self.wait_thread.stop()
|
||||
sys.exit(1)
|
||||
elif result_root_con == 2:
|
||||
raise Exception(1)
|
||||
elif result_user_root == 2:
|
||||
raise Exception(1)
|
||||
break
|
||||
|
||||
|
||||
|
||||
class CheckingClientHTTPSHandler(u2.HTTPSHandler):
|
||||
def __init__(self, cert_path, 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)
|
||||
self.cert_path = cert_path
|
||||
|
||||
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 CheckingClientHTTPSConnection(self.cert_path, *args, **new_kw)
|
||||
return self.do_open(open, req)
|
||||
|
||||
https_request = u2.AbstractHTTPHandler.do_request_
|
||||
|
||||
|
||||
class HTTPSClientCertTransport(HttpTransport):
|
||||
def __init__(self, key, cert, path_to_cert, password=None,
|
||||
ca_certs=None, cert_verifier=None,
|
||||
client_keyfile=None, client_certfile=None,
|
||||
client_keyobj=None, client_certobj=None,
|
||||
cookie_callback=None, user_agent_string=None,
|
||||
wait_thread=None, rsa_password=None, **kwargs):
|
||||
Transport.__init__(self)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = path_to_cert
|
||||
self.rsa_password = rsa_password or b""
|
||||
if key:
|
||||
with open(cert) as cert_file:
|
||||
client_certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, cert_file.read())
|
||||
if password:
|
||||
with open(key) as key_file:
|
||||
client_keyobj = OpenSSL.crypto.load_privatekey \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, key_file.read(),
|
||||
password)
|
||||
else:
|
||||
import M2Crypto
|
||||
bio = M2Crypto.BIO.openfile(key)
|
||||
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(),lambda *unused: self.rsa_password)
|
||||
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(), passphrase=self.rsa_password or None)
|
||||
|
||||
Unskin(self.options).update(kwargs)
|
||||
self.cookiejar = CookieJar(DefaultCookiePolicy())
|
||||
self.cookie_callback = cookie_callback
|
||||
self.user_agent_string = user_agent_string
|
||||
log.debug("Proxy: %s", self.options.proxy)
|
||||
|
||||
|
||||
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
|
||||
# proxy_handler = ProxyManager.HTTPS_PROXY.create_proxy_handler()
|
||||
# proxy_auth_handler = ProxyManager.HTTPS_PROXY.create_proxy_auth_handler()
|
||||
|
||||
# apparently, dslib simply returned None on create_proxy_auth_handler
|
||||
# if this is ever needed, probably use urllib2.ProxyBasicAuthHandler
|
||||
# proxy_auth_handler = None
|
||||
# and create_proxy_handler SHOULD HAVE eval'd to this:
|
||||
# proxy_handler = urllib2.ProxyHandler({"https" : "https://hostname"})
|
||||
# but because no hostname was given, it also just returned None
|
||||
# proxy_handler = None
|
||||
|
||||
#these two literally do nothing right now
|
||||
# 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', str(self.user_agent_string))]
|
||||
|
@ -1,102 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 sys
|
||||
import socket
|
||||
from M2Crypto import RSA, X509, EVP, m2
|
||||
from calculate.lib.datavars import DataVars
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_console3', sys.modules[__name__])
|
||||
|
||||
|
||||
def passphrase_callback(v):
|
||||
if type(v) == int or not v:
|
||||
return ""
|
||||
return str(v)
|
||||
|
||||
|
||||
def generateRSAKey():
|
||||
return RSA.gen_key(2048, m2.RSA_F4)
|
||||
|
||||
|
||||
def makePKey(key):
|
||||
pkey = EVP.PKey()
|
||||
pkey.assign_rsa(key)
|
||||
return pkey
|
||||
|
||||
|
||||
def makeRequest(pubkey, pkey, serv_host, auto=False):
|
||||
""" create query to the signing on server """
|
||||
req = X509.Request()
|
||||
# Seems to default to 0, but we can now set it as well, so just API test
|
||||
req.set_version(req.get_version())
|
||||
req.set_pubkey(pkey)
|
||||
name = X509.X509_Name()
|
||||
if auto:
|
||||
c = 'n'
|
||||
else:
|
||||
c = input(_("Enter the certificate data manually? y/[n]: "))
|
||||
# Get HostName
|
||||
host_name = socket.getfqdn()
|
||||
list_host_name = host_name.split('.')
|
||||
result_host_name = list_host_name[0] + "@" + serv_host
|
||||
# Get username
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
username = clVars.Get('ur_fullname')
|
||||
# Get language
|
||||
lang = clVars.Get('os_locale_locale')[:2]
|
||||
if c.lower() in ['y', 'yes']:
|
||||
# if serv_host in host_name:
|
||||
# host_name = host_name.replace('.'+serv_host, '')
|
||||
# list_host_name = host_name.split('.')
|
||||
# result_host_name = \
|
||||
# list_host_name[len(list_host_name)-1]+"@"+serv_host
|
||||
# else:
|
||||
# host_name = socket.getfqdn()
|
||||
_CN = input(_('Host Name [%s]: ') % result_host_name)
|
||||
name.CN = _CN or result_host_name
|
||||
|
||||
_OU = input(_('User Name [%s]: ') % username)
|
||||
name.OU = _OU or username
|
||||
_O = input(_('Organization Name: '))
|
||||
name.O = _O or ""
|
||||
|
||||
_L = input(_('Network address (hostname or IP) [%s]: ')
|
||||
% host_name)
|
||||
name.L = _L or ""
|
||||
_ST = input(_('City: '))
|
||||
name.ST = _ST or ""
|
||||
_C = input(_('Country (2 characters): [%s]') % lang)
|
||||
name.C = _C or lang
|
||||
|
||||
else:
|
||||
name.CN = result_host_name or "" # Имя сертификата (Common Name);
|
||||
name.OU = username or "" # Название отдела (Organization Unit);
|
||||
name.O = 'My Company' # Название организации (Organization Name);
|
||||
name.L = host_name or "" # Название города (Locality Name);
|
||||
name.ST = 'My State' # Название региона (State Name);
|
||||
name.C = lang or "C" # Двухсимвольный код страны (Country);
|
||||
req.set_subject_name(name)
|
||||
|
||||
ext1 = X509.new_extension('nsComment', 'Auto Generated')
|
||||
extstack = X509.X509_Extension_Stack()
|
||||
extstack.push(ext1)
|
||||
req.add_extensions(extstack)
|
||||
req.sign(pkey, 'md5')
|
||||
return req
|
@ -1,155 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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.
|
||||
from .function import _print
|
||||
|
||||
import sys
|
||||
import datetime
|
||||
from calculate.lib.utils.tools import classificate
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_console3', sys.modules[__name__])
|
||||
client_types = "console"
|
||||
|
||||
|
||||
def pid_inf(client, sid, pids, wait_thread=None):
|
||||
""" get and show information about process """
|
||||
for mark, pid in classificate(pids):
|
||||
s = client.service.pid_info(sid, pid)
|
||||
if wait_thread:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write("\b")
|
||||
sys.stdout.flush()
|
||||
if s == "":
|
||||
print(_("PID not found"))
|
||||
return 1
|
||||
if s[0][0] == "Permission denied":
|
||||
print(_("Permission denied"))
|
||||
return 1
|
||||
|
||||
_print(_(u"Process name: %s") % s[0][4])
|
||||
print(_(u"ID: %s") % s[0][0])
|
||||
_print(_(u"Start time: %s") % s[0][2].partition(".")[0])
|
||||
if s[0][1] == '1':
|
||||
status = _(u"Active")
|
||||
elif s[0][1] == '0':
|
||||
status = _(u"Completed")
|
||||
else:
|
||||
status = _(u"Killed")
|
||||
print(_(u"Status: %s") % status)
|
||||
if not mark.last:
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
def client_list_pid(client):
|
||||
""" get all process id for this session """
|
||||
sid = client.get_sid()
|
||||
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid=sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print(red + _("PIDs not found for this session!"))
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
print(green + "pid - %d" % i)
|
||||
except Exception:
|
||||
print(red + _("Error fetching the PID list from the server"))
|
||||
return 1
|
||||
return len(list_pid[0])
|
||||
|
||||
|
||||
def gen_pid_ls(client):
|
||||
""" generation list with pid for this session """
|
||||
sid = client.get_sid()
|
||||
pid_ls = []
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid=sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print(_("PIDs not found for this session!"))
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
pid_ls.append(i)
|
||||
except Exception:
|
||||
print(_("Error fetching the PID list from the server"))
|
||||
return 0
|
||||
return pid_ls
|
||||
|
||||
|
||||
def client_pid_info(client, wait_thread=None):
|
||||
""" get information about selected process (or about all) """
|
||||
sid = client.get_sid()
|
||||
pid_ls = gen_pid_ls(client)
|
||||
if wait_thread:
|
||||
wait_thread.stop()
|
||||
sys.stdout.write("\b")
|
||||
sys.stdout.flush()
|
||||
if pid_ls:
|
||||
pid_inf(client, sid, pid_ls, wait_thread=wait_thread)
|
||||
|
||||
|
||||
def client_list_methods(client):
|
||||
""" get & show all available methods for this certificate """
|
||||
DAT = 0 # Access to data soap structure
|
||||
RES = 0 # Access to result
|
||||
COM = 0 # Getting command line
|
||||
METH = 1 # Getting method line
|
||||
TR_METH = 3 # Translate method name
|
||||
results = client.service.get_methods(client.sid, client_types)
|
||||
if not results:
|
||||
print(_('No methods available'))
|
||||
return 1
|
||||
try:
|
||||
if results[DAT][RES][RES][COM] == '0':
|
||||
print(_('No methods available'))
|
||||
return 1
|
||||
except:
|
||||
pass
|
||||
print(_("Available methods:"))
|
||||
group_dict = {}
|
||||
for group in results.stringArray:
|
||||
if len(group.string) == 4:
|
||||
group_dict[group.string[METH]] = group.string[TR_METH]
|
||||
if len(group.string) == 3:
|
||||
group_dict[group.string[METH]] = group.string[TR_METH - 1]
|
||||
sort_keys = list(group_dict.keys())
|
||||
sort_keys.sort()
|
||||
for key in sort_keys:
|
||||
print(" %s - %s" % (key, group_dict[key]))
|
||||
|
||||
|
||||
def client_pid_kill(client, pid):
|
||||
sid = client.get_sid()
|
||||
|
||||
result = client.service.pid_kill(pid, sid)
|
||||
if result == 0:
|
||||
print(_("Process completed"))
|
||||
elif result == 2:
|
||||
print(_("Process killed"))
|
||||
elif result == 3:
|
||||
print(_("Process not found"))
|
||||
elif result == -1:
|
||||
print(_("Certificate not found on the server"))
|
||||
elif result == -2:
|
||||
print(_("Session not matching your certificate"))
|
||||
elif result == 1:
|
||||
print(_("Failed to terminate the process"))
|
||||
return 0
|
@ -1,146 +0,0 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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.
|
||||
|
||||
|
||||
from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
|
||||
from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_2
|
||||
|
||||
# from socket import socket
|
||||
from socket import SocketIO
|
||||
import io
|
||||
|
||||
# the OpenSSL stuff
|
||||
import OpenSSL
|
||||
|
||||
_ssl_to_openssl_cert_op_remap = {
|
||||
CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
|
||||
CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
|
||||
CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER|OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT
|
||||
}
|
||||
|
||||
_ssl_to_openssl_version_remap = {
|
||||
PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
|
||||
PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
|
||||
PROTOCOL_TLSv1_2 : OpenSSL.SSL.TLSv1_2_METHOD
|
||||
}
|
||||
|
||||
class PyOpenSSLSocket(OpenSSL.SSL.Connection):
|
||||
def __init__(self, sock, keyfile=None, certfile=None,
|
||||
server_side=False, cert_reqs=CERT_NONE,
|
||||
ssl_version=PROTOCOL_TLSv1_2, ca_certs=None,
|
||||
do_handshake_on_connect=True,
|
||||
keyobj=None, certobj=None):
|
||||
|
||||
context = PyOpenSSLSocket.make_context(
|
||||
keyfile = keyfile,
|
||||
certfile = certfile,
|
||||
cert_reqs = cert_reqs,
|
||||
ssl_version = ssl_version,
|
||||
ca_certs = ca_certs,
|
||||
keyobj = keyobj,
|
||||
certobj = certobj)
|
||||
super().__init__(context, sock)
|
||||
self.setblocking(True)
|
||||
self.set_connect_state()
|
||||
if do_handshake_on_connect:
|
||||
timeout = self.gettimeout()
|
||||
try:
|
||||
self.settimeout(None)
|
||||
self.do_handshake()
|
||||
finally:
|
||||
self.settimeout(timeout)
|
||||
|
||||
self._io_refs = 0
|
||||
self.do_handshake_on_connect = do_handshake_on_connect
|
||||
|
||||
|
||||
def connect(self, addr):
|
||||
print("PYOPENSSL CONNECT")
|
||||
super().connect(addr)
|
||||
if self.do_handshake_on_connect:
|
||||
self.do_handshake()
|
||||
|
||||
def close (self):
|
||||
if self._io_refs < 1:
|
||||
self._socket.close()
|
||||
else:
|
||||
self._io_refs -= 1
|
||||
|
||||
def makefile(self, mode="r", buffering=None, *,
|
||||
encoding=None, errors=None, newline=None):
|
||||
"""makefile(...) -> an I/O stream connected to the socket
|
||||
|
||||
The arguments are as for io.open() after the filename, except the only
|
||||
supported mode values are 'r' (default), 'w' and 'b'.
|
||||
"""
|
||||
if not set(mode) <= {"r", "w", "b"}:
|
||||
raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
|
||||
writing = "w" in mode
|
||||
reading = "r" in mode or not writing
|
||||
assert reading or writing
|
||||
binary = "b" in mode
|
||||
rawmode = ""
|
||||
if reading:
|
||||
rawmode += "r"
|
||||
if writing:
|
||||
rawmode += "w"
|
||||
raw = SocketIO(self, rawmode)
|
||||
self._io_refs += 1
|
||||
if buffering is None:
|
||||
buffering = -1
|
||||
if buffering < 0:
|
||||
buffering = io.DEFAULT_BUFFER_SIZE
|
||||
if buffering == 0:
|
||||
if not binary:
|
||||
raise ValueError("unbuffered streams must be binary")
|
||||
return raw
|
||||
if reading and writing:
|
||||
buffer = io.BufferedRWPair(raw, raw, buffering)
|
||||
elif reading:
|
||||
buffer = io.BufferedReader(raw, buffering)
|
||||
else:
|
||||
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):
|
||||
# no extra validation - just return whatever OpenSSL already
|
||||
# decided during its check
|
||||
return bool(ret_code)
|
@ -1,140 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# 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 os
|
||||
|
||||
import sys
|
||||
from calculate.lib.utils.files import readLinesFile, readFile, writeFile
|
||||
from calculate.lib.utils.tools import Locker
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_console3', sys.modules[__name__])
|
||||
|
||||
|
||||
def sid_inf(client, sid):
|
||||
""" get information about selected session """
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
s = client.service.sid_info(sid)
|
||||
if s[0][0] == "-1":
|
||||
print(red + _("Session non registered on the server!"))
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print(red + _("Failed to obtain certificate data!"))
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print(red + _("%s: permission denied") % s[0][1])
|
||||
return -3
|
||||
|
||||
print(_('Session information: '))
|
||||
print(green + _(u"ID: %s") % sid)
|
||||
print(green + _(u"Certificate number: %s") % s[0][0])
|
||||
print(green + _(u"Certificate issued: %s") % s[0][1].partition(".")[0])
|
||||
print(green + "IP: %s" % s[0][2])
|
||||
print(green + "MAC: %s\n" % s[0][3])
|
||||
return 0
|
||||
|
||||
|
||||
def client_session_info(client, sid=None):
|
||||
""" select session for get information """
|
||||
try:
|
||||
select_sid = sid if sid else client.sid
|
||||
sid_inf(client, select_sid)
|
||||
except Exception as e:
|
||||
if type(e) == tuple and len(e) == 2 \
|
||||
and e[1] == 'Forbidden':
|
||||
print(_("Access forbidden!"))
|
||||
else:
|
||||
_print(parseError(e))
|
||||
return 1
|
||||
|
||||
|
||||
def client_session_list(client):
|
||||
red = '\033[31m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
try:
|
||||
res = client.service.get_sessions(client.sid)
|
||||
except Exception as e:
|
||||
if type(e) == tuple and len(e) == 2 \
|
||||
and e[1] == 'Forbidden':
|
||||
print(_("Access forbidden!"))
|
||||
else:
|
||||
_print(parseError(e))
|
||||
return 1
|
||||
if hasattr(res, 'string'):
|
||||
if res.string:
|
||||
print(_('Active sessions on the server: '))
|
||||
for session_id in res.string:
|
||||
print(green + session_id)
|
||||
print()
|
||||
return 0
|
||||
print(red + _('No active sessions on the server'))
|
||||
|
||||
|
||||
def session_clean(client):
|
||||
try:
|
||||
res = client.service.clear_session_cache(client.sid)
|
||||
if res:
|
||||
print(_('Error clearing the session cache'))
|
||||
else:
|
||||
print(_('Session cache cleared'))
|
||||
except Exception as e:
|
||||
if type(e) == tuple and len(e) == 2 \
|
||||
and e[1] == 'Forbidden':
|
||||
print(_("Access forbidden!"))
|
||||
else:
|
||||
_print(parseError(e))
|
||||
|
||||
|
||||
class SessionId():
|
||||
SID_FILE = None
|
||||
HOST = None
|
||||
SID_LOCK = None
|
||||
|
||||
def get_sid(self):
|
||||
if not os.path.exists(self.SID_FILE):
|
||||
return "0"
|
||||
else:
|
||||
with Locker(fn=self.SID_LOCK):
|
||||
for line in readLinesFile(self.SID_FILE):
|
||||
data = line.split()
|
||||
if len(data) == 2:
|
||||
host, sid = data
|
||||
if self.host_alias(self.HOST) == host:
|
||||
return sid
|
||||
return "0"
|
||||
|
||||
def host_alias(self, host):
|
||||
if host == "localhost":
|
||||
return "127.0.0.1"
|
||||
return host
|
||||
|
||||
def write_sid(self, sid):
|
||||
with Locker(fn=self.SID_LOCK):
|
||||
sid_data = readFile(self.SID_FILE)
|
||||
added = False
|
||||
with writeFile(self.SID_FILE) as f:
|
||||
for line in sid_data.split('\n'):
|
||||
data = line.split()
|
||||
if len(data) == 2:
|
||||
host, oldsid = data
|
||||
if self.host_alias(self.HOST) == host:
|
||||
oldsid = str(sid)
|
||||
added = True
|
||||
f.write("%s %s\n" % (host, oldsid))
|
||||
if not added:
|
||||
f.write("%s %s" % (self.host_alias(self.HOST), str(sid)))
|
Loading…
Reference in new issue