parent
cc9288b31b
commit
5ec8b4989e
@ -1,322 +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 __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import os
|
||||
import sys
|
||||
from .sid_func import client_sid
|
||||
from .function import get_sid, get_ip_mac_type
|
||||
from .create_cert import (generateRSAKey, makePKey,
|
||||
makeRequest, passphrase_callback)
|
||||
import hashlib
|
||||
from .client_class import HTTPSClientCertTransport
|
||||
from .cert_verify import VerifyError
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
VERSION = 0.11
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def client_post_cert(client):
|
||||
""" send a certificate server for check """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
results = client.service.post_cert()
|
||||
|
||||
if results[0][0] == -4:
|
||||
print(_("Certificate not found in the server database!"))
|
||||
sys.exit(1)
|
||||
client_sid(sid, client, cert_id=results[0][0])
|
||||
if results[0][0] == -3:
|
||||
print(_("Certificate not sent!"))
|
||||
else:
|
||||
print(_(" Your certifitate ID = %d") % (results[0][0]))
|
||||
try:
|
||||
if results[0][1] == -2:
|
||||
print(_("Certificate expired"))
|
||||
elif results[0][1] > 0:
|
||||
print(_("The certificate expires after %d days") % (
|
||||
results[0][1]))
|
||||
except (IndexError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
# Creation of secret key of the client
|
||||
def new_key_req(key, cert_path, server_host_name, auto=False):
|
||||
rsa = generateRSAKey()
|
||||
rsa.save_key(key + '_pub', cipher=None, callback=passphrase_callback)
|
||||
|
||||
pkey = makePKey(rsa)
|
||||
pkey.save_key(key, cipher=None, callback=passphrase_callback)
|
||||
|
||||
req = makeRequest(rsa, pkey, server_host_name, auto)
|
||||
crtreq = req.as_pem()
|
||||
|
||||
req_file = os.path.join(cert_path, '%s.csr' % server_host_name)
|
||||
crtfile = open(req_file, 'w')
|
||||
crtfile.write(crtreq)
|
||||
crtfile.close()
|
||||
return req_file
|
||||
|
||||
|
||||
def delete_old_cert(client):
|
||||
os.unlink(client.CERT_FILE)
|
||||
os.unlink(client.REQ_FILE)
|
||||
os.unlink(client.PKEY_FILE)
|
||||
os.unlink(client.PubKEY_FILE)
|
||||
|
||||
|
||||
def client_post_request(cert_path, by_host):
|
||||
if os.path.exists(cert_path + 'req_id'):
|
||||
print(_("You already sent a certificate signature request."))
|
||||
print(_("Request ID = %s") % readFile(cert_path + 'req_id'))
|
||||
ans = raw_input(_("Send a new request? y/[n]: "))
|
||||
if not ans.lower() in ['y', 'yes']:
|
||||
return 0
|
||||
|
||||
port = raw_input(_("Enter the port number: "))
|
||||
try:
|
||||
port = int(port)
|
||||
except ValueError:
|
||||
print(_('The port number must be int'))
|
||||
return 1
|
||||
url = "https://%s:%d/?wsdl" % (by_host, port)
|
||||
print(url + '\n' + _("connecting..."))
|
||||
from suds.client import Client
|
||||
# try:
|
||||
client = Client(url, transport=HTTPSClientCertTransport(None, None,
|
||||
cert_path))
|
||||
# except (KeyboardInterrupt, urllib2.URLError), e:
|
||||
# print '\n'+_("Closed. Connection error.")
|
||||
# print _("Error code: %s") %e
|
||||
# return 0
|
||||
|
||||
server_host_name = client.service.get_server_host_name()
|
||||
|
||||
key = cert_path + server_host_name + '.key'
|
||||
csr_file = cert_path + server_host_name + '.csr'
|
||||
if os.path.exists(key) and os.path.exists(csr_file):
|
||||
print(_("the private key and request now exist"))
|
||||
ask = raw_input(_("Create a new private key and request? y/[n]: "))
|
||||
if ask.lower() in ['y', 'yes']:
|
||||
new_key_req(key, cert_path, server_host_name)
|
||||
else:
|
||||
new_key_req(key, cert_path, server_host_name)
|
||||
|
||||
ip, mac, client_type = get_ip_mac_type()
|
||||
data = readFile(csr_file)
|
||||
res = client.service.post_client_request(request=data, ip=ip,
|
||||
mac=mac, client_type=client_type)
|
||||
if int(res) < 0:
|
||||
print(_("This server is not enabled to sign certificates!"))
|
||||
return 1
|
||||
fc = open(cert_path + 'req_id', 'w')
|
||||
fc.write(res)
|
||||
fc.close()
|
||||
print(_("Your request ID = %s") % res)
|
||||
return 0
|
||||
|
||||
|
||||
def client_get_cert(cert_path, args):
|
||||
if not os.path.exists(cert_path + 'req_id'):
|
||||
print(_("request not sent or file %s deleted") % (cert_path + 'req_id'))
|
||||
return 1
|
||||
fc = open(cert_path + 'req_id', 'r')
|
||||
req_id = fc.read()
|
||||
fc.close()
|
||||
|
||||
print('\n' + _("the URL looks like"), "https://%s:[port]/?wsdl" \
|
||||
% args.from_host)
|
||||
port = raw_input(_("Enter the port number: "))
|
||||
try:
|
||||
port = int(port)
|
||||
except ValueError:
|
||||
print(_('The port number must be int'))
|
||||
return 1
|
||||
url = "https://%s:%d/?wsdl" % (args.from_host, port)
|
||||
print(url + '\n' + _("connecting..."))
|
||||
|
||||
from suds.client import Client
|
||||
|
||||
try:
|
||||
client = Client(url, transport=HTTPSClientCertTransport(None, None,
|
||||
cert_path))
|
||||
except KeyboardInterrupt:
|
||||
print('\n' + _("Closed. Connection error."))
|
||||
return 1
|
||||
|
||||
server_host_name = client.service.get_server_host_name()
|
||||
|
||||
if not os.path.exists(cert_path + server_host_name + '.csr'):
|
||||
print(_('Request %s not found') % (
|
||||
cert_path + server_host_name + '.csr'))
|
||||
return 1
|
||||
request = readFile(cert_path + server_host_name + '.csr')
|
||||
md5 = hashlib.md5()
|
||||
md5.update(request)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
result = client.service.get_client_cert(req_id, md5sum)
|
||||
cert = result[0][0]
|
||||
ca_root = result[0][1]
|
||||
if cert == '1':
|
||||
print(_('The signature request was rejected!'))
|
||||
return 1
|
||||
elif cert == '2':
|
||||
print(_("The signature request has not been examined yet."))
|
||||
print(_("Your request ID = %s") % req_id)
|
||||
return 1
|
||||
elif cert == '3':
|
||||
print(_("The signature request does not match earlier data."))
|
||||
return 1
|
||||
elif cert == '4':
|
||||
print(_("The request was sent from another IP."))
|
||||
return 1
|
||||
fc = open(cert_path + server_host_name + '.crt', 'w')
|
||||
fc.write(cert)
|
||||
fc.close()
|
||||
os.unlink(cert_path + 'req_id')
|
||||
print('OK. Certificate saved. Your certificate ID = %s' % req_id)
|
||||
|
||||
if ca_root:
|
||||
cl_vars = DataVarsCore()
|
||||
cl_vars.importCore()
|
||||
cl_vars.flIniFile()
|
||||
system_ca_db = cl_vars.Get('cl_glob_root_cert')
|
||||
if os.path.exists(system_ca_db):
|
||||
if ca_root in readFile(system_ca_db):
|
||||
return 0
|
||||
|
||||
cl_client_cert_dir = cl_vars.Get('cl_client_cert_dir')
|
||||
home_path = cl_vars.Get('ur_home_path')
|
||||
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", home_path)
|
||||
root_cert_md5 = cl_client_cert_dir + "/ca/cert_list"
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_root)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
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]
|
||||
import OpenSSL
|
||||
|
||||
if not filename:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, ca_root)
|
||||
issuer = certobj.get_issuer().get_components()
|
||||
for item in issuer:
|
||||
if item[0] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
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(cl_client_cert_dir + '/ca/' + filename, 'w')
|
||||
fd.write(ca_root)
|
||||
fd.close()
|
||||
|
||||
user_root_cert = cl_vars.Get('cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~", home_path)
|
||||
fa = open(user_root_cert, 'a')
|
||||
fa.write(ca_root)
|
||||
fa.close()
|
||||
print(_("Certificate added"))
|
||||
else:
|
||||
print(_("file containing the CA certificate now exists"))
|
||||
return 0
|
||||
|
||||
|
||||
def client_post_auth(client):
|
||||
""" authorization client or post request """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
try:
|
||||
if os.path.exists(client.CERT_FILE):
|
||||
pass # client_post_cert(client)
|
||||
else:
|
||||
# client_post_request(client)
|
||||
print(_('You do not have a certificate. Use option '
|
||||
'--gen-cert-by HOST to generate a new certificate '
|
||||
'or --get-cert-from HOST to get the certificate '
|
||||
'from the server.'))
|
||||
sys.exit()
|
||||
print(client.service.versions(sid, VERSION))
|
||||
except VerifyError as e:
|
||||
print(e.value)
|
||||
sys.exit()
|
||||
|
||||
|
||||
# show rights on requested certificated
|
||||
def cert_right_inf(client, sid, cert_id):
|
||||
s = client.service.view_cert_right(cert_id)
|
||||
if s[0][0] == "-1":
|
||||
print(_("Certificate not found on the server!"))
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print(_("Failed to create the certificate ID!"))
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print(_("%s: Permission denied") % s[0][1])
|
||||
return -3
|
||||
|
||||
print(_("The certificate with ID = %d can execute:") % cert_id)
|
||||
for meth in s[0]:
|
||||
print(" - %s" % meth)
|
||||
|
||||
|
||||
# Viewing rights of any certificate on server by its id
|
||||
def client_view_cert_right(client):
|
||||
cert_id = raw_input(_("Certificate ID: "))
|
||||
try:
|
||||
cert_id = int(cert_id)
|
||||
except ValueError:
|
||||
print(_("Invalid certificate ID"))
|
||||
return 1
|
||||
try:
|
||||
sid = get_sid(client.SID_FILE)
|
||||
if cert_id > 0:
|
||||
cert_right_inf(client, sid, cert_id)
|
||||
else:
|
||||
print(_("Please enter a valid certificate ID!"))
|
||||
except Exception as e:
|
||||
if e[0][0] == 403:
|
||||
print(_('Permission denied'))
|
||||
else:
|
||||
print(e)
|
||||
# print _("Failed to get data")
|
||||
return 1
|
||||
return 0
|
@ -1,320 +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 sid_func import client_sid
|
||||
from function import get_sid, get_ip_mac_type
|
||||
from create_cert import (generateRSAKey, makePKey,
|
||||
makeRequest, passphrase_callback)
|
||||
import hashlib
|
||||
from client_class import HTTPSClientCertTransport
|
||||
from cert_verify import VerifyError
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
VERSION = 0.11
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def client_post_cert(client):
|
||||
""" send a certificate server for check """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
results = client.service.post_cert()
|
||||
|
||||
if results[0][0] == -4:
|
||||
print _("Certificate not found in the server database!")
|
||||
sys.exit(1)
|
||||
client_sid(sid, client, cert_id=results[0][0])
|
||||
if results[0][0] == -3:
|
||||
print _("Certificate not sent!")
|
||||
else:
|
||||
print _(" Your certifitate ID = %d") % (results[0][0])
|
||||
try:
|
||||
if results[0][1] == -2:
|
||||
print _("Certificate expired")
|
||||
elif results[0][1] > 0:
|
||||
print _("The certificate expires after %d days") % (
|
||||
results[0][1])
|
||||
except (IndexError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
# Creation of secret key of the client
|
||||
def new_key_req(key, cert_path, server_host_name, auto=False):
|
||||
rsa = generateRSAKey()
|
||||
rsa.save_key(key + '_pub', cipher=None, callback=passphrase_callback)
|
||||
|
||||
pkey = makePKey(rsa)
|
||||
pkey.save_key(key, cipher=None, callback=passphrase_callback)
|
||||
|
||||
req = makeRequest(rsa, pkey, server_host_name, auto)
|
||||
crtreq = req.as_pem()
|
||||
|
||||
req_file = os.path.join(cert_path, '%s.csr' % server_host_name)
|
||||
crtfile = open(req_file, 'w')
|
||||
crtfile.write(crtreq)
|
||||
crtfile.close()
|
||||
return req_file
|
||||
|
||||
|
||||
def delete_old_cert(client):
|
||||
os.unlink(client.CERT_FILE)
|
||||
os.unlink(client.REQ_FILE)
|
||||
os.unlink(client.PKEY_FILE)
|
||||
os.unlink(client.PubKEY_FILE)
|
||||
|
||||
|
||||
def client_post_request(cert_path, by_host):
|
||||
if os.path.exists(cert_path + 'req_id'):
|
||||
print _("You already sent a certificate signature request.")
|
||||
print _("Request ID = %s") % readFile(cert_path + 'req_id')
|
||||
ans = raw_input(_("Send a new request? y/[n]: "))
|
||||
if not ans.lower() in ['y', 'yes']:
|
||||
return 0
|
||||
|
||||
port = raw_input(_("Enter the port number: "))
|
||||
try:
|
||||
port = int(port)
|
||||
except ValueError:
|
||||
print _('The port number must be int')
|
||||
return 1
|
||||
url = "https://%s:%d/?wsdl" % (by_host, port)
|
||||
print url + '\n' + _("connecting...")
|
||||
from suds.client import Client
|
||||
# try:
|
||||
client = Client(url, transport=HTTPSClientCertTransport(None, None,
|
||||
cert_path))
|
||||
# except (KeyboardInterrupt, urllib2.URLError), e:
|
||||
# print '\n'+_("Closed. Connection error.")
|
||||
# print _("Error code: %s") %e
|
||||
# return 0
|
||||
|
||||
server_host_name = client.service.get_server_host_name()
|
||||
|
||||
key = cert_path + server_host_name + '.key'
|
||||
csr_file = cert_path + server_host_name + '.csr'
|
||||
if os.path.exists(key) and os.path.exists(csr_file):
|
||||
print _("the private key and request now exist")
|
||||
ask = raw_input(_("Create a new private key and request? y/[n]: "))
|
||||
if ask.lower() in ['y', 'yes']:
|
||||
new_key_req(key, cert_path, server_host_name)
|
||||
else:
|
||||
new_key_req(key, cert_path, server_host_name)
|
||||
|
||||
ip, mac, client_type = get_ip_mac_type()
|
||||
data = readFile(csr_file)
|
||||
res = client.service.post_client_request(request=data, ip=ip,
|
||||
mac=mac, client_type=client_type)
|
||||
if int(res) < 0:
|
||||
print _("This server is not enabled to sign certificates!")
|
||||
return 1
|
||||
fc = open(cert_path + 'req_id', 'w')
|
||||
fc.write(res)
|
||||
fc.close()
|
||||
print _("Your request ID = %s") % res
|
||||
return 0
|
||||
|
||||
|
||||
def client_get_cert(cert_path, args):
|
||||
if not os.path.exists(cert_path + 'req_id'):
|
||||
print _("request not sent or file %s deleted") % (cert_path + 'req_id')
|
||||
return 1
|
||||
fc = open(cert_path + 'req_id', 'r')
|
||||
req_id = fc.read()
|
||||
fc.close()
|
||||
|
||||
print '\n' + _("the URL looks like"), "https://%s:[port]/?wsdl" \
|
||||
% args.from_host
|
||||
port = raw_input(_("Enter the port number: "))
|
||||
try:
|
||||
port = int(port)
|
||||
except ValueError:
|
||||
print _('The port number must be int')
|
||||
return 1
|
||||
url = "https://%s:%d/?wsdl" % (args.from_host, port)
|
||||
print url + '\n' + _("connecting...")
|
||||
|
||||
from suds.client import Client
|
||||
|
||||
try:
|
||||
client = Client(url, transport=HTTPSClientCertTransport(None, None,
|
||||
cert_path))
|
||||
except KeyboardInterrupt:
|
||||
print '\n' + _("Closed. Connection error.")
|
||||
return 1
|
||||
|
||||
server_host_name = client.service.get_server_host_name()
|
||||
|
||||
if not os.path.exists(cert_path + server_host_name + '.csr'):
|
||||
print _('Request %s not found') % (
|
||||
cert_path + server_host_name + '.csr')
|
||||
return 1
|
||||
request = readFile(cert_path + server_host_name + '.csr')
|
||||
md5 = hashlib.md5()
|
||||
md5.update(request)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
result = client.service.get_client_cert(req_id, md5sum)
|
||||
cert = result[0][0]
|
||||
ca_root = result[0][1]
|
||||
if cert == '1':
|
||||
print _('The signature request was rejected!')
|
||||
return 1
|
||||
elif cert == '2':
|
||||
print _("The signature request has not been examined yet.")
|
||||
print _("Your request ID = %s") % req_id
|
||||
return 1
|
||||
elif cert == '3':
|
||||
print _("The signature request does not match earlier data.")
|
||||
return 1
|
||||
elif cert == '4':
|
||||
print _("The request was sent from another IP.")
|
||||
return 1
|
||||
fc = open(cert_path + server_host_name + '.crt', 'w')
|
||||
fc.write(cert)
|
||||
fc.close()
|
||||
os.unlink(cert_path + 'req_id')
|
||||
print 'OK. Certificate saved. Your certificate ID = %s' % req_id
|
||||
|
||||
if ca_root:
|
||||
cl_vars = DataVarsCore()
|
||||
cl_vars.importCore()
|
||||
cl_vars.flIniFile()
|
||||
system_ca_db = cl_vars.Get('cl_glob_root_cert')
|
||||
if os.path.exists(system_ca_db):
|
||||
if ca_root in readFile(system_ca_db):
|
||||
return 0
|
||||
|
||||
cl_client_cert_dir = cl_vars.Get('cl_client_cert_dir')
|
||||
home_path = cl_vars.Get('ur_home_path')
|
||||
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", home_path)
|
||||
root_cert_md5 = cl_client_cert_dir + "/ca/cert_list"
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_root)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
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]
|
||||
import OpenSSL
|
||||
|
||||
if not filename:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, ca_root)
|
||||
issuer = certobj.get_issuer().get_components()
|
||||
for item in issuer:
|
||||
if item[0] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
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(cl_client_cert_dir + '/ca/' + filename, 'w')
|
||||
fd.write(ca_root)
|
||||
fd.close()
|
||||
|
||||
user_root_cert = cl_vars.Get('cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~", home_path)
|
||||
fa = open(user_root_cert, 'a')
|
||||
fa.write(ca_root)
|
||||
fa.close()
|
||||
print _("Certificate added")
|
||||
else:
|
||||
print _("file containing the CA certificate now exists")
|
||||
return 0
|
||||
|
||||
|
||||
def client_post_auth(client):
|
||||
""" authorization client or post request """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
try:
|
||||
if os.path.exists(client.CERT_FILE):
|
||||
pass # client_post_cert(client)
|
||||
else:
|
||||
# client_post_request(client)
|
||||
print _('You do not have a certificate. Use option '
|
||||
'--gen-cert-by HOST to generate a new certificate '
|
||||
'or --get-cert-from HOST to get the certificate '
|
||||
'from the server.')
|
||||
sys.exit()
|
||||
print client.service.versions(sid, VERSION)
|
||||
except VerifyError, e:
|
||||
print e.value
|
||||
sys.exit()
|
||||
|
||||
|
||||
# show rights on requested certificated
|
||||
def cert_right_inf(client, sid, cert_id):
|
||||
s = client.service.view_cert_right(cert_id)
|
||||
if s[0][0] == "-1":
|
||||
print _("Certificate not found on the server!")
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print _("Failed to create the certificate ID!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print _("%s: Permission denied") % s[0][1]
|
||||
return -3
|
||||
|
||||
print _("The certificate with ID = %d can execute:") % cert_id
|
||||
for meth in s[0]:
|
||||
print " - %s" % meth
|
||||
|
||||
|
||||
# Viewing rights of any certificate on server by its id
|
||||
def client_view_cert_right(client):
|
||||
cert_id = raw_input(_("Certificate ID: "))
|
||||
try:
|
||||
cert_id = int(cert_id)
|
||||
except ValueError:
|
||||
print _("Invalid certificate ID")
|
||||
return 1
|
||||
try:
|
||||
sid = get_sid(client.SID_FILE)
|
||||
if cert_id > 0:
|
||||
cert_right_inf(client, sid, cert_id)
|
||||
else:
|
||||
print _("Please enter a valid certificate ID!")
|
||||
except Exception, e:
|
||||
if e[0][0] == 403:
|
||||
print _('Permission denied')
|
||||
else:
|
||||
print e
|
||||
# print _("Failed to get data")
|
||||
return 1
|
||||
return 0
|
@ -1,312 +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 __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
class VerifyError(Exception):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
|
||||
|
||||
# check recall of server certificate
|
||||
def verify(server_cert, crl_path, flag):
|
||||
import OpenSSL
|
||||
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM,
|
||||
server_cert)
|
||||
serverSerial = certobj.get_serial_number()
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
CN, L = None, None
|
||||
for i in Issuer:
|
||||
if i[0] == 'CN':
|
||||
CN = i[1]
|
||||
elif i[0] == 'L':
|
||||
L = i[1]
|
||||
|
||||
if CN and len(CN) > 2:
|
||||
crl_file = crl_path + CN
|
||||
elif L:
|
||||
try:
|
||||
host = L.split(':')[0]
|
||||
except Exception:
|
||||
if not flag:
|
||||
print(_('The CN and L fields in the CA certificate are '
|
||||
'incorrect!'))
|
||||
return 0
|
||||
crl_file = crl_path + host
|
||||
else:
|
||||
if not flag:
|
||||
print(_('The CN and L fields in the CA certificate are incorrect!'))
|
||||
return 0
|
||||
|
||||
if not os.path.exists(crl_file):
|
||||
if not flag:
|
||||
print(_("This certificate cannot be verified in the CRL."))
|
||||
return 0
|
||||
|
||||
with open(crl_file, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
if crl == '':
|
||||
return 0
|
||||
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)
|
||||
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if serverSerial == int(rvk.get_serial(), 16):
|
||||
print(_("This certificate has been revoked!"))
|
||||
print (_("Serial") + ': %s\n' % rvk.get_serial() +
|
||||
_("Revoke date") + _(': %s') % rvk.get_rev_date())
|
||||
|
||||
raise VerifyError('CRL Exception')
|
||||
return 0
|
||||
|
||||
|
||||
def get_CRL(path_to_cert):
|
||||
""" get new CRL (Certificate Revocation List) from all CA """
|
||||
# local CRL
|
||||
CRL_path = path_to_cert + 'ca/crl/'
|
||||
if not os.path.exists(CRL_path):
|
||||
if not os.path.exists(path_to_cert + '/ca'):
|
||||
if not os.path.exists(path_to_cert):
|
||||
try:
|
||||
os.makedirs(path_to_cert)
|
||||
except OSError:
|
||||
print(_("Error creating directory %s") % path_to_cert)
|
||||
sys.exit()
|
||||
try:
|
||||
os.makedirs(path_to_cert + '/ca')
|
||||
except OSError:
|
||||
print(_("Error creating directory %s") % (path_to_cert + '/ca'))
|
||||
sys.exit()
|
||||
os.makedirs(CRL_path)
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
# user and system ca and root certificates
|
||||
user_root_cert = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
|
||||
glob_root_cert = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
user_ca_certs = readFile(user_root_cert)
|
||||
else:
|
||||
user_ca_certs = ''
|
||||
if os.path.exists(glob_root_cert):
|
||||
glob_ca_certs = readFile(glob_root_cert)
|
||||
else:
|
||||
glob_ca_certs = ''
|
||||
|
||||
# get certificates list fron text
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
glob_ca_certs_list = p.findall(glob_ca_certs)
|
||||
|
||||
# association in one list
|
||||
all_ca_certs_list = user_ca_certs_list + glob_ca_certs_list
|
||||
import OpenSSL
|
||||
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM, ca)
|
||||
# get url from certificates
|
||||
url = None
|
||||
CN = None
|
||||
Subject = certobj.get_subject().get_components()
|
||||
subj = None
|
||||
for subj in Subject:
|
||||
if subj[0] == 'L':
|
||||
url = "https://" + subj[1] + "/?wsdl"
|
||||
if subj[0] == 'CN':
|
||||
CN = subj[1]
|
||||
|
||||
if subj and url:
|
||||
from calculate.core.client.client_class import Client_suds
|
||||
from .client_class import HTTPSClientCertTransport
|
||||
# connect to ca server (url get from certificates)
|
||||
try:
|
||||
client = Client_suds(url, transport=HTTPSClientCertTransport(
|
||||
None, None, path_to_cert))
|
||||
|
||||
client.set_parameters(path_to_cert, None, None)
|
||||
new_crl = client.service.get_crl()
|
||||
if new_crl:
|
||||
if CN and len(CN) > 2:
|
||||
CRL_file = CRL_path + CN
|
||||
else:
|
||||
host = subj[1].split(':')[0]
|
||||
CRL_file = CRL_path + host
|
||||
if new_crl == ' ':
|
||||
open(CRL_file, 'w').close()
|
||||
# if os.path.exists(CRL_file):
|
||||
# os.unlink(CRL_file)
|
||||
continue
|
||||
if os.path.exists(CRL_file):
|
||||
if readFile(CRL_file) == new_crl:
|
||||
continue
|
||||
|
||||
with open(CRL_file, 'w') as fd:
|
||||
fd.write(new_crl)
|
||||
print(_("CRL added"))
|
||||
except VerifyError as e:
|
||||
print(e.value)
|
||||
# rm_ca_from_trusted(ca)
|
||||
sys.exit()
|
||||
except Exception:
|
||||
pass
|
||||
find_ca_in_crl(CRL_path, all_ca_certs_list)
|
||||
|
||||
|
||||
def find_ca_in_crl(CRL_path, all_ca_certs_list):
|
||||
import OpenSSL
|
||||
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM,
|
||||
ca)
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
for item in Issuer:
|
||||
if item[0] == 'CN':
|
||||
CN = item[1]
|
||||
break
|
||||
else:
|
||||
continue
|
||||
server_serial = certobj.get_serial_number()
|
||||
CRL = CRL_path + CN
|
||||
if not os.path.exists(CRL):
|
||||
continue
|
||||
|
||||
with open(CRL, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
try:
|
||||
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM,
|
||||
crl)
|
||||
except OpenSSL.SSL.Error:
|
||||
continue
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if server_serial == int(rvk.get_serial(), 16):
|
||||
rm_ca_from_trusted(ca)
|
||||
|
||||
|
||||
def rm_ca_from_trusted(ca_cert):
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
|
||||
user_ca_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_dir = user_ca_dir.replace("~", homePath)
|
||||
user_ca_dir = os.path.join(user_ca_dir, 'ca')
|
||||
user_ca_list = os.path.join(user_ca_dir, 'cert_list')
|
||||
user_ca_db = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_db = user_ca_db.replace("~", homePath)
|
||||
|
||||
system_ca_dir = clVars.Get('cl_core_cert_path')
|
||||
system_ca_db = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
import hashlib
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_cert)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
# search ca certificate in user ca list
|
||||
newfile = ''
|
||||
with open(user_ca_list) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
newfile = ''
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
if words[0] == md5sum:
|
||||
filename = os.path.join(user_ca_dir, words[1])
|
||||
if ca_cert == readFile(filename):
|
||||
os.unlink(filename)
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
|
||||
fd.close()
|
||||
fn = open(user_ca_list, 'w')
|
||||
fn.write(newfile)
|
||||
fn.close()
|
||||
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
|
||||
# open, write and split user ca certificates
|
||||
user_ca_certs = readFile(user_ca_db)
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
|
||||
if ca_cert in user_ca_certs_list:
|
||||
new_user_ca_certs = []
|
||||
for cert in user_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_user_ca_certs.append(cert)
|
||||
else:
|
||||
print(_("CA certificate deleted from the user's trusted "
|
||||
"certificates list"))
|
||||
|
||||
with open(user_ca_db, 'w') as fd:
|
||||
for cert in new_user_ca_certs:
|
||||
fd.write(cert)
|
||||
|
||||
if not os.path.exists(system_ca_db):
|
||||
open(system_ca_db, 'w').close()
|
||||
|
||||
system_ca_certs = readFile(system_ca_db)
|
||||
system_ca_certs_list = p.findall(system_ca_certs)
|
||||
|
||||
if ca_cert in system_ca_certs_list:
|
||||
new_system_ca_certs = []
|
||||
for cert in system_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_system_ca_certs.append(cert)
|
||||
else:
|
||||
print(_('CA certificate deleted from the system trusted '
|
||||
'certificates list'))
|
||||
|
||||
fd = open(system_ca_db, 'w')
|
||||
for cert in new_system_ca_certs:
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
|
||||
return 0
|
@ -1,310 +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 os
|
||||
import re
|
||||
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
class VerifyError(Exception):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
|
||||
|
||||
# check recall of server certificate
|
||||
def verify(server_cert, crl_path, flag):
|
||||
import OpenSSL
|
||||
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM,
|
||||
server_cert)
|
||||
serverSerial = certobj.get_serial_number()
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
CN, L = None, None
|
||||
for i in Issuer:
|
||||
if i[0] == 'CN':
|
||||
CN = i[1]
|
||||
elif i[0] == 'L':
|
||||
L = i[1]
|
||||
|
||||
if CN and len(CN) > 2:
|
||||
crl_file = crl_path + CN
|
||||
elif L:
|
||||
try:
|
||||
host = L.split(':')[0]
|
||||
except Exception:
|
||||
if not flag:
|
||||
print _('The CN and L fields in the CA certificate are '
|
||||
'incorrect!')
|
||||
return 0
|
||||
crl_file = crl_path + host
|
||||
else:
|
||||
if not flag:
|
||||
print _('The CN and L fields in the CA certificate are incorrect!')
|
||||
return 0
|
||||
|
||||
if not os.path.exists(crl_file):
|
||||
if not flag:
|
||||
print _("This certificate cannot be verified in the CRL.")
|
||||
return 0
|
||||
|
||||
with open(crl_file, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
if crl == '':
|
||||
return 0
|
||||
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)
|
||||
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if serverSerial == int(rvk.get_serial(), 16):
|
||||
print _("This certificate has been revoked!")
|
||||
print (_("Serial") + ': %s\n' % rvk.get_serial() +
|
||||
_("Revoke date") + _(': %s') % rvk.get_rev_date())
|
||||
|
||||
raise VerifyError('CRL Exception')
|
||||
return 0
|
||||
|
||||
|
||||
def get_CRL(path_to_cert):
|
||||
""" get new CRL (Certificate Revocation List) from all CA """
|
||||
# local CRL
|
||||
CRL_path = path_to_cert + 'ca/crl/'
|
||||
if not os.path.exists(CRL_path):
|
||||
if not os.path.exists(path_to_cert + '/ca'):
|
||||
if not os.path.exists(path_to_cert):
|
||||
try:
|
||||
os.makedirs(path_to_cert)
|
||||
except OSError:
|
||||
print _("Error creating directory %s") % path_to_cert
|
||||
sys.exit()
|
||||
try:
|
||||
os.makedirs(path_to_cert + '/ca')
|
||||
except OSError:
|
||||
print _("Error creating directory %s") % (path_to_cert + '/ca')
|
||||
sys.exit()
|
||||
os.makedirs(CRL_path)
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
# user and system ca and root certificates
|
||||
user_root_cert = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
|
||||
glob_root_cert = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
user_ca_certs = readFile(user_root_cert)
|
||||
else:
|
||||
user_ca_certs = ''
|
||||
if os.path.exists(glob_root_cert):
|
||||
glob_ca_certs = readFile(glob_root_cert)
|
||||
else:
|
||||
glob_ca_certs = ''
|
||||
|
||||
# get certificates list fron text
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
glob_ca_certs_list = p.findall(glob_ca_certs)
|
||||
|
||||
# association in one list
|
||||
all_ca_certs_list = user_ca_certs_list + glob_ca_certs_list
|
||||
import OpenSSL
|
||||
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM, ca)
|
||||
# get url from certificates
|
||||
url = None
|
||||
CN = None
|
||||
Subject = certobj.get_subject().get_components()
|
||||
subj = None
|
||||
for subj in Subject:
|
||||
if subj[0] == 'L':
|
||||
url = "https://" + subj[1] + "/?wsdl"
|
||||
if subj[0] == 'CN':
|
||||
CN = subj[1]
|
||||
|
||||
if subj and url:
|
||||
from calculate.core.client.client_class import Client_suds
|
||||
from client_class import HTTPSClientCertTransport
|
||||
# connect to ca server (url get from certificates)
|
||||
try:
|
||||
client = Client_suds(url, transport=HTTPSClientCertTransport(
|
||||
None, None, path_to_cert))
|
||||
|
||||
client.set_parameters(path_to_cert, None, None)
|
||||
new_crl = client.service.get_crl()
|
||||
if new_crl:
|
||||
if CN and len(CN) > 2:
|
||||
CRL_file = CRL_path + CN
|
||||
else:
|
||||
host = subj[1].split(':')[0]
|
||||
CRL_file = CRL_path + host
|
||||
if new_crl == ' ':
|
||||
open(CRL_file, 'w').close()
|
||||
# if os.path.exists(CRL_file):
|
||||
# os.unlink(CRL_file)
|
||||
continue
|
||||
if os.path.exists(CRL_file):
|
||||
if readFile(CRL_file) == new_crl:
|
||||
continue
|
||||
|
||||
with open(CRL_file, 'w') as fd:
|
||||
fd.write(new_crl)
|
||||
print _("CRL added")
|
||||
except VerifyError as e:
|
||||
print e.value
|
||||
# rm_ca_from_trusted(ca)
|
||||
sys.exit()
|
||||
except Exception:
|
||||
pass
|
||||
find_ca_in_crl(CRL_path, all_ca_certs_list)
|
||||
|
||||
|
||||
def find_ca_in_crl(CRL_path, all_ca_certs_list):
|
||||
import OpenSSL
|
||||
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM,
|
||||
ca)
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
for item in Issuer:
|
||||
if item[0] == 'CN':
|
||||
CN = item[1]
|
||||
break
|
||||
else:
|
||||
continue
|
||||
server_serial = certobj.get_serial_number()
|
||||
CRL = CRL_path + CN
|
||||
if not os.path.exists(CRL):
|
||||
continue
|
||||
|
||||
with open(CRL, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
try:
|
||||
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM,
|
||||
crl)
|
||||
except OpenSSL.SSL.Error:
|
||||
continue
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if server_serial == int(rvk.get_serial(), 16):
|
||||
rm_ca_from_trusted(ca)
|
||||
|
||||
|
||||
def rm_ca_from_trusted(ca_cert):
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
|
||||
user_ca_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_dir = user_ca_dir.replace("~", homePath)
|
||||
user_ca_dir = os.path.join(user_ca_dir, 'ca')
|
||||
user_ca_list = os.path.join(user_ca_dir, 'cert_list')
|
||||
user_ca_db = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_db = user_ca_db.replace("~", homePath)
|
||||
|
||||
system_ca_dir = clVars.Get('cl_core_cert_path')
|
||||
system_ca_db = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
import hashlib
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_cert)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
# search ca certificate in user ca list
|
||||
newfile = ''
|
||||
with open(user_ca_list) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
newfile = ''
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
if words[0] == md5sum:
|
||||
filename = os.path.join(user_ca_dir, words[1])
|
||||
if ca_cert == readFile(filename):
|
||||
os.unlink(filename)
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
|
||||
fd.close()
|
||||
fn = open(user_ca_list, 'w')
|
||||
fn.write(newfile)
|
||||
fn.close()
|
||||
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
|
||||
# open, write and split user ca certificates
|
||||
user_ca_certs = readFile(user_ca_db)
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
|
||||
if ca_cert in user_ca_certs_list:
|
||||
new_user_ca_certs = []
|
||||
for cert in user_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_user_ca_certs.append(cert)
|
||||
else:
|
||||
print _("CA certificate deleted from the user's trusted "
|
||||
"certificates list")
|
||||
|
||||
with open(user_ca_db, 'w') as fd:
|
||||
for cert in new_user_ca_certs:
|
||||
fd.write(cert)
|
||||
|
||||
if not os.path.exists(system_ca_db):
|
||||
open(system_ca_db, 'w').close()
|
||||
|
||||
system_ca_certs = readFile(system_ca_db)
|
||||
system_ca_certs_list = p.findall(system_ca_certs)
|
||||
|
||||
if ca_cert in system_ca_certs_list:
|
||||
new_system_ca_certs = []
|
||||
for cert in system_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_system_ca_certs.append(cert)
|
||||
else:
|
||||
print _('CA certificate deleted from the system trusted '
|
||||
'certificates list')
|
||||
|
||||
fd = open(system_ca_db, 'w')
|
||||
for cert in new_system_ca_certs:
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
|
||||
return 0
|
@ -1,485 +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 __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import urllib2 as u2
|
||||
import os
|
||||
import sys
|
||||
import calculate.contrib
|
||||
from suds.transport.http import HttpTransport
|
||||
import httplib #http.client in python3
|
||||
from httplib import HTTPConnection
|
||||
import socket
|
||||
import ssl
|
||||
import hashlib
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.datavars import DataVars
|
||||
from calculate.lib.utils.files import readFile
|
||||
from suds.client import Client
|
||||
from .cert_verify import verify, get_CRL
|
||||
|
||||
if hasattr(ssl, "PROTOCOL_TLSv1_2"):
|
||||
ssl_version = ssl.PROTOCOL_TLSv1_2
|
||||
else:
|
||||
ssl_version = None
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
flag = 0
|
||||
|
||||
|
||||
class Client_suds(Client):
|
||||
def set_parameters(self, path_to_cert, CERT_FILE, PKEY_FILE):
|
||||
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 + 'sid.int'
|
||||
self.CRL_PATH = path_to_cert + 'ca/crl/'
|
||||
if not os.path.exists(self.CRL_PATH):
|
||||
os.makedirs(self.CRL_PATH)
|
||||
|
||||
|
||||
class clientHTTPSConnection(httplib.HTTPSConnection):
|
||||
def __init__(self, host, port=None, key_file=None, cert_file=None,
|
||||
strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
||||
source_address=None, cert_path=None):
|
||||
HTTPConnection.__init__(self, host, port, strict, timeout,
|
||||
source_address)
|
||||
self.key_file = key_file
|
||||
self.cert_file = cert_file
|
||||
self.cert_path = cert_path
|
||||
self.CRL_PATH = cert_path + 'ca/crl/'
|
||||
|
||||
# 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 (IndexError, IOError):
|
||||
print(_("Certificate not found on the client's side"))
|
||||
return None
|
||||
try:
|
||||
with open(self.trusted_path + filename, 'r') as fd:
|
||||
store_cert = fd.read()
|
||||
if store_cert == server_cert:
|
||||
return filename
|
||||
except IOError:
|
||||
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()
|
||||
import OpenSSL
|
||||
|
||||
for cert in list_ca_certs:
|
||||
system_ca_db = clVarsCore.Get('cl_glob_root_cert')
|
||||
if os.path.exists(system_ca_db):
|
||||
if cert in readFile(system_ca_db):
|
||||
continue
|
||||
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
|
||||
user_root_cert = clVarsCore.Get('cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
if os.path.exists(user_root_cert):
|
||||
if cert in readFile(user_root_cert):
|
||||
continue
|
||||
|
||||
cl_client_cert_dir = clVarsCore.Get('cl_client_cert_dir')
|
||||
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_md5 = cl_client_cert_dir + "/ca/cert_list"
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(cert)
|
||||
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] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
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(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(_("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))
|
||||
cert = client.service.get_ca()
|
||||
if cert == '1':
|
||||
print(_("Invalid server certificate!"))
|
||||
sys.exit()
|
||||
|
||||
if cert == '2':
|
||||
print(_("CA certificate not found on the server"))
|
||||
sys.exit()
|
||||
|
||||
import OpenSSL
|
||||
|
||||
try:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
except (OpenSSL.SSL.Error, IOError):
|
||||
print(_("Error. Certificate not added to the trusted list."))
|
||||
sys.exit()
|
||||
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 = raw_input(_("Add the CA certificate to trusted? y/[n]:"))
|
||||
if ans.lower() in ['y', 'yes']:
|
||||
list_ca_certs.append(cert)
|
||||
self.add_all_ca_cert(list_ca_certs)
|
||||
else:
|
||||
print(_("Certificate not added to trusted"))
|
||||
sys.exit()
|
||||
|
||||
# add certificate server in trusted
|
||||
def add_server_cert(self, cert):
|
||||
import OpenSSL
|
||||
|
||||
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 = raw_input(_("Quit (q)? s/c/[q]: "))
|
||||
if choice.lower() in ['s', 'c']:
|
||||
# self.sock = ssl.wrap_socket(sock)
|
||||
ca_certs = 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':
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
cl_client_cert_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_dir = cl_client_cert_dir + "/ca"
|
||||
|
||||
if not os.path.exists(root_cert_dir):
|
||||
try:
|
||||
os.makedirs(root_cert_dir)
|
||||
except OSError:
|
||||
print(_("Error creating directory %s") % root_cert_dir)
|
||||
sys.exit()
|
||||
|
||||
print('\n' + _("Add the CA and root certificates"))
|
||||
self.list_ca_certs = []
|
||||
self.add_ca_cert(cert, self.list_ca_certs)
|
||||
sys.exit()
|
||||
else:
|
||||
sys.exit()
|
||||
|
||||
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:
|
||||
sys.exit()
|
||||
else:
|
||||
import time
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
try:
|
||||
if ssl_version is None:
|
||||
print(_("SSL library is not support TLSv1_2"))
|
||||
self.sock.close()
|
||||
return 2
|
||||
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ca_certs=root_cert,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_REQUIRED)
|
||||
|
||||
dercert_after_connect = self.sock.getpeercert(True)
|
||||
cert_after_connect = \
|
||||
ssl.DER_cert_to_PEM_cert(dercert_after_connect)
|
||||
if not server_cert == cert_after_connect:
|
||||
print ('\n' +
|
||||
_("WARNING! %s trying to replace the certificate!")
|
||||
% self.host + '\n')
|
||||
self.sock.close()
|
||||
return 2
|
||||
return 0
|
||||
except Exception:
|
||||
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:
|
||||
sys.exit()
|
||||
HTTPSClientCertTransport.filename = self.cert_list(
|
||||
self.host, ca_cert_list, server_cert)
|
||||
if HTTPSClientCertTransport.filename:
|
||||
try:
|
||||
if ssl_version is None:
|
||||
print(_("SSL library is not support TLSv1_2"))
|
||||
HTTPSClientCertTransport.filename = None
|
||||
self.sock.close()
|
||||
return 1
|
||||
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_NONE)
|
||||
dercert_after_connect = self.sock.getpeercert(True)
|
||||
ssl.DER_cert_to_PEM_cert(dercert_after_connect)
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(e)
|
||||
HTTPSClientCertTransport.filename = None
|
||||
return 1
|
||||
else:
|
||||
self.add_server_cert(server_cert)
|
||||
|
||||
def connect(self):
|
||||
"""Connect to a host on a given (SSL) port."""
|
||||
if self.host == '127.0.0.1':
|
||||
self.host = 'localhost'
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout, self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
|
||||
user_root_cert = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
result_user_root = 1
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
result_user_root = self.connect_trusted_root(sock, user_root_cert,
|
||||
self.CRL_PATH)
|
||||
# print 'rur = ',result_user_root
|
||||
if result_user_root == 1:
|
||||
glob_root_cert = clVars.Get('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)
|
||||
# print 'rrc = ',result_root_con
|
||||
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)
|
||||
# print 'rsc = ',result_server_con
|
||||
if result_server_con in [1, 2]:
|
||||
raise Exception
|
||||
# sys.exit(1)
|
||||
elif result_root_con == 2:
|
||||
# sys.exit(1)
|
||||
raise Exception
|
||||
elif result_user_root == 2:
|
||||
# sys.exit(1)
|
||||
raise Exception
|
||||
|
||||
|
||||
class HTTPSClientAuthHandler(u2.HTTPSHandler):
|
||||
def __init__(self, key, cert, cert_path):
|
||||
u2.HTTPSHandler.__init__(self)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = cert_path
|
||||
|
||||
def https_open(self, req):
|
||||
# Rather than pass in a reference to a connection class, we pass in
|
||||
# a reference to a function which, for all intents and purposes,
|
||||
# will behave as a constructor
|
||||
return self.do_open(self.getConnection, req)
|
||||
|
||||
def getConnection(self, host, timeout=300):
|
||||
return clientHTTPSConnection(host, key_file=self.key,
|
||||
cert_file=self.cert,
|
||||
cert_path=self.cert_path)
|
||||
|
||||
|
||||
class HTTPSClientCertTransport(HttpTransport):
|
||||
def __init__(self, key, cert, path_to_cert, *args, **kwargs):
|
||||
HttpTransport.__init__(self, *args, **kwargs)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = path_to_cert
|
||||
|
||||
def u2open(self, u2request):
|
||||
"""
|
||||
Open a connection.
|
||||
@param u2request: A urllib2 request.
|
||||
@type u2request: urllib2.Requet.
|
||||
@return: The opened file-like urllib2 object.
|
||||
@rtype: fp
|
||||
"""
|
||||
tm = self.options.timeout
|
||||
url = u2.build_opener(HTTPSClientAuthHandler(self.key, self.cert,
|
||||
self.cert_path))
|
||||
|
||||
# from urllib2 import URLError
|
||||
# try:
|
||||
if hasattr(self, "u2ver"):
|
||||
if self.u2ver() < 2.6:
|
||||
socket.setdefaulttimeout(tm)
|
||||
return url.open(u2request)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
@ -1,483 +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 urllib2 as u2
|
||||
import os
|
||||
import sys
|
||||
import calculate.contrib
|
||||
from suds.transport.http import HttpTransport
|
||||
import httplib #http.client in python3
|
||||
from httplib import HTTPConnection
|
||||
import socket
|
||||
import ssl
|
||||
import hashlib
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.datavars import DataVars
|
||||
from calculate.lib.utils.files import readFile
|
||||
from suds.client import Client
|
||||
from cert_verify import verify, get_CRL
|
||||
|
||||
if hasattr(ssl, "PROTOCOL_TLSv1_2"):
|
||||
ssl_version = ssl.PROTOCOL_TLSv1_2
|
||||
else:
|
||||
ssl_version = None
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
flag = 0
|
||||
|
||||
|
||||
class Client_suds(Client):
|
||||
def set_parameters(self, path_to_cert, CERT_FILE, PKEY_FILE):
|
||||
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 + 'sid.int'
|
||||
self.CRL_PATH = path_to_cert + 'ca/crl/'
|
||||
if not os.path.exists(self.CRL_PATH):
|
||||
os.makedirs(self.CRL_PATH)
|
||||
|
||||
|
||||
class clientHTTPSConnection(httplib.HTTPSConnection):
|
||||
def __init__(self, host, port=None, key_file=None, cert_file=None,
|
||||
strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
||||
source_address=None, cert_path=None):
|
||||
HTTPConnection.__init__(self, host, port, strict, timeout,
|
||||
source_address)
|
||||
self.key_file = key_file
|
||||
self.cert_file = cert_file
|
||||
self.cert_path = cert_path
|
||||
self.CRL_PATH = cert_path + 'ca/crl/'
|
||||
|
||||
# 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 (IndexError, IOError):
|
||||
print _("Certificate not found on the client's side")
|
||||
return None
|
||||
try:
|
||||
with open(self.trusted_path + filename, 'r') as fd:
|
||||
store_cert = fd.read()
|
||||
if store_cert == server_cert:
|
||||
return filename
|
||||
except IOError:
|
||||
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()
|
||||
import OpenSSL
|
||||
|
||||
for cert in list_ca_certs:
|
||||
system_ca_db = clVarsCore.Get('cl_glob_root_cert')
|
||||
if os.path.exists(system_ca_db):
|
||||
if cert in readFile(system_ca_db):
|
||||
continue
|
||||
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
|
||||
user_root_cert = clVarsCore.Get('cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
if os.path.exists(user_root_cert):
|
||||
if cert in readFile(user_root_cert):
|
||||
continue
|
||||
|
||||
cl_client_cert_dir = clVarsCore.Get('cl_client_cert_dir')
|
||||
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_md5 = cl_client_cert_dir + "/ca/cert_list"
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(cert)
|
||||
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] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
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(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 _("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))
|
||||
cert = client.service.get_ca()
|
||||
if cert == '1':
|
||||
print _("Invalid server certificate!")
|
||||
sys.exit()
|
||||
|
||||
if cert == '2':
|
||||
print _("CA certificate not found on the server")
|
||||
sys.exit()
|
||||
|
||||
import OpenSSL
|
||||
|
||||
try:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
except (OpenSSL.SSL.Error, IOError):
|
||||
print _("Error. Certificate not added to the trusted list.")
|
||||
sys.exit()
|
||||
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 = raw_input(_("Add the CA certificate to trusted? y/[n]:"))
|
||||
if ans.lower() in ['y', 'yes']:
|
||||
list_ca_certs.append(cert)
|
||||
self.add_all_ca_cert(list_ca_certs)
|
||||
else:
|
||||
print _("Certificate not added to trusted")
|
||||
sys.exit()
|
||||
|
||||
# add certificate server in trusted
|
||||
def add_server_cert(self, cert):
|
||||
import OpenSSL
|
||||
|
||||
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 = raw_input(_("Quit (q)? s/c/[q]: "))
|
||||
if choice.lower() in ['s', 'c']:
|
||||
# self.sock = ssl.wrap_socket(sock)
|
||||
ca_certs = 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':
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
cl_client_cert_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
|
||||
root_cert_dir = cl_client_cert_dir + "/ca"
|
||||
|
||||
if not os.path.exists(root_cert_dir):
|
||||
try:
|
||||
os.makedirs(root_cert_dir)
|
||||
except OSError:
|
||||
print _("Error creating directory %s") % root_cert_dir
|
||||
sys.exit()
|
||||
|
||||
print '\n' + _("Add the CA and root certificates")
|
||||
self.list_ca_certs = []
|
||||
self.add_ca_cert(cert, self.list_ca_certs)
|
||||
sys.exit()
|
||||
else:
|
||||
sys.exit()
|
||||
|
||||
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:
|
||||
sys.exit()
|
||||
else:
|
||||
import time
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
try:
|
||||
if ssl_version is None:
|
||||
print _("SSL library is not support TLSv1_2")
|
||||
self.sock.close()
|
||||
return 2
|
||||
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ca_certs=root_cert,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_REQUIRED)
|
||||
|
||||
dercert_after_connect = self.sock.getpeercert(True)
|
||||
cert_after_connect = \
|
||||
ssl.DER_cert_to_PEM_cert(dercert_after_connect)
|
||||
if not server_cert == cert_after_connect:
|
||||
print ('\n' +
|
||||
_("WARNING! %s trying to replace the certificate!")
|
||||
% self.host + '\n')
|
||||
self.sock.close()
|
||||
return 2
|
||||
return 0
|
||||
except Exception:
|
||||
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:
|
||||
sys.exit()
|
||||
HTTPSClientCertTransport.filename = self.cert_list(
|
||||
self.host, ca_cert_list, server_cert)
|
||||
if HTTPSClientCertTransport.filename:
|
||||
try:
|
||||
if ssl_version is None:
|
||||
print _("SSL library is not support TLSv1_2")
|
||||
HTTPSClientCertTransport.filename = None
|
||||
self.sock.close()
|
||||
return 1
|
||||
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_NONE)
|
||||
dercert_after_connect = self.sock.getpeercert(True)
|
||||
ssl.DER_cert_to_PEM_cert(dercert_after_connect)
|
||||
return 0
|
||||
except Exception as e:
|
||||
print e
|
||||
HTTPSClientCertTransport.filename = None
|
||||
return 1
|
||||
else:
|
||||
self.add_server_cert(server_cert)
|
||||
|
||||
def connect(self):
|
||||
"""Connect to a host on a given (SSL) port."""
|
||||
if self.host == '127.0.0.1':
|
||||
self.host = 'localhost'
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout, self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
|
||||
user_root_cert = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~", homePath)
|
||||
result_user_root = 1
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
result_user_root = self.connect_trusted_root(sock, user_root_cert,
|
||||
self.CRL_PATH)
|
||||
# print 'rur = ',result_user_root
|
||||
if result_user_root == 1:
|
||||
glob_root_cert = clVars.Get('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)
|
||||
# print 'rrc = ',result_root_con
|
||||
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)
|
||||
# print 'rsc = ',result_server_con
|
||||
if result_server_con in [1, 2]:
|
||||
raise Exception
|
||||
# sys.exit(1)
|
||||
elif result_root_con == 2:
|
||||
# sys.exit(1)
|
||||
raise Exception
|
||||
elif result_user_root == 2:
|
||||
# sys.exit(1)
|
||||
raise Exception
|
||||
|
||||
|
||||
class HTTPSClientAuthHandler(u2.HTTPSHandler):
|
||||
def __init__(self, key, cert, cert_path):
|
||||
u2.HTTPSHandler.__init__(self)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = cert_path
|
||||
|
||||
def https_open(self, req):
|
||||
# Rather than pass in a reference to a connection class, we pass in
|
||||
# a reference to a function which, for all intents and purposes,
|
||||
# will behave as a constructor
|
||||
return self.do_open(self.getConnection, req)
|
||||
|
||||
def getConnection(self, host, timeout=300):
|
||||
return clientHTTPSConnection(host, key_file=self.key,
|
||||
cert_file=self.cert,
|
||||
cert_path=self.cert_path)
|
||||
|
||||
|
||||
class HTTPSClientCertTransport(HttpTransport):
|
||||
def __init__(self, key, cert, path_to_cert, *args, **kwargs):
|
||||
HttpTransport.__init__(self, *args, **kwargs)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = path_to_cert
|
||||
|
||||
def u2open(self, u2request):
|
||||
"""
|
||||
Open a connection.
|
||||
@param u2request: A urllib2 request.
|
||||
@type u2request: urllib2.Requet.
|
||||
@return: The opened file-like urllib2 object.
|
||||
@rtype: fp
|
||||
"""
|
||||
tm = self.options.timeout
|
||||
url = u2.build_opener(HTTPSClientAuthHandler(self.key, self.cert,
|
||||
self.cert_path))
|
||||
|
||||
# from urllib2 import URLError
|
||||
# try:
|
||||
if hasattr(self, "u2ver"):
|
||||
if self.u2ver() < 2.6:
|
||||
socket.setdefaulttimeout(tm)
|
||||
return url.open(u2request)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
@ -1,136 +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 __future__ import print_function
|
||||
import os
|
||||
import sys
|
||||
import calculate.contrib
|
||||
from suds import MethodNotFound
|
||||
from calculate.core.server.cert_cmd import getHwAddr, getIpLocal
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def get_sid(sid_file):
|
||||
if not os.path.exists(sid_file):
|
||||
with open(sid_file, 'w') as fi:
|
||||
fi.write('0')
|
||||
sid = 0
|
||||
else:
|
||||
with open(sid_file, 'r') as fi:
|
||||
sid = fi.read()
|
||||
return sid
|
||||
|
||||
|
||||
def clear():
|
||||
""" delete caching suds file """
|
||||
import glob
|
||||
|
||||
for filename in glob.glob("/tmp/suds/suds-*"):
|
||||
try:
|
||||
os.unlink(filename)
|
||||
except OSError as e:
|
||||
print(str(e))
|
||||
print(_("Failed to clear the cache! "))
|
||||
return 1
|
||||
|
||||
|
||||
def get_ip_mac_type(client_type=None):
|
||||
results = [getIpLocal(), getHwAddr()]
|
||||
if client_type:
|
||||
results.append(client_type)
|
||||
else:
|
||||
results.append('console')
|
||||
return results
|
||||
|
||||
|
||||
def create_obj(client, method_name):
|
||||
""" create object indispensable for transfer to the server function """
|
||||
sd_item = 0
|
||||
num_port = 0
|
||||
operation_from_port = 0
|
||||
inf_param = 1
|
||||
param_type = 0
|
||||
ns_name = 0
|
||||
ns_type = 1
|
||||
param = 1
|
||||
pref = ""
|
||||
|
||||
sd = client.sd[sd_item]
|
||||
|
||||
# get parameter type
|
||||
operation = sd.ports[num_port][operation_from_port]
|
||||
|
||||
info = operation.methods.get(method_name)
|
||||
if not info:
|
||||
raise MethodNotFound(method_name)
|
||||
type_op = info.binding.input.param_defs(info)[param][inf_param]
|
||||
str_type = type_op.type[param_type]
|
||||
|
||||
# get prefix
|
||||
str_ns = type_op.type[ns_type]
|
||||
nsprefix = sd.prefixes
|
||||
|
||||
# Find a match prefix
|
||||
for pref_num in range(0, len(nsprefix)):
|
||||
if str_ns == sd.prefixes[pref_num][ns_type]:
|
||||
pref = sd.prefixes[pref_num][ns_name]
|
||||
# Combine in a type
|
||||
if not pref:
|
||||
pref = sd.getprefix(str_ns)
|
||||
for_factory = pref + ":" + str_type
|
||||
|
||||
return client.factory.create(for_factory)
|
||||
|
||||
|
||||
def listToArray(client, _list, _type='string'):
|
||||
array = client.factory.create('%sArray' % _type)
|
||||
for i in _list:
|
||||
array['%s' % _type].append(i)
|
||||
return array
|
||||
|
||||
|
||||
def listToArrayArray(client, _list, _type='string'):
|
||||
array_array = client.factory.create('%sArrayArray' % _type)
|
||||
for i in _list:
|
||||
array = client.factory.create('%sArray' % _type)
|
||||
for j in i:
|
||||
array[_type].append(j)
|
||||
array_array['%sArray' % _type].append(array)
|
||||
return array_array
|
||||
|
||||
|
||||
class switch(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
self.fall = False
|
||||
|
||||
def __iter__(self):
|
||||
"""Return the match method once, then stop"""
|
||||
yield self.match
|
||||
raise StopIteration
|
||||
|
||||
def match(self, *args):
|
||||
"""Indicate whether or not to enter a case suite"""
|
||||
if self.fall or not args:
|
||||
return True
|
||||
elif self.value in args: # changed for v1.5, see below
|
||||
self.fall = True
|
||||
return True
|
||||
else:
|
||||
return False
|
@ -1,135 +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
|
||||
import calculate.contrib
|
||||
from suds import MethodNotFound
|
||||
from calculate.core.server.cert_cmd import getHwAddr, getIpLocal
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def get_sid(sid_file):
|
||||
if not os.path.exists(sid_file):
|
||||
with open(sid_file, 'w') as fi:
|
||||
fi.write('0')
|
||||
sid = 0
|
||||
else:
|
||||
with open(sid_file, 'r') as fi:
|
||||
sid = fi.read()
|
||||
return sid
|
||||
|
||||
|
||||
def clear():
|
||||
""" delete caching suds file """
|
||||
import glob
|
||||
|
||||
for filename in glob.glob("/tmp/suds/suds-*"):
|
||||
try:
|
||||
os.unlink(filename)
|
||||
except OSError as e:
|
||||
print str(e)
|
||||
print _("Failed to clear the cache! ")
|
||||
return 1
|
||||
|
||||
|
||||
def get_ip_mac_type(client_type=None):
|
||||
results = [getIpLocal(), getHwAddr()]
|
||||
if client_type:
|
||||
results.append(client_type)
|
||||
else:
|
||||
results.append('console')
|
||||
return results
|
||||
|
||||
|
||||
def create_obj(client, method_name):
|
||||
""" create object indispensable for transfer to the server function """
|
||||
sd_item = 0
|
||||
num_port = 0
|
||||
operation_from_port = 0
|
||||
inf_param = 1
|
||||
param_type = 0
|
||||
ns_name = 0
|
||||
ns_type = 1
|
||||
param = 1
|
||||
pref = ""
|
||||
|
||||
sd = client.sd[sd_item]
|
||||
|
||||
# get parameter type
|
||||
operation = sd.ports[num_port][operation_from_port]
|
||||
|
||||
info = operation.methods.get(method_name)
|
||||
if not info:
|
||||
raise MethodNotFound(method_name)
|
||||
type_op = info.binding.input.param_defs(info)[param][inf_param]
|
||||
str_type = type_op.type[param_type]
|
||||
|
||||
# get prefix
|
||||
str_ns = type_op.type[ns_type]
|
||||
nsprefix = sd.prefixes
|
||||
|
||||
# Find a match prefix
|
||||
for pref_num in range(0, len(nsprefix)):
|
||||
if str_ns == sd.prefixes[pref_num][ns_type]:
|
||||
pref = sd.prefixes[pref_num][ns_name]
|
||||
# Combine in a type
|
||||
if not pref:
|
||||
pref = sd.getprefix(str_ns)
|
||||
for_factory = pref + ":" + str_type
|
||||
|
||||
return client.factory.create(for_factory)
|
||||
|
||||
|
||||
def listToArray(client, _list, _type='string'):
|
||||
array = client.factory.create('%sArray' % _type)
|
||||
for i in _list:
|
||||
array['%s' % _type].append(i)
|
||||
return array
|
||||
|
||||
|
||||
def listToArrayArray(client, _list, _type='string'):
|
||||
array_array = client.factory.create('%sArrayArray' % _type)
|
||||
for i in _list:
|
||||
array = client.factory.create('%sArray' % _type)
|
||||
for j in i:
|
||||
array[_type].append(j)
|
||||
array_array['%sArray' % _type].append(array)
|
||||
return array_array
|
||||
|
||||
|
||||
class switch(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
self.fall = False
|
||||
|
||||
def __iter__(self):
|
||||
"""Return the match method once, then stop"""
|
||||
yield self.match
|
||||
raise StopIteration
|
||||
|
||||
def match(self, *args):
|
||||
"""Indicate whether or not to enter a case suite"""
|
||||
if self.fall or not args:
|
||||
return True
|
||||
elif self.value in args: # changed for v1.5, see below
|
||||
self.fall = True
|
||||
return True
|
||||
else:
|
||||
return False
|
@ -1,171 +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 __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import sys
|
||||
from .function import get_sid
|
||||
|
||||
client_types = "console"
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def pid_inf(client, sid, pids):
|
||||
""" get and show information about process """
|
||||
print("============================")
|
||||
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][3])
|
||||
print(_(u"Process ID: %s") % s[0][0])
|
||||
if s[0][1] == '1':
|
||||
print(_(u"Process active"))
|
||||
elif s[0][1] == '0':
|
||||
print(_(u"Process completed"))
|
||||
else:
|
||||
print(_(u"Process killed"))
|
||||
print(_(u"%s: Process started") % s[0][2])
|
||||
print("============================")
|
||||
return 0
|
||||
|
||||
|
||||
def client_list_pid(client):
|
||||
""" get all process id for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
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]:
|
||||
print("pid - %d" % i)
|
||||
except Exception:
|
||||
print(_("Failed to get PIDs from the server"))
|
||||
return 1
|
||||
return len(list_pid[0])
|
||||
|
||||
|
||||
def gen_pid_ls(client, pid_ls):
|
||||
""" generation list with pid for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
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(_("Failed to get PIDs from the server"))
|
||||
return 0
|
||||
return pid_ls
|
||||
|
||||
|
||||
def client_pid_info(client):
|
||||
""" get information about selected process (or about all) """
|
||||
pid = raw_input(_("PID") + _(": "))
|
||||
try:
|
||||
pid = int(pid)
|
||||
except ValueError:
|
||||
print(_("PID error"))
|
||||
return 1
|
||||
try:
|
||||
pid_ls = []
|
||||
pid_get = [pid]
|
||||
sid = get_sid(client.SID_FILE)
|
||||
if pid > 0:
|
||||
pid_inf(client, sid, pid_get)
|
||||
elif pid == 0:
|
||||
if gen_pid_ls(client, pid_ls):
|
||||
pid_inf(client, sid, pid_ls)
|
||||
except Exception:
|
||||
print(_("Failed to 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
|
||||
|
||||
results = client.service.get_methods(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 (IndexError, AttributeError):
|
||||
pass
|
||||
print('\n' + _("You can execute:"))
|
||||
for num in range(0, len(results[DAT])):
|
||||
print(" %s - %s" % (results[DAT][num][RES][COM],
|
||||
results[DAT][num][RES][METH]))
|
||||
|
||||
|
||||
def client_list_sessions(client):
|
||||
""" get all sessions on server """
|
||||
results = client.service.get_sessions()
|
||||
if results[0][0] == "Permission denied":
|
||||
print(results[0][0])
|
||||
return 1
|
||||
|
||||
print(_("Sessions running:"))
|
||||
for sess in results[0]:
|
||||
print(" - %s" % sess)
|
||||
return 0
|
||||
|
||||
|
||||
def client_pid_kill(client):
|
||||
""" kill process on server """
|
||||
pid = raw_input(_("PID to be killed: "))
|
||||
try:
|
||||
pid = int(pid)
|
||||
except ValueError:
|
||||
print(_("PID error"))
|
||||
return 1
|
||||
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
result = client.service.pid_kill(pid, sid)
|
||||
if result == 0:
|
||||
print(_(" Killed successfully!"))
|
||||
elif result == 2:
|
||||
print(_(" Process completed!"))
|
||||
elif result == -1:
|
||||
print(_(" Certificate not found in the server database!"))
|
||||
elif result == -2:
|
||||
print(_(" Session not matching your certificate!"))
|
||||
elif result == 1:
|
||||
print(_(" Failed to terminate the process!"))
|
@ -1,169 +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
|
||||
from function import get_sid
|
||||
|
||||
client_types = "console"
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def pid_inf(client, sid, pids):
|
||||
""" get and show information about process """
|
||||
print "============================"
|
||||
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][3]
|
||||
print _(u"Process ID: %s") % s[0][0]
|
||||
if s[0][1] == '1':
|
||||
print _(u"Process active")
|
||||
elif s[0][1] == '0':
|
||||
print _(u"Process completed")
|
||||
else:
|
||||
print _(u"Process killed")
|
||||
print _(u"%s: Process started") % s[0][2]
|
||||
print "============================"
|
||||
return 0
|
||||
|
||||
|
||||
def client_list_pid(client):
|
||||
""" get all process id for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
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]:
|
||||
print "pid - %d" % i
|
||||
except Exception:
|
||||
print _("Failed to get PIDs from the server")
|
||||
return 1
|
||||
return len(list_pid[0])
|
||||
|
||||
|
||||
def gen_pid_ls(client, pid_ls):
|
||||
""" generation list with pid for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
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 _("Failed to get PIDs from the server")
|
||||
return 0
|
||||
return pid_ls
|
||||
|
||||
|
||||
def client_pid_info(client):
|
||||
""" get information about selected process (or about all) """
|
||||
pid = raw_input(_("PID") + _(": "))
|
||||
try:
|
||||
pid = int(pid)
|
||||
except ValueError:
|
||||
print _("PID error")
|
||||
return 1
|
||||
try:
|
||||
pid_ls = []
|
||||
pid_get = [pid]
|
||||
sid = get_sid(client.SID_FILE)
|
||||
if pid > 0:
|
||||
pid_inf(client, sid, pid_get)
|
||||
elif pid == 0:
|
||||
if gen_pid_ls(client, pid_ls):
|
||||
pid_inf(client, sid, pid_ls)
|
||||
except Exception:
|
||||
print _("Failed to 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
|
||||
|
||||
results = client.service.get_methods(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 (IndexError, AttributeError):
|
||||
pass
|
||||
print '\n' + _("You can execute:")
|
||||
for num in range(0, len(results[DAT])):
|
||||
print " %s - %s" % (results[DAT][num][RES][COM],
|
||||
results[DAT][num][RES][METH])
|
||||
|
||||
|
||||
def client_list_sessions(client):
|
||||
""" get all sessions on server """
|
||||
results = client.service.get_sessions()
|
||||
if results[0][0] == "Permission denied":
|
||||
print results[0][0]
|
||||
return 1
|
||||
|
||||
print _("Sessions running:")
|
||||
for sess in results[0]:
|
||||
print " - %s" % sess
|
||||
return 0
|
||||
|
||||
|
||||
def client_pid_kill(client):
|
||||
""" kill process on server """
|
||||
pid = raw_input(_("PID to be killed: "))
|
||||
try:
|
||||
pid = int(pid)
|
||||
except ValueError:
|
||||
print _("PID error")
|
||||
return 1
|
||||
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
result = client.service.pid_kill(pid, sid)
|
||||
if result == 0:
|
||||
print _(" Killed successfully!")
|
||||
elif result == 2:
|
||||
print _(" Process completed!")
|
||||
elif result == -1:
|
||||
print _(" Certificate not found in the server database!")
|
||||
elif result == -2:
|
||||
print _(" Session not matching your certificate!")
|
||||
elif result == 1:
|
||||
print _(" Failed to terminate the process!")
|
@ -1,115 +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 __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import sys
|
||||
from .function import get_sid
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def client_sid(sid, client, cert_id):
|
||||
""" get number session from server and write this in file """
|
||||
# lang = raw_input ("Enter language (ru, en, de, fr): ")
|
||||
lang = "ru"
|
||||
new_sid = client.service.post_sid(sid=sid, cert_id=cert_id, lang=lang)
|
||||
fi = open(client.SID_FILE, 'w')
|
||||
sid = str(new_sid[0][0])
|
||||
fi.write(sid)
|
||||
fi.close()
|
||||
if new_sid[0][1] == 1:
|
||||
print(_(" New session"))
|
||||
else:
|
||||
print(_(" Old session"))
|
||||
print(_(" Your session ID = %s") % sid)
|
||||
|
||||
|
||||
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 the 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 Exception:
|
||||
print(_("Failed to delete the SID on the server"))
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def sid_inf(client, sid):
|
||||
""" get information about selected session """
|
||||
s = client.service.sid_info(sid)
|
||||
if s[0][0] == "-1":
|
||||
print(_("Session not registered on the server!"))
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print(_("Failed to obtain the certificate data!"))
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print(_("%s: Permission denied") % s[0][1])
|
||||
return -3
|
||||
|
||||
print("============================")
|
||||
print('\n' + _(u"Session number: %s") % sid)
|
||||
if s[0][5] == "0":
|
||||
print(_(u"Session active"))
|
||||
else:
|
||||
print(_(u"Session inactive"))
|
||||
print(_(u"Certificate number: %s") % s[0][0])
|
||||
print(_(u"Certificate issued on %s") % s[0][1])
|
||||
print(_(u"IP: %s") % s[0][2])
|
||||
print(_(u"MAC: %s") % s[0][3])
|
||||
print(_(u"Client type: %s") % s[0][4])
|
||||
print("============================")
|
||||
return 0
|
||||
|
||||
|
||||
def client_session_info(client):
|
||||
""" select session for get information """
|
||||
sid = raw_input("SID: ")
|
||||
try:
|
||||
sid = int(sid)
|
||||
except ValueError:
|
||||
print(_("Invalid SID"))
|
||||
return 1
|
||||
try:
|
||||
if sid > 0:
|
||||
sid_inf(client, sid)
|
||||
else:
|
||||
print(_("Please enter a correct SID"))
|
||||
except Exception:
|
||||
print(_("Failed to get data"))
|
||||
return 1
|
||||
return 0
|
@ -1,113 +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
|
||||
from function import get_sid
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def client_sid(sid, client, cert_id):
|
||||
""" get number session from server and write this in file """
|
||||
# lang = raw_input ("Enter language (ru, en, de, fr): ")
|
||||
lang = "ru"
|
||||
new_sid = client.service.post_sid(sid=sid, cert_id=cert_id, lang=lang)
|
||||
fi = open(client.SID_FILE, 'w')
|
||||
sid = str(new_sid[0][0])
|
||||
fi.write(sid)
|
||||
fi.close()
|
||||
if new_sid[0][1] == 1:
|
||||
print _(" New session")
|
||||
else:
|
||||
print _(" Old session")
|
||||
print _(" Your session ID = %s") % sid
|
||||
|
||||
|
||||
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 the 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 Exception:
|
||||
print _("Failed to delete the SID on the server")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def sid_inf(client, sid):
|
||||
""" get information about selected session """
|
||||
s = client.service.sid_info(sid)
|
||||
if s[0][0] == "-1":
|
||||
print _("Session not registered on the server!")
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print _("Failed to obtain the certificate data!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print _("%s: Permission denied") % s[0][1]
|
||||
return -3
|
||||
|
||||
print "============================"
|
||||
print '\n' + _(u"Session number: %s") % sid
|
||||
if s[0][5] == "0":
|
||||
print _(u"Session active")
|
||||
else:
|
||||
print _(u"Session inactive")
|
||||
print _(u"Certificate number: %s") % s[0][0]
|
||||
print _(u"Certificate issued on %s") % s[0][1]
|
||||
print _(u"IP: %s") % s[0][2]
|
||||
print _(u"MAC: %s") % s[0][3]
|
||||
print _(u"Client type: %s") % s[0][4]
|
||||
print "============================"
|
||||
return 0
|
||||
|
||||
|
||||
def client_session_info(client):
|
||||
""" select session for get information """
|
||||
sid = raw_input("SID: ")
|
||||
try:
|
||||
sid = int(sid)
|
||||
except ValueError:
|
||||
print _("Invalid SID")
|
||||
return 1
|
||||
try:
|
||||
if sid > 0:
|
||||
sid_inf(client, sid)
|
||||
else:
|
||||
print _("Please enter a correct SID")
|
||||
except Exception:
|
||||
print _("Failed to get data")
|
||||
return 1
|
||||
return 0
|
@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python2
|
||||
# -*- 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 server.cl_server import main
|
||||
# print(main)
|
||||
|
||||
def core_main():
|
||||
import sys
|
||||
|
||||
if hasattr(sys, "setdefaultencoding"):
|
||||
sys.setdefaultencoding("utf-8")
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core', sys.modules[__name__])
|
||||
from traceback import print_exc
|
||||
from os import path
|
||||
|
||||
if not path.exists('/dev/urandom'):
|
||||
sys.stderr.write("/dev/urandom not found\n")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
from server.cl_server import main
|
||||
|
||||
reload(sys)
|
||||
from calculate.lib.datavars import CriticalError, DataVarsError
|
||||
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (CriticalError, DataVarsError) as e:
|
||||
sys.stderr.write("%s\n" % str(e))
|
||||
sys.exit(1)
|
||||
except ImportError as e:
|
||||
print_exc()
|
||||
cannot_import = 'cannot import name '
|
||||
no_module = 'No module named '
|
||||
if e.message.startswith(cannot_import):
|
||||
print (_('Failed to import %s')
|
||||
% e.message.rpartition(cannot_import)[2])
|
||||
elif e.message.startswith(no_module):
|
||||
print (_('No module named %s') %
|
||||
e.message.rpartition(no_module)[2])
|
||||
else:
|
||||
print e.message
|
||||
sys.exit(1)
|
||||
except KeyboardInterrupt:
|
||||
print
|
||||
print _("Task interrupted")
|
||||
|
||||
|
||||
if (__name__ == "__main__"):
|
||||
core_main()
|
@ -1,404 +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
|
||||
|
||||
import calculate.contrib
|
||||
from spyne import rpc
|
||||
from spyne import Service
|
||||
from spyne import String, Integer, Array
|
||||
|
||||
from calculate.core.server.core_interfaces import CoreServiceInterface
|
||||
from calculate.lib.utils.files import readFile
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import getLazyLocalTranslate, setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
__ = getLazyLocalTranslate(_)
|
||||
|
||||
from clean import sid_monitor, monitor
|
||||
from tasks import restart, dbus_stop
|
||||
from loaded_methods import LoadedMethods
|
||||
from api_types import Message, ReturnProgress, Table
|
||||
import post_cert
|
||||
import post_request
|
||||
import send_cert
|
||||
|
||||
String.Attributes.encoding = "utf-8"
|
||||
|
||||
# class Basic(CoreServiceInterface):
|
||||
class Basic(Service, CoreServiceInterface):
|
||||
""" Basic server class """
|
||||
|
||||
SERV_VERS = 0.11
|
||||
glob_process_dict = {}
|
||||
process_pid = {}
|
||||
glob_progress_dict = {}
|
||||
glob_table_dict = {}
|
||||
glob_frame_list = {}
|
||||
manager = None
|
||||
|
||||
data_path = None
|
||||
certbase = None
|
||||
rights = None
|
||||
sids = None
|
||||
pids = None
|
||||
sids_file = None
|
||||
ssl_certificate = None
|
||||
ssl_private_key = None
|
||||
cachedict = {}
|
||||
|
||||
#workaround: Spyne won't let us use self ref in @rpc,
|
||||
# and ctx leads to original service class (Basic in this case)
|
||||
# but some methods are gathered from CoreWsdl classes, so we need
|
||||
# a ref to combined class
|
||||
comb_class_ref = None
|
||||
|
||||
# function getting object from cache
|
||||
@staticmethod
|
||||
def get_cache(sid, meth_name, obj_name):
|
||||
if sid in Basic.cachedict:
|
||||
if meth_name in Basic.cachedict[sid]:
|
||||
if obj_name in Basic.cachedict[sid][meth_name]:
|
||||
return Basic.cachedict[sid][meth_name][obj_name]
|
||||
return None
|
||||
|
||||
# function placing object in cache
|
||||
@staticmethod
|
||||
def set_cache(sid, meth_name, obj_name, obj, smart=True):
|
||||
try:
|
||||
if sid not in Basic.cachedict:
|
||||
Basic.cachedict[sid] = {}
|
||||
if meth_name not in Basic.cachedict[sid]:
|
||||
Basic.cachedict[sid][meth_name] = {}
|
||||
if obj_name not in Basic.cachedict[sid][meth_name]:
|
||||
Basic.cachedict[sid][meth_name][obj_name] = obj
|
||||
return True
|
||||
if smart:
|
||||
for var_name, var_value in obj.__dict__.viewitems():
|
||||
if var_value is not None:
|
||||
setattr(Basic.cachedict[sid][meth_name][obj_name],
|
||||
var_name, var_value)
|
||||
else:
|
||||
Basic.cachedict[sid][meth_name][obj_name] = obj
|
||||
return True
|
||||
except Exception as e:
|
||||
if isinstance(e, SyntaxError):
|
||||
raise
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@staticmethod
|
||||
def clear_cache(sid, meth_name=None, obj_name=None):
|
||||
if sid not in Basic.cachedict:
|
||||
return True
|
||||
if meth_name:
|
||||
if meth_name not in Basic.cachedict[sid]:
|
||||
return True
|
||||
|
||||
if obj_name:
|
||||
if obj_name not in Basic.cachedict[sid][meth_name]:
|
||||
return True
|
||||
else:
|
||||
obj = Basic.cachedict[sid][meth_name].pop(obj_name, None)
|
||||
if hasattr(obj, 'close'):
|
||||
obj.close()
|
||||
else:
|
||||
method_dict = Basic.cachedict[sid].pop(meth_name, None)
|
||||
for val_obj in method_dict.values():
|
||||
if hasattr(val_obj, 'close'):
|
||||
val_obj.close()
|
||||
else:
|
||||
session_dict = Basic.cachedict.pop(sid, None)
|
||||
for method_dict in session_dict.values():
|
||||
for val_obj in method_dict.values():
|
||||
if hasattr(val_obj, 'close'):
|
||||
val_obj.close()
|
||||
|
||||
@staticmethod
|
||||
def clear_cache_method(method=None):
|
||||
for k, v in Basic.cachedict.items():
|
||||
Basic.clear_cache(k, method)
|
||||
|
||||
@staticmethod
|
||||
def set_paths(data_path, certbase, serv_certbase, rights,
|
||||
group_rights, sids, pids, sids_pids, sids_file, pids_file,
|
||||
max_sid, max_pid, cert_path, log_filename,
|
||||
cert="server.crt", key="server.key"):
|
||||
""" set system path for main class """
|
||||
Basic.data_path = data_path
|
||||
Basic.certbase = certbase
|
||||
Basic.serv_certbase = serv_certbase
|
||||
Basic.rights = rights
|
||||
Basic.group_rights = group_rights
|
||||
Basic.sids = sids
|
||||
Basic.pids = pids
|
||||
Basic.sids_pids = sids_pids
|
||||
Basic.sids_file = sids_file
|
||||
Basic.pids_file = pids_file
|
||||
Basic.ssl_certificate = cert
|
||||
Basic.ssl_private_key = key
|
||||
Basic.cert_path = cert_path
|
||||
Basic.max_sid = int(max_sid)
|
||||
Basic.max_pid = int(max_pid)
|
||||
Basic.log_filename = log_filename
|
||||
|
||||
|
||||
@staticmethod
|
||||
def set_comb_class_ref(comb_class_ref):
|
||||
Basic.comb_class_ref = comb_class_ref
|
||||
|
||||
@staticmethod
|
||||
def run_tasks():
|
||||
"""
|
||||
Запуситить регулярные задачи
|
||||
"""
|
||||
import threading
|
||||
# start monitor and sid_monitor threads
|
||||
monitoring = threading.Thread(target=monitor,
|
||||
args=(Basic.certbase, Basic.sids_file))
|
||||
sid_mon = threading.Thread(target=sid_monitor,
|
||||
args=(Basic.sids_file, Basic.sids, Basic.comb_class_ref))
|
||||
restart_watchdog = threading.Thread(target=restart,
|
||||
args=(Basic.comb_class_ref.glob_process_dict,))
|
||||
dbus_stop_mon = threading.Thread(target=dbus_stop,
|
||||
args=(Basic.comb_class_ref.glob_process_dict, Basic.comb_class_ref.sids, Basic.comb_class_ref))
|
||||
threads = []
|
||||
for thread, success, failed in (
|
||||
(monitoring, _("General monitoring started"),
|
||||
_("Monitoring error")),
|
||||
(sid_mon, _("Session monitoring started"),
|
||||
_("Session monitoring failed")),
|
||||
(restart_watchdog, _("Restart watchdog started"),
|
||||
_("Restart watchdog failed")),
|
||||
(dbus_stop_mon, _("Inactive watchdog started"),
|
||||
_("Inactive watchdog failed"))):
|
||||
try:
|
||||
threads.append(thread)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
print success
|
||||
except Exception:
|
||||
print failed
|
||||
print
|
||||
|
||||
@staticmethod
|
||||
def killall():
|
||||
sys.stdout.write('\n' + _('Closing all processes') + '...')
|
||||
sys.stdout.flush()
|
||||
import time
|
||||
# Waiting for closing
|
||||
for pid in Basic.process_pid.keys():
|
||||
try:
|
||||
os.kill(Basic.process_pid[pid].pid, 2)
|
||||
except OSError:
|
||||
pass
|
||||
while True:
|
||||
num_active_process = 0
|
||||
for pid in Basic.process_pid.keys():
|
||||
if Basic.process_pid[pid].is_alive():
|
||||
num_active_process += 1
|
||||
|
||||
if num_active_process:
|
||||
sys.stdout.write('.')
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
print '\n' + _('All processes are closed.')
|
||||
return 0
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
@rpc(_returns=Array(Integer))
|
||||
def post_cert(ctx):
|
||||
# import post_cert
|
||||
returns = post_cert.serv_post_cert(Basic.comb_class_ref)
|
||||
return returns
|
||||
|
||||
@rpc(Integer, _returns=Integer)
|
||||
def clear_session_cache(ctx, sid):
|
||||
check_sid = Basic.comb_class_ref.check_sid_cert(Basic.comb_class_ref, sid)
|
||||
if not check_sid:
|
||||
return 1
|
||||
# clear cache
|
||||
Basic.clear_cache(sid)
|
||||
return 0
|
||||
|
||||
@rpc(Integer, String, _returns=Integer)
|
||||
def clear_method_cache(ctx, sid, method_name):
|
||||
check_sid = Basic.comb_class_ref.check_sid_cert(Basic.comb_class_ref, sid)
|
||||
if not check_sid:
|
||||
return 1
|
||||
# clear cache
|
||||
Basic.clear_cache(sid, method_name)
|
||||
return 0
|
||||
|
||||
@rpc(Integer, Integer, _returns=Integer)
|
||||
def clear_pid_cache(ctx, sid, pid):
|
||||
if not Basic.comb_class_ref.check_sid_cert(Basic.comb_class_ref, sid):
|
||||
return 1
|
||||
|
||||
if pid in Basic.comb_class_ref.find_sid_pid_file(Basic.comb_class_ref, sid):
|
||||
# clear pid cache
|
||||
Basic.comb_class_ref.delete_pid(Basic.comb_class_ref, sid, pid)
|
||||
return 0
|
||||
|
||||
return 2
|
||||
|
||||
@rpc(Integer, Integer, String, _returns=Array(Integer))
|
||||
def post_sid(self, sid, cert_id, lang):
|
||||
return Basic.comb_class_ref.sid_cmp(Basic.comb_class_ref, sid, cert_id, lang)
|
||||
|
||||
@rpc(Integer, String, _returns=(Array(Integer), Array(Integer)))
|
||||
def init_session(ctx, sid, lang):
|
||||
return Basic.comb_class_ref.serv_init_session(Basic.comb_class_ref, sid, lang)
|
||||
|
||||
@rpc(Integer, _returns=Array(String))
|
||||
# @Dec.check_permissions(['del_sid'])
|
||||
def del_sid(self, sid):
|
||||
flag = Basic.comb_class_ref.del_sid_pid(Basic.comb_class_ref, sid)
|
||||
Basic.comb_class_ref.clear_cache(int(sid))
|
||||
if not flag:
|
||||
return Basic.comb_class_ref.del_sid_from_file(Basic.comb_class_ref,
|
||||
sid)
|
||||
else:
|
||||
return ['-1']
|
||||
|
||||
@rpc(Integer, Integer, _returns=Integer)
|
||||
def pid_kill(ctx, pid, sid):
|
||||
return Basic.comb_class_ref.serv_pid_kill(Basic.comb_class_ref, pid, sid)
|
||||
|
||||
@rpc(Integer, _returns=Array(Integer))
|
||||
def list_pid(ctx, sid):
|
||||
return Basic.comb_class_ref.find_sid_pid_file(Basic.comb_class_ref, sid)
|
||||
|
||||
@rpc(Integer, String, _returns=Array(Array(String)))
|
||||
def get_methods(ctx, sid, client_type):
|
||||
return map(lambda x: map(str, x),
|
||||
Basic.comb_class_ref.serv_get_methods(Basic.comb_class_ref, client_type))
|
||||
|
||||
@rpc(Integer, _returns=Array(String))
|
||||
@LoadedMethods.core_method(rights=["get-sessions"])
|
||||
# @Dec.console('list-session')
|
||||
def get_sessions(ctx, sid):
|
||||
if not Basic.comb_class_ref.check_sid_cert(Basic.comb_class_ref, sid):
|
||||
return ['']
|
||||
return Basic.comb_class_ref.serv_get_sessions(Basic.comb_class_ref)
|
||||
|
||||
@rpc(Integer, Integer, _returns=Array(String))
|
||||
# @Dec.check_permissions(["pid_info"])
|
||||
def pid_info(ctx, sid, pid):
|
||||
return Basic.comb_class_ref.serv_pid_info(Basic.comb_class_ref, sid, pid)
|
||||
|
||||
@rpc(Integer, _returns=Array(String))
|
||||
@LoadedMethods.core_method(rights=["session_info"])
|
||||
def sid_info(ctx, sid):
|
||||
return Basic.comb_class_ref.serv_sid_info(Basic.comb_class_ref, sid)
|
||||
|
||||
@rpc(Integer, String, _returns=Array(String))
|
||||
@LoadedMethods.check_permissions(["view_cert_right"])
|
||||
# @Dec.console('view-cert-right')
|
||||
# @Dec.gui('System')
|
||||
def view_cert_right(ctx, cert_id, client_type):
|
||||
return Basic.comb_class_ref.serv_view_cert_right(Basic.comb_class_ref,
|
||||
cert_id, Basic.data_path, client_type)
|
||||
|
||||
@rpc(Integer, _returns=Integer)
|
||||
def active_client(ctx, sid):
|
||||
return Basic.comb_class_ref.active_clients(Basic.comb_class_ref, sid)
|
||||
|
||||
@rpc(String, String, String, String, _returns=String)
|
||||
def post_client_request(ctx, request, ip, mac, client_type):
|
||||
res = post_request.serv_post_client_request(request, Basic.data_path,
|
||||
ip, mac, client_type,
|
||||
Basic.certbase,
|
||||
Basic.cert_path)
|
||||
return res
|
||||
|
||||
@rpc(String, String, _returns=Array(String))
|
||||
def get_client_cert(ctx, req_id, request):
|
||||
res = post_request.serv_get_client_cert(req_id, request,
|
||||
Basic.data_path, Basic.certbase,
|
||||
Basic.cert_path)
|
||||
return res
|
||||
|
||||
@rpc(String, String, String, _returns=String)
|
||||
def post_server_request(ctx, request, ip, mac):
|
||||
res = post_request.serv_post_server_request(request, Basic.data_path,
|
||||
ip, mac, Basic.serv_certbase,
|
||||
Basic.cert_path)
|
||||
return res
|
||||
|
||||
@rpc(String, String, _returns=Array(String))
|
||||
def get_server_cert(ctx, req_id, request):
|
||||
res = post_request.serv_get_server_request(req_id, request,
|
||||
Basic.data_path,
|
||||
Basic.serv_certbase,
|
||||
Basic.cert_path)
|
||||
return res
|
||||
|
||||
@rpc(_returns=String)
|
||||
def get_crl(self):
|
||||
if os.path.exists(Basic.data_path + '/server_certs/ca.crl'):
|
||||
return readFile(Basic.data_path + '/server_certs/ca.crl')
|
||||
return ' '
|
||||
|
||||
@rpc(_returns=String)
|
||||
def get_server_host_name(ctx):
|
||||
import OpenSSL
|
||||
|
||||
cert = readFile(Basic.ssl_certificate)
|
||||
cert_obj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
subject = cert_obj.get_subject().get_components()
|
||||
for subj in subject:
|
||||
if subj[0] == 'CN':
|
||||
return subj[1]
|
||||
return ''
|
||||
|
||||
@rpc(_returns=String)
|
||||
def get_ca(ctx):
|
||||
return send_cert.get_ca(Basic.cert_path)
|
||||
|
||||
#moved here from api_types:
|
||||
|
||||
@rpc(Integer, Integer, String, _returns=Array(Message))
|
||||
# @Dec.check_permissions()
|
||||
def get_frame(ctx, sid, pid, client_type):
|
||||
return Basic.comb_class_ref.client_get_frame(Basic.comb_class_ref, sid, pid, client_type)
|
||||
|
||||
@rpc(Integer, Integer, _returns=Array(Message))
|
||||
def get_entire_frame(self, sid, pid):
|
||||
return Basic.comb_class_ref.client_get_entire_frame(Basic.comb_class_ref, sid, pid)
|
||||
|
||||
@rpc(Integer, Integer, Integer, _returns=ReturnProgress)
|
||||
# @Dec.check_permissions()
|
||||
def get_progress(self, sid, pid, id):
|
||||
return Basic.comb_class_ref.client_get_progress(Basic.comb_class_ref, sid, pid, id)
|
||||
|
||||
@rpc(Integer, Integer, Integer, _returns=Table)
|
||||
# @Dec.check_permissions()
|
||||
def get_table(self, sid, pid, id):
|
||||
return Basic.comb_class_ref.client_get_table(Basic.comb_class_ref, sid, pid, id)
|
||||
|
||||
# get messages, transferred from client
|
||||
@rpc(Integer, Integer, String, _returns=Message)
|
||||
# @Dec.check_permissions()
|
||||
def send_message(self, sid, pid, text):
|
||||
return Basic.comb_class_ref.client_send_message(Basic.comb_class_ref, sid, pid, text)
|
@ -1,499 +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 cert_cmd
|
||||
import post_request
|
||||
import datetime
|
||||
import subprocess
|
||||
import shutil
|
||||
|
||||
from calculate.core.client.cert_func import new_key_req
|
||||
from calculate.core.client.function import get_ip_mac_type
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.utils.files import (makeDirectory, pathJoin, readFile,
|
||||
writeFile, readFileEx)
|
||||
from calculate.lib.utils.mount import isMount
|
||||
from calculate.core.server.admin import Admins
|
||||
import os
|
||||
import hashlib
|
||||
import pwd
|
||||
import socket
|
||||
import sys
|
||||
import re
|
||||
|
||||
_ = lambda x: x
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def parse_cert_date(date):
|
||||
year = int(date[:4])
|
||||
month = int(date[4:6])
|
||||
day = int(date[6:8])
|
||||
hour = int(date[8:10])
|
||||
minute = int(date[10:12])
|
||||
sec = int(date[12:14])
|
||||
return datetime.datetime(year, month, day, hour, minute, sec)
|
||||
|
||||
|
||||
def check(cert, key):
|
||||
error_flag = 0
|
||||
if not os.path.isfile(cert):
|
||||
error_flag = 1
|
||||
print _('Certificate %s not found') % cert
|
||||
print key, cert
|
||||
if not os.path.isfile(key):
|
||||
error_flag = 1
|
||||
print _('Private key %s not found') % key
|
||||
if os.path.isfile(cert) and os.path.isfile(key):
|
||||
import OpenSSL
|
||||
# check correspondence certificate and private key
|
||||
cmd_cert = 'openssl x509 -noout -modulus -in ' + cert
|
||||
cmd_key = 'openssl rsa -noout -modulus -in ' + key
|
||||
p_cert = subprocess.Popen(cmd_cert.split(), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
p_key = subprocess.Popen(cmd_key.split(), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
if not p_cert.stdout.read().strip() == p_key.stdout.read().strip():
|
||||
print _('The certificate does not match the private key')
|
||||
error_flag = 1
|
||||
|
||||
# check certificate date
|
||||
cert_data = readFile(cert)
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert_data)
|
||||
certobj.get_notBefore()
|
||||
try:
|
||||
not_after = parse_cert_date(certobj.get_notAfter())
|
||||
not_before = parse_cert_date(certobj.get_notBefore())
|
||||
|
||||
date = datetime.datetime.now()
|
||||
|
||||
if not_before > date:
|
||||
print _('Certificate creation date later than current date')
|
||||
error_flag = 1
|
||||
elif not_after < date:
|
||||
print _('Certificate expired')
|
||||
error_flag = 1
|
||||
except ValueError:
|
||||
print _('Failed to get certificate work date')
|
||||
error_flag = 1
|
||||
|
||||
sys.exit(error_flag)
|
||||
|
||||
|
||||
def init(cert, key, cert_path, data_path, certbase, args, port):
|
||||
if args.remove_certificates:
|
||||
key_force(cert_path, data_path)
|
||||
|
||||
new_serv_cert = False
|
||||
if not check_serv_cert(cert_path):
|
||||
print _('Generating the server certificate')
|
||||
for step in range(2):
|
||||
args = change_args(args, step)
|
||||
create_server_cert(cert, key, cert_path, args, port)
|
||||
new_serv_cert = True
|
||||
else:
|
||||
print _('Server certificate now exists.')
|
||||
|
||||
os.chmod(data_path, 0700)
|
||||
|
||||
def force_user_cert(server_cert, cert_path, data_path, cert_base, user_name,
|
||||
dv=None):
|
||||
def is_crypthome_notmount(dv, username):
|
||||
dv.Set('ur_login', user_name, force=True)
|
||||
homedir = dv.Get('ur_home_path')
|
||||
if (dv.GetBool('ur_home_crypt_set') and
|
||||
'.Private' not in isMount(homedir)):
|
||||
return True
|
||||
return False
|
||||
|
||||
if not check_client_cert(user_name, server_cert=server_cert):
|
||||
print _('Generating the client certificate')
|
||||
else:
|
||||
print _('Regenerating the client certificate')
|
||||
group = "all"
|
||||
if dv:
|
||||
admins = Admins(dv)
|
||||
if user_name not in admins:
|
||||
admins[user_name] = group
|
||||
admins.save()
|
||||
group = admins[user_name]
|
||||
if is_crypthome_notmount(dv, user_name):
|
||||
print _("User profile is encrypted. Please perform user login for "
|
||||
"complete of certificate generation")
|
||||
return
|
||||
create_client_cert(server_cert, cert_path, data_path, cert_base,
|
||||
user_name, group)
|
||||
|
||||
|
||||
def check_serv_cert(cert_path):
|
||||
if os.path.isfile(os.path.join(cert_path, 'server.crt')) and \
|
||||
os.path.isfile(os.path.join(cert_path, 'server.key')):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def check_client_cert(user_name, server_cert=None):
|
||||
client_cert_path = check_user_path(user_name)
|
||||
if server_cert:
|
||||
server_host_name = get_certificate_dn(server_cert)
|
||||
else:
|
||||
server_host_name = socket.getfqdn()
|
||||
crt_fn = os.path.join(client_cert_path, server_host_name + '.crt')
|
||||
key_fn = os.path.join(client_cert_path, server_host_name + '.key')
|
||||
if os.path.isfile(crt_fn) and os.path.isfile(key_fn):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def change_args(args, step=None):
|
||||
if step == 0:
|
||||
args.host = False
|
||||
args.gen_root_cert = True
|
||||
args.root_host = False
|
||||
args.use_root_cert = False
|
||||
elif step == 1:
|
||||
args.gen_root_cert = False
|
||||
args.use_root_cert = True
|
||||
|
||||
return args
|
||||
|
||||
|
||||
def create_server_cert(cert, key, cert_path, args, port):
|
||||
cert_cmd.check_server_certificate(cert, key, cert_path, args, port,
|
||||
auto=True)
|
||||
|
||||
|
||||
def create_client_cert(server_cert, cert_path, data_path, certbase, user_name,
|
||||
group="all"):
|
||||
client_cert_path = check_user_path(user_name)
|
||||
if not client_cert_path:
|
||||
print _('no path to the client certificate')
|
||||
return 1
|
||||
req_id = create_request(server_cert, cert_path, data_path, certbase,
|
||||
client_cert_path, user_name)
|
||||
sign_certificate(req_id, cert_path, data_path, group)
|
||||
get_certificate(cert_path, data_path, certbase, client_cert_path, user_name,
|
||||
server_cert=server_cert)
|
||||
|
||||
|
||||
def check_user_path(user_name):
|
||||
try:
|
||||
pwdObj = pwd.getpwnam(user_name)
|
||||
except KeyError as e:
|
||||
print e
|
||||
return None
|
||||
|
||||
home_dir = pwdObj.pw_dir
|
||||
if not os.path.isdir(home_dir):
|
||||
if not makeDirectory(home_dir):
|
||||
return None
|
||||
os.chown(home_dir, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(home_dir, 0700)
|
||||
calc_dir = os.path.join(home_dir, '.calculate')
|
||||
cert_dir = os.path.join(calc_dir, 'client_cert')
|
||||
for directory in [calc_dir, cert_dir]:
|
||||
if not os.path.isdir(directory):
|
||||
if not makeDirectory(directory):
|
||||
return None
|
||||
os.chown(directory, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(directory, 0755)
|
||||
|
||||
for path in os.walk(cert_dir):
|
||||
os.chown(path[0], pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
for _file in path[2]:
|
||||
fn = pathJoin(path[0], _file)
|
||||
if os.path.isfile(fn):
|
||||
os.chown(fn, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(fn, 0644)
|
||||
return cert_dir
|
||||
|
||||
|
||||
def create_request(server_cert, cert_path, data_path, certbase,
|
||||
client_cert_path, user_name):
|
||||
server_host_name = get_certificate_dn(server_cert)
|
||||
|
||||
key = os.path.join(client_cert_path, server_host_name + '.key')
|
||||
|
||||
client_req_file = new_key_req(key, client_cert_path, server_host_name,
|
||||
auto=True)
|
||||
|
||||
try:
|
||||
pwdObj = pwd.getpwnam(user_name)
|
||||
except KeyError as e:
|
||||
print e
|
||||
return None
|
||||
for files in [client_req_file, key + '_pub']:
|
||||
if os.path.exists(files):
|
||||
os.chown(files, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(files, 0644)
|
||||
if os.path.exists(key):
|
||||
os.chown(key, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(key, 0600)
|
||||
|
||||
ip, mac, client_type = get_ip_mac_type()
|
||||
data = readFile(client_req_file)
|
||||
|
||||
req_id = post_request.serv_post_client_request(
|
||||
data, data_path, ip, mac, client_type, certbase, cert_path)
|
||||
|
||||
fc = open(os.path.join(client_cert_path, 'req_id'), 'w')
|
||||
fc.write(req_id)
|
||||
fc.close()
|
||||
return req_id
|
||||
|
||||
|
||||
def sign_certificate(req_id, cert_path, data_path, group="all"):
|
||||
cert_cmd.sing_req_by_server(req_id, cert_path, data_path, auto=True,
|
||||
group_name=group)
|
||||
|
||||
|
||||
def get_certificate_dn(cert_file):
|
||||
cert_data = readFile(cert_file)
|
||||
if cert_data:
|
||||
import OpenSSL
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert_data)
|
||||
cert_info = dict(certobj.get_subject().get_components())
|
||||
return cert_info["CN"]
|
||||
return "localhost"
|
||||
|
||||
|
||||
def clear_localuser_certificates(certbase):
|
||||
"""
|
||||
Удалить все пользовательские сертификаты, создаваемые для локальных
|
||||
пользователей
|
||||
"""
|
||||
certdata = readFileEx(certbase, grab=True)
|
||||
certdn = os.path.dirname(certbase)
|
||||
# оставляем только сертификаты, которые не содержат отметки
|
||||
# для какого локального пользователя они созданы
|
||||
writedata = "\n".join(x[0] for x in re.findall("^((\S+\s+){6}\S+)\s*$",
|
||||
certdata, flags=re.M))
|
||||
with writeFile(certbase) as f:
|
||||
f.write("%s\n"%writedata)
|
||||
|
||||
# удаляем физически сертификаты, созданные для локальных пользователей
|
||||
for localcert in re.finditer("^(\S+)\s+(\S+\s+){6}\S+\s*$",
|
||||
certdata, flags=re.M):
|
||||
cert_fn = "%s/%s.crt"%(certdn, localcert.group(1))
|
||||
try:
|
||||
os.unlink(cert_fn)
|
||||
except OSError:
|
||||
print _("Failed to remove local client certificate") % cert_fn
|
||||
|
||||
|
||||
def get_certificate(cert_path, data_path, certbase, client_cert_path,
|
||||
user_name, server_cert=None):
|
||||
req_id_file = os.path.join(client_cert_path, 'req_id')
|
||||
if not os.path.exists(req_id_file):
|
||||
print _("request not sent or file %s deleted") % req_id_file
|
||||
return 1
|
||||
fc = open(req_id_file, 'r')
|
||||
req_id = fc.read()
|
||||
fc.close()
|
||||
|
||||
if server_cert:
|
||||
server_host_name = get_certificate_dn(server_cert)
|
||||
else:
|
||||
server_host_name = socket.getfqdn()
|
||||
|
||||
req_file = os.path.join(client_cert_path, server_host_name + '.csr')
|
||||
if not os.path.exists(req_file):
|
||||
print _('Request %s not found') % req_file
|
||||
return 1
|
||||
request = readFile(req_file)
|
||||
md5 = hashlib.md5()
|
||||
md5.update(request)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
result = post_request.serv_get_client_cert(
|
||||
req_id, md5sum, data_path, certbase, cert_path,
|
||||
localuser=user_name)
|
||||
|
||||
cert = result[0]
|
||||
if len(result) > 1:
|
||||
ca_root = result[1]
|
||||
else:
|
||||
return None
|
||||
|
||||
if cert == '1':
|
||||
print _('The signature request was rejected!')
|
||||
return 1
|
||||
elif cert == '2':
|
||||
print _("The signature request has not been examined yet.")
|
||||
print _("Your request ID = %s") % req_id
|
||||
return 1
|
||||
elif cert == '3':
|
||||
print _("The signature request does not match earlier data.")
|
||||
return 1
|
||||
elif cert == '4':
|
||||
print _("The request was sent from another IP.")
|
||||
return 1
|
||||
cert_file = os.path.join(client_cert_path, server_host_name + '.crt')
|
||||
fc = open(cert_file, 'w')
|
||||
fc.write(cert)
|
||||
fc.close()
|
||||
|
||||
try:
|
||||
pwdObj = pwd.getpwnam(user_name)
|
||||
except KeyError, e:
|
||||
print e
|
||||
return None
|
||||
os.chown(cert_file, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(cert_file, 0600)
|
||||
|
||||
os.unlink(req_id_file)
|
||||
print _('Certificate saved. Your certificate ID: %s') % req_id
|
||||
|
||||
if ca_root:
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
system_ca_db = clVars.Get('cl_glob_root_cert')
|
||||
if os.path.exists(system_ca_db):
|
||||
if ca_root in readFile(system_ca_db):
|
||||
return 0
|
||||
|
||||
ca_dir = os.path.join(client_cert_path, 'ca')
|
||||
if not os.path.isdir(ca_dir):
|
||||
os.makedirs(ca_dir)
|
||||
os.chown(ca_dir, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(ca_dir, 0755)
|
||||
root_cert_md5 = os.path.join(ca_dir, "cert_list")
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_root)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
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:
|
||||
import OpenSSL
|
||||
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, ca_root)
|
||||
issuer = certobj.get_issuer().get_components()
|
||||
for item in issuer:
|
||||
if item[0] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
fc = open(root_cert_md5, "a")
|
||||
fc.write('%s %s\n' % (md5sum, filename))
|
||||
fc.close()
|
||||
os.chown(root_cert_md5, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(root_cert_md5, 0644)
|
||||
|
||||
if not filename:
|
||||
print _('Field "CN" not found in the certificate!')
|
||||
return 1
|
||||
|
||||
ca_cert = os.path.join(ca_dir, filename)
|
||||
fd = open(ca_cert, 'w')
|
||||
fd.write(ca_root)
|
||||
fd.close()
|
||||
os.chown(ca_cert, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(ca_cert, 0644)
|
||||
|
||||
user_root_cert = os.path.join(ca_dir, 'ca_root.crt')
|
||||
fa = open(user_root_cert, 'a')
|
||||
fa.write(ca_root)
|
||||
fa.close()
|
||||
os.chown(user_root_cert, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(user_root_cert, 0644)
|
||||
# print _("Certificate added")
|
||||
# else:
|
||||
# print _("file with the CA certificate now exists")
|
||||
|
||||
trust_dir = os.path.join(client_cert_path, 'trusted')
|
||||
if not os.path.isdir(trust_dir):
|
||||
os.makedirs(trust_dir)
|
||||
os.chown(trust_dir, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(trust_dir, 0755)
|
||||
|
||||
ca_certs = os.path.join(trust_dir, "cert.list")
|
||||
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs, "w")
|
||||
fc.close()
|
||||
os.chown(ca_certs, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(ca_certs, 0644)
|
||||
|
||||
host = 'localhost'
|
||||
filename = host
|
||||
cert_file_trust = os.path.join(trust_dir, filename)
|
||||
fc = open(cert_file_trust, "w")
|
||||
fc.write(ca_root)
|
||||
fc.close()
|
||||
os.chown(cert_file_trust, pwdObj.pw_uid, pwdObj.pw_gid)
|
||||
os.chmod(cert_file_trust, 0644)
|
||||
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()
|
||||
return 0
|
||||
|
||||
|
||||
def key_force(cert_path, data_path):
|
||||
while True:
|
||||
try:
|
||||
resp = raw_input(_('Do you really want to remove all '
|
||||
'certificates, requests and config files from '
|
||||
'the server?') + ' (yes/no): ')
|
||||
except KeyboardInterrupt:
|
||||
resp = 'no'
|
||||
if resp.lower() in ['n', 'no']:
|
||||
return 0
|
||||
elif resp.lower() in ['y', 'yes']:
|
||||
break
|
||||
|
||||
if os.path.isdir(cert_path):
|
||||
shutil.rmtree(cert_path)
|
||||
remove_dirs = ['conf', 'server_certs', 'client_certs', 'pids', 'sids']
|
||||
for rm_dir in remove_dirs:
|
||||
remove_dir = os.path.join(data_path, rm_dir)
|
||||
if os.path.isdir(remove_dir):
|
||||
shutil.rmtree(remove_dir)
|
||||
|
||||
remove_files = ['sid.db', 'sid_pid']
|
||||
for rm_file in remove_files:
|
||||
remove_file = os.path.join(data_path, rm_file)
|
||||
if os.path.isfile(remove_file):
|
||||
os.unlink(remove_file)
|
File diff suppressed because it is too large
Load Diff
@ -1,382 +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 os
|
||||
from calculate.lib.utils.tools import unpack_single_opts
|
||||
import cert_cmd
|
||||
import pwd
|
||||
from calculate.core.server.func import clearDataVars
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
import calculate.contrib
|
||||
# from spyne.protocol.http import HttpRpc
|
||||
# from spyne.protocol.xml import XmlDocument
|
||||
# from spyne.protocol.json import JsonDocument
|
||||
from spyne.protocol.soap import Soap11
|
||||
from spyne import Application
|
||||
# from spyne.server.wsgi import WsgiApplication
|
||||
|
||||
from spyne_adapter import CoreInnerWsdl, make_service
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
_("User must be root")
|
||||
_('Failed to import %s')
|
||||
_('No module named %s')
|
||||
|
||||
|
||||
@clearDataVars
|
||||
def main(*args, **keywords):
|
||||
_args = list(unpack_single_opts(sys.argv[1:]))
|
||||
if os.path.basename(sys.argv[0]) != 'cl-core':
|
||||
parser = cert_cmd.parse(full=False)
|
||||
args, unknown_args = parser.parse_known_args(_args)
|
||||
args.method = '_temp_'
|
||||
else:
|
||||
parser = cert_cmd.parse(full=True)
|
||||
args, unknown_args = parser.parse_known_args(_args)
|
||||
if args.method:
|
||||
parser = cert_cmd.parse(full=False)
|
||||
args, unknown_args = parser.parse_known_args(_args)
|
||||
if not args.method:
|
||||
if unknown_args:
|
||||
args = parser.parse_args(_args)
|
||||
|
||||
if args.help and not args.method:
|
||||
parser.print_help()
|
||||
return 0
|
||||
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
|
||||
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')
|
||||
data_path = ob.Get('cl_core_data')
|
||||
local_data_path = ob.Get('cl_core_local_data')
|
||||
certbase = ob.Get('cl_core_database')
|
||||
serv_certbase = ob.Get('cl_core_serv_database')
|
||||
rights = ob.Get('cl_core_rights')
|
||||
group_rights = ob.Get('cl_core_group_rights_path')
|
||||
sids = ob.Get('cl_core_sids_path')
|
||||
pids = ob.Get('cl_core_pids_path')
|
||||
sids_pids = ob.Get('cl_core_sids_pids')
|
||||
sids_file = ob.Get('cl_core_sids_file')
|
||||
pids_file = ob.Get('cl_core_pids_file')
|
||||
max_sid = ob.Get('cl_core_max_sid')
|
||||
max_pid = ob.Get('cl_core_max_pid')
|
||||
cert_path = ob.Get('cl_core_cert_path')
|
||||
cert = ob.Get('cl_core_cert')
|
||||
key = ob.Get('cl_core_key')
|
||||
cl_ver = ob.Get('cl_ver')
|
||||
log_path_var = ob.Get('cl_log_path')
|
||||
cl_core_port = ob.GetInteger('cl_core_port')
|
||||
port = cl_core_port
|
||||
file_logger = None
|
||||
|
||||
# создать симлинки на команды
|
||||
if not args.method and args.create_symlink:
|
||||
from func import create_symlink, initialization
|
||||
|
||||
initialization(cl_wsdl)
|
||||
create_symlink(local_data_path, data_path)
|
||||
return 0
|
||||
|
||||
if args.version:
|
||||
print cl_ver
|
||||
return 0
|
||||
|
||||
log_filename = None
|
||||
|
||||
if ob.Get('cl_ebuild_phase') == '' and os.getuid() == 0:
|
||||
import logging
|
||||
import logging.handlers
|
||||
|
||||
# logging.raiseExceptions = 0
|
||||
|
||||
log_path = args.log_path if args.log_path else log_path_var
|
||||
|
||||
if not os.path.exists(log_path):
|
||||
os.makedirs(log_path)
|
||||
log_filename = os.path.join(log_path, 'logging_cl_core.out')
|
||||
file_logger = logging.getLogger('MyLogger')
|
||||
file_logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Add the log message handler to the logger
|
||||
try:
|
||||
handler = logging.handlers.RotatingFileHandler(
|
||||
log_filename, maxBytes=10000000, backupCount=3)
|
||||
|
||||
file_logger.addHandler(handler)
|
||||
|
||||
# debug
|
||||
if args.debug:
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger('spyne.server.wsgi')
|
||||
logger.setLevel(logging.DEBUG)
|
||||
except IOError:
|
||||
pass
|
||||
|
||||
from urllib2 import URLError
|
||||
|
||||
from traceback import print_exc
|
||||
|
||||
ob.close()
|
||||
if not args.method:
|
||||
try:
|
||||
port = args.port or cl_core_port
|
||||
if args.check:
|
||||
import bootstrap
|
||||
|
||||
bootstrap.check(cert, key)
|
||||
return 0
|
||||
|
||||
if args.bootstrap_user_name:
|
||||
import bootstrap
|
||||
bootstrap.init(cert, key, cert_path, data_path, certbase, args,
|
||||
port)
|
||||
if not args.cert_user_name:
|
||||
return 0
|
||||
if args.clear_user_cert:
|
||||
import bootstrap
|
||||
bootstrap.clear_localuser_certificates(certbase)
|
||||
if not args.cert_user_name:
|
||||
return 0
|
||||
if args.cert_user_name:
|
||||
cert_user_name = args.cert_user_name
|
||||
try:
|
||||
pwd.getpwnam(cert_user_name)
|
||||
except KeyError:
|
||||
print _("User %s does not exist") % cert_user_name
|
||||
return 1
|
||||
|
||||
import bootstrap
|
||||
bootstrap.force_user_cert(cert, cert_path, data_path,
|
||||
certbase, cert_user_name, dv=ob)
|
||||
return 0
|
||||
if args.revoke_cert_id:
|
||||
cert_cmd.revoke_signed_cert(args.revoke_cert_id, data_path,
|
||||
cert_path)
|
||||
return 0
|
||||
if (args.host or args.gen_root_cert or args.root_host or
|
||||
args.use_root_cert):
|
||||
cert_cmd.check_server_certificate(cert, key, cert_path, args,
|
||||
port)
|
||||
return 0
|
||||
if args.id_client_req:
|
||||
cert_cmd.sing_req_by_server(args.id_client_req, cert_path,
|
||||
data_path)
|
||||
return 0
|
||||
if args.Id:
|
||||
cert_cmd.view_cert(args, certbase, data_path, rights,
|
||||
group_rights)
|
||||
return 0
|
||||
if args.cert_id:
|
||||
cert_cmd.view_signed_cert(args, serv_certbase, data_path)
|
||||
return 0
|
||||
if args.req_id:
|
||||
cert_cmd.view_client_request(args, certbase, data_path)
|
||||
return 0
|
||||
# Sign request by root certificate
|
||||
if args.id_server_req:
|
||||
cert_cmd.sing_req_by_root(args, cert_path, data_path)
|
||||
return 0
|
||||
if args.id_del_req or args.id_del_client_req:
|
||||
cert_cmd.del_request(args.id_del_req, args.id_del_client_req,
|
||||
serv_certbase, certbase, data_path)
|
||||
return 0
|
||||
except BaseException as e:
|
||||
from urllib2 import URLError
|
||||
|
||||
if isinstance(e, URLError) and log_filename:
|
||||
if file_logger:
|
||||
fd = open(log_filename, 'a')
|
||||
file_logger.debug(print_exc(file=fd))
|
||||
fd.close()
|
||||
print e
|
||||
else:
|
||||
raise
|
||||
params_list = ["start", "create_symlink", "method",
|
||||
"list_methods"]
|
||||
for param in params_list:
|
||||
if hasattr(args, param) and getattr(args, param):
|
||||
break
|
||||
else:
|
||||
parser.print_help()
|
||||
return 0
|
||||
#####################
|
||||
# importing other modules
|
||||
from func import initialization
|
||||
|
||||
outer_wsdl_classes = initialization(cl_wsdl)
|
||||
|
||||
pack = "calculate.core.server"
|
||||
import importlib
|
||||
|
||||
func_metaclass = importlib.import_module('%s.func_metaclass' % pack)
|
||||
core_wsdl_classes = []
|
||||
core_wsdl_classes.append(func_metaclass.Func_MetaClass)
|
||||
|
||||
from calculate.core.server.baseClass import Basic
|
||||
# make server metaclass
|
||||
if args.method or args.list_methods:
|
||||
from local_call import local_method, LocalCall
|
||||
|
||||
ClService = CoreInnerWsdl("ClService",
|
||||
tuple([LocalCall] + outer_wsdl_classes + [Basic] + core_wsdl_classes),
|
||||
{
|
||||
"__metaclass__" : CoreInnerWsdl
|
||||
})
|
||||
tc = ClService()
|
||||
tc.set_comb_class_ref(tc)
|
||||
return local_method(tc, args, unknown_args)
|
||||
|
||||
ClService = make_service(Basic, core_wsdl_classes, outer_wsdl_classes, "ClService")
|
||||
|
||||
from server_class import ClApplication, OpenSSLAdapter
|
||||
#do we even need this anymore?
|
||||
tc = ClService()
|
||||
App = Application([ClService], 'tns',
|
||||
name="ClApplication",
|
||||
in_protocol=Soap11(),
|
||||
out_protocol=Soap11(),
|
||||
)
|
||||
# delete all sid and pid informations file
|
||||
wsgi_application = ClApplication(App, log=file_logger)
|
||||
cert_cmd.create_path(data_path, certbase, rights, group_rights,
|
||||
local_data_path)
|
||||
|
||||
# set all path
|
||||
tc.set_paths(data_path, certbase, serv_certbase,
|
||||
rights, group_rights, sids, pids, sids_pids,
|
||||
sids_file, pids_file, max_sid,
|
||||
max_pid, cert_path, log_filename,
|
||||
cert, key)
|
||||
|
||||
tc.set_comb_class_ref(tc)
|
||||
tc.run_tasks()
|
||||
|
||||
|
||||
|
||||
max_num = 99999999
|
||||
import calculate.contrib
|
||||
from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher
|
||||
|
||||
dispatcher = WSGIPathInfoDispatcher({'': wsgi_application})
|
||||
server = CherryPyWSGIServer(('0.0.0.0', port), dispatcher,
|
||||
numthreads=10, max=max_num,
|
||||
request_queue_size=max_num)
|
||||
|
||||
# logger = logging.getLogger("spyne.application")
|
||||
# logger.setLevel(0)
|
||||
print _("listening to https://0.0.0.0:%d") % port
|
||||
print _("wsdl is located at: https://0.0.0.0:%d/?wsdl") % port
|
||||
|
||||
|
||||
|
||||
|
||||
ca_cert = cert_path + "/ca_root.crt"
|
||||
if not os.path.exists(ca_cert):
|
||||
ca_cert = None
|
||||
|
||||
ssl_adapter = OpenSSLAdapter(cert, key, ca_cert)
|
||||
|
||||
ssl_adapter.certbase = certbase
|
||||
|
||||
server.ssl_adapter = ssl_adapter
|
||||
server.certbase = certbase
|
||||
server.serv_certbase = serv_certbase
|
||||
server.rights = rights
|
||||
server.group_rights = group_rights
|
||||
server.sids = sids
|
||||
server.pids = pids
|
||||
server.sids_file = sids_file
|
||||
server.pids_file = pids_file
|
||||
server.data_path = data_path
|
||||
server.cert_path = cert_path
|
||||
|
||||
server.ssl_certificate = cert
|
||||
server.ssl_private_key = key
|
||||
from OpenSSL.SSL import Error as SSLError
|
||||
import socket
|
||||
|
||||
try:
|
||||
if args.pidfile:
|
||||
try:
|
||||
with open(args.pidfile, "w") as f:
|
||||
f.write(str(os.getpid()))
|
||||
except OSError:
|
||||
sys.stderr.write(_("failed to create PID file %s")
|
||||
% args.pidfile + "\n")
|
||||
sys.exit(1)
|
||||
# For cleaning of sessions at server reboot
|
||||
from clean import clean
|
||||
from gen_pid import clear_finished_pids
|
||||
from calculate.lib.utils.files import writeFile
|
||||
|
||||
clean(sids_file, pids_file, sids_pids, sids, pids)
|
||||
clear_finished_pids(ob)
|
||||
print _("Server started")
|
||||
dbus_stop_file = ob.Get('cl_core_dbus_stop_path')
|
||||
if args.inactiveclose:
|
||||
try:
|
||||
writeFile(dbus_stop_file).close()
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
else:
|
||||
if os.path.exists(dbus_stop_file):
|
||||
os.unlink(dbus_stop_file)
|
||||
server.start()
|
||||
except KeyboardInterrupt:
|
||||
try:
|
||||
ClService.killall()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
print '\n' + _("Server stopped")
|
||||
server.stop()
|
||||
sys.exit(0)
|
||||
except socket.error, e:
|
||||
if e.message == "No socket could be created":
|
||||
print _("No socket could be created")
|
||||
print _('Port %d already in use') % port
|
||||
else:
|
||||
if file_logger:
|
||||
fd = open(log_filename, 'a')
|
||||
file_logger.debug(print_exc(file=fd))
|
||||
fd.close()
|
||||
print e
|
||||
except SSLError:
|
||||
print '\n', _('Server certificate not found') # , e
|
||||
print _("use cl-core with option --gen-cert-by HOST "
|
||||
"(--get-cert-from HOST) or --use-root-as-server)")
|
||||
except Exception:
|
||||
if file_logger:
|
||||
fd = open(log_filename, 'a')
|
||||
file_logger.debug(print_exc(file=fd))
|
||||
fd.close()
|
||||
|
||||
server.stop()
|
||||
if args.pidfile:
|
||||
if os.path.exists(args.pidfile):
|
||||
os.unlink(args.pidfile)
|
||||
sys.exit(0)
|
@ -1,190 +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 glob
|
||||
import sys
|
||||
import time
|
||||
import datetime
|
||||
import pickle
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.core.server.core_interfaces import CoreServiceInterface
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def clean(sid_file, pid_file, sid_pid, sids_dir, pids_dir):
|
||||
"""
|
||||
Удалить все файлы сервера после перезапуска
|
||||
"""
|
||||
for fn in (sid_file, pid_file, sid_pid):
|
||||
if os.path.exists(fn):
|
||||
try:
|
||||
os.unlink(fn)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
for dn in (sids_dir, pids_dir):
|
||||
if os.path.isdir(dn):
|
||||
for filename in glob.glob(os.path.join(dn, "*.sid")):
|
||||
try:
|
||||
os.unlink(filename)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class CoreWsdl(CoreServiceInterface):
|
||||
# watch for process
|
||||
@staticmethod
|
||||
def watcher_pid_proc(cls, sid, pid):
|
||||
period = 2
|
||||
time.sleep(period)
|
||||
try:
|
||||
# while process status "Active"
|
||||
while cls.glob_process_dict[pid]['status'] == 1:
|
||||
# frequency check
|
||||
time.sleep(period)
|
||||
|
||||
cls.delete_pid(cls, sid, pid)
|
||||
except IOError as e:
|
||||
print 'Except IOError', str(e)
|
||||
except Exception:
|
||||
print _("PID %d watcher error") % pid
|
||||
try:
|
||||
cls.delete_pid(cls, sid, pid)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
@staticmethod
|
||||
def delete_pid(cls, sid, pid):
|
||||
while len(cls.glob_frame_list[pid]) > \
|
||||
cls.glob_process_dict[pid]['counter']:
|
||||
time.sleep(1)
|
||||
methodname = cls.glob_process_dict[pid]['method_name']
|
||||
if methodname:
|
||||
cls.clear_cache(sid, methodname)
|
||||
cls.del_pid(cls, pid)
|
||||
cls.del_pid_from_sid_pid(cls, pid)
|
||||
|
||||
|
||||
def monitor(certbase, sid_file):
|
||||
""" function to delete old session """
|
||||
# Get value of period and lifetime session from DataVars
|
||||
try:
|
||||
ob = DataVarsCore()
|
||||
ob.importCore()
|
||||
|
||||
if not ob.flIniFile():
|
||||
sys.exit(1)
|
||||
period = float(ob.Get('cl_core_monitor_period'))
|
||||
sid_live = float(ob.Get('cl_core_sid_live'))
|
||||
except Exception:
|
||||
print _("Variable cl_core_monitor_period or cl_core_sid_live not "
|
||||
"found")
|
||||
raise
|
||||
# Check lifetime. if necessary, remove
|
||||
while True:
|
||||
# check session
|
||||
try:
|
||||
sid_file_t = sid_file + '_temp'
|
||||
fd = open(sid_file, 'r')
|
||||
ft = open(sid_file_t, 'w')
|
||||
while 1:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (EOFError, KeyError, IOError):
|
||||
break
|
||||
# how time exists session
|
||||
delta = datetime.datetime.now() - list_sid[2]
|
||||
# if not outdated, then leave
|
||||
if delta.seconds < sid_live * 60:
|
||||
pickle.dump(list_sid, ft)
|
||||
fd.close()
|
||||
ft.close()
|
||||
|
||||
# copy all from temp file
|
||||
ft = open(sid_file_t, 'rb')
|
||||
fd = open(sid_file, 'wb')
|
||||
ft.seek(0)
|
||||
fd.write(ft.read())
|
||||
ft.close()
|
||||
fd.close()
|
||||
|
||||
# Delete temp file
|
||||
os.unlink(sid_file_t)
|
||||
except (IOError, OSError):
|
||||
return 1
|
||||
|
||||
# Частота проверки
|
||||
time.sleep(60 * period)
|
||||
|
||||
|
||||
# check client's presence
|
||||
def sid_monitor(sid_fn, sids_dn, cls):
|
||||
# check interval
|
||||
period = 21
|
||||
while True:
|
||||
try:
|
||||
sids = []
|
||||
# create, if file not exists
|
||||
if not os.path.exists(sid_fn):
|
||||
temp = open(sid_fn, 'w')
|
||||
temp.close()
|
||||
fd = open(sid_fn, 'r')
|
||||
while 1:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (EOFError, KeyError, IOError):
|
||||
break
|
||||
# add session id in sesession list
|
||||
sids.append(list_sid[0])
|
||||
fd.close()
|
||||
except (IOError, OSError):
|
||||
print _("Error reading SID files")
|
||||
return
|
||||
|
||||
try:
|
||||
# for each session
|
||||
for filename in sids:
|
||||
# find file this session
|
||||
sid_path = sids_dn + "/%d.sid" % filename
|
||||
with cls.sid_locker:
|
||||
if os.path.isfile(sid_path):
|
||||
with open(sid_path) as fd:
|
||||
# read information about session
|
||||
sid_inf = pickle.load(fd)
|
||||
# if number of missed inspections more 3
|
||||
if sid_inf[1] > 3:
|
||||
# flag client absence
|
||||
sid_inf[2] = 1
|
||||
fd.close()
|
||||
if os.path.isfile(sid_path):
|
||||
# add to digit missed inspections
|
||||
# client constantly nulls this value!
|
||||
ft = open(sid_path, 'w')
|
||||
if sid_inf[1] < 4:
|
||||
sid_inf[1] += 1
|
||||
pickle.dump(sid_inf, ft)
|
||||
ft.close()
|
||||
except (IOError, OSError, KeyError):
|
||||
pass
|
||||
# check period
|
||||
time.sleep(period)
|
@ -1,247 +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 urllib2 as u2
|
||||
import os
|
||||
import sys
|
||||
import calculate.contrib
|
||||
from suds.transport.http import HttpTransport
|
||||
from httplib import HTTPConnection, HTTPSConnection
|
||||
import socket
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
class clientHTTPSConnection(HTTPSConnection):
|
||||
def __init__(self, host, port=None, key_file=None, cert_file=None,
|
||||
strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
||||
source_address=None, cert_path=None):
|
||||
HTTPConnection.__init__(self, host, port, strict, timeout,
|
||||
source_address)
|
||||
self.key_file = key_file
|
||||
self.cert_file = cert_file
|
||||
self.cert_path = cert_path
|
||||
|
||||
# get filename store cert server
|
||||
def cert_list(self, host, ca_certs, server_cert):
|
||||
if not os.path.exists(self.ca_path):
|
||||
try:
|
||||
os.makedirs(self.ca_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 (IOError, IndexError):
|
||||
print _("Certificate not found on the client's side")
|
||||
return None
|
||||
try:
|
||||
fd = open(self.ca_path + filename, 'r')
|
||||
store_cert = fd.read()
|
||||
fd.close()
|
||||
if store_cert == server_cert:
|
||||
return filename
|
||||
except IOError as e:
|
||||
print _("Failed to open the file") + "%s%s %s" % (self.ca_path,
|
||||
filename, str(e))
|
||||
return None
|
||||
|
||||
# add certificate server in trusted
|
||||
def add_server_cert(self, cert):
|
||||
print _("Untrusted server certificate!")
|
||||
import OpenSSL
|
||||
|
||||
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])
|
||||
|
||||
choice = raw_input(
|
||||
_("add this certificate to trusted and continue? y/[n]: "))
|
||||
if choice in ['y', 'yes', 'Y', 'YES']:
|
||||
ca_certs = self.ca_path + "cert.list"
|
||||
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs, "w")
|
||||
fc.close()
|
||||
|
||||
filename = self.host
|
||||
fc = open(self.ca_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] == self.host:
|
||||
return 0
|
||||
# Open file with compliance server certificates and server hostname
|
||||
fcl = open(ca_certs, "a")
|
||||
fcl.write(self.host + ' ' + filename + '\n')
|
||||
fcl.close()
|
||||
|
||||
else:
|
||||
sys.exit()
|
||||
|
||||
def connect_trusted_server(self, sock):
|
||||
import ssl
|
||||
|
||||
if hasattr(ssl, "PROTOCOL_TLSv1_2"):
|
||||
ssl_version = ssl.PROTOCOL_TLSv1_2
|
||||
else:
|
||||
print _("SSL library is not support TLSv1_2")
|
||||
return 1
|
||||
self.ca_path = self.cert_path + "ca/"
|
||||
ca_certs = self.ca_path + "cert.list"
|
||||
server_cert = ssl.get_server_certificate(addr=(self.host, self.port))
|
||||
if (not hasattr(HTTPSClientsCertTransport, 'filename') or
|
||||
HTTPSClientsCertTransport.filename is None):
|
||||
HTTPSClientsCertTransport.filename = self.cert_list(
|
||||
self.host, ca_certs, server_cert)
|
||||
if HTTPSClientsCertTransport.filename:
|
||||
try:
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_NONE)
|
||||
|
||||
dercert_after_connect = self.sock.getpeercert(True)
|
||||
cert_after_connect = ssl.DER_cert_to_PEM_cert(
|
||||
dercert_after_connect)
|
||||
filename2 = self.cert_list(self.host, ca_certs,
|
||||
cert_after_connect)
|
||||
|
||||
if not HTTPSClientsCertTransport.filename == filename2:
|
||||
print '\n' + _("WARNING!!! %s trying to replace the "
|
||||
"certificate!") % self.host + '\n'
|
||||
self.sock.close()
|
||||
return 2
|
||||
return 0
|
||||
except Exception:
|
||||
print _("Error. The server certificate and the private "
|
||||
"key are probably invalid!")
|
||||
HTTPSClientsCertTransport.filename = None
|
||||
return 1
|
||||
else:
|
||||
self.sock = ssl.wrap_socket(sock)
|
||||
self.add_server_cert(server_cert)
|
||||
|
||||
def connect(self):
|
||||
"""Connect to a host on a given (SSL) port."""
|
||||
timeout = 15
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
timeout, self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
if not clVars.flIniFile():
|
||||
sys.exit(1)
|
||||
import ssl
|
||||
|
||||
if hasattr(ssl, "PROTOCOL_TLSv1_2"):
|
||||
ssl_version = ssl.PROTOCOL_TLSv1_2
|
||||
else:
|
||||
print _("SSL library is not support TLSv1_2")
|
||||
sys.exit(1)
|
||||
|
||||
self.sock = ssl.wrap_socket(sock,
|
||||
certfile=self.cert_file,
|
||||
keyfile=self.key_file,
|
||||
ssl_version=ssl_version,
|
||||
cert_reqs=ssl.CERT_NONE)
|
||||
|
||||
|
||||
class HTTPSClientAuthHandler(u2.HTTPSHandler):
|
||||
def __init__(self, key, cert, cert_path):
|
||||
u2.HTTPSHandler.__init__(self)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = cert_path
|
||||
|
||||
def https_open(self, req):
|
||||
# Rather than pass in a reference to a connection class, we pass in
|
||||
# a reference to a function which, for all intents and purposes,
|
||||
# will behave as a constructor
|
||||
return self.do_open(self.getConnection, req)
|
||||
|
||||
def getConnection(self, host, timeout=300):
|
||||
return clientHTTPSConnection(host, key_file=self.key,
|
||||
cert_file=self.cert,
|
||||
cert_path=self.cert_path)
|
||||
|
||||
|
||||
class HTTPSClientsCertTransport(HttpTransport):
|
||||
def __init__(self, key, cert, path_to_cert, *args, **kwargs):
|
||||
HttpTransport.__init__(self, *args, **kwargs)
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = path_to_cert
|
||||
|
||||
def u2open(self, u2request):
|
||||
"""
|
||||
Open a connection.
|
||||
@param u2request: A urllib2 request.
|
||||
@type u2request: urllib2.Requet.
|
||||
@return: The opened file-like urllib2 object.
|
||||
@rtype: fp
|
||||
"""
|
||||
tm = self.options.timeout
|
||||
url = u2.build_opener(HTTPSClientAuthHandler(self.key, self.cert,
|
||||
self.cert_path))
|
||||
|
||||
# from urllib2 import URLError
|
||||
# try:
|
||||
if hasattr(self, "u2ver"):
|
||||
if self.u2ver() < 2.6:
|
||||
socket.setdefaulttimeout(tm)
|
||||
return url.open(u2request)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
||||
else:
|
||||
return url.open(u2request, timeout=tm)
|
@ -1,189 +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
|
||||
from M2Crypto import RSA, X509, EVP, m2
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
from binascii import hexlify
|
||||
import hashlib
|
||||
from calculate.lib.utils.text import _u8
|
||||
|
||||
from M2Crypto import m2
|
||||
from M2Crypto.X509 import X509_Extension
|
||||
from calculate.lib.utils.files import writeFile, readFile
|
||||
from ctypes import *
|
||||
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
def passphrase_callback(v):
|
||||
return ""
|
||||
|
||||
|
||||
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, port):
|
||||
""" 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()
|
||||
c = raw_input(_("Enter the certificate date manually? [y]/n: "))
|
||||
if c.lower() in ['n', 'no']:
|
||||
name.CN = 'root_cert' # (Common Name);
|
||||
name.OU = 'www.calculate-linux.ru' # (Organization Unit);
|
||||
name.O = 'calculate-linux' # (Organization Name);
|
||||
name.L = '' # (Locality Name);
|
||||
name.ST = 'Spb' # (State Name);
|
||||
name.C = 'En' # (Country);
|
||||
else:
|
||||
import socket
|
||||
|
||||
print _('Do not use spaces or tabs.')
|
||||
host_name = socket.getfqdn()
|
||||
# if serv_host == host_name:
|
||||
# print '\n'+_("Want to create self-signed certificate?\n"
|
||||
# "Use key --gen-cert-self")
|
||||
# return None
|
||||
if serv_host in host_name:
|
||||
host_name = host_name.replace('.' + serv_host, '')
|
||||
list_host_name = host_name.split('.')
|
||||
print 'list_host_name = ', list_host_name
|
||||
result_host_name = \
|
||||
list_host_name[len(list_host_name) - 1] + "." + serv_host
|
||||
else:
|
||||
host_name = socket.getfqdn()
|
||||
list_host_name = host_name.split('.')
|
||||
result_host_name = list_host_name[0] + "." + serv_host
|
||||
|
||||
def cleardata(x):
|
||||
if x:
|
||||
return x.replace(' ', '_').replace('\t', '_')
|
||||
return ""
|
||||
|
||||
_CN = raw_input(_('Hostname [%s] : ') % _u8(result_host_name))
|
||||
name.CN = _CN or result_host_name or ""
|
||||
_OU = raw_input(_('Organization unit: '))
|
||||
name.OU = cleardata(_OU)
|
||||
_O = raw_input(_('Organization name: '))
|
||||
name.O = cleardata(_O)
|
||||
network = _('Full network address (host:port)')
|
||||
_L = raw_input(network + ' [%s:%d]: ' % (_u8(host_name), port))
|
||||
name.L = cleardata(_L) or (_u8(host_name) + ':' + str(port))
|
||||
_ST = raw_input(_('City: '))
|
||||
name.ST = cleardata(_ST)
|
||||
_C = raw_input(_('Country (two letters only!): '))
|
||||
name.C = _C or "C"
|
||||
|
||||
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
|
||||
|
||||
class CreateCertError(Exception):
|
||||
pass
|
||||
|
||||
def create_selfsigned_ca(dn_data, keyfile, certfile):
|
||||
from OpenSSL import crypto
|
||||
|
||||
certpem = readFile(keyfile)
|
||||
if not certpem:
|
||||
raise CreateCertError(_("Key file {} not found").format(keyfile))
|
||||
|
||||
try:
|
||||
pkey = crypto.load_privatekey(
|
||||
crypto.FILETYPE_PEM, certpem)
|
||||
ca = crypto.X509()
|
||||
ca.set_version(2)
|
||||
subject = ca.get_subject()
|
||||
subject.countryName = dn_data['C']
|
||||
subject.commonName = dn_data['CN']
|
||||
subject.stateOrProvinceName = dn_data['ST']
|
||||
subject.localityName = dn_data['L']
|
||||
subject.organizationName = dn_data['O']
|
||||
subject.organizationalUnitName = dn_data['OU']
|
||||
|
||||
ca.gmtime_adj_notBefore(-60*60*24)
|
||||
ca.gmtime_adj_notAfter(60*60*24*365*20)
|
||||
ca.set_issuer(subject)
|
||||
ca.set_pubkey(pkey)
|
||||
ca.add_extensions([
|
||||
crypto.X509Extension(b'basicConstraints', True, b'CA:TRUE'),
|
||||
#crypto.X509Extension(b'keyUsage', False, b'keyCertSign, cRLSign'),
|
||||
crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', subject=ca)])
|
||||
ca.add_extensions([crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid:always',issuer=ca)])
|
||||
ca.sign(pkey, 'sha1')
|
||||
|
||||
with writeFile(certfile) as f:
|
||||
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca))
|
||||
except crypto.Error as e:
|
||||
raise CreateCertError(str(e))
|
||||
|
||||
def sign_client_certifacation_request(ca_keyfile, ca_certfile, requestfile, out_cert, group):
|
||||
from OpenSSL import crypto
|
||||
cakeyfilepem = readFile(ca_keyfile)
|
||||
cacertpem = readFile(ca_certfile)
|
||||
requestpem = readFile(requestfile)
|
||||
if not cakeyfilepem:
|
||||
raise CreateCertError(
|
||||
_("Key file {} not found").format(ca_keyfile))
|
||||
if not cacertpem:
|
||||
raise CreateCertError(
|
||||
_("CA certitficate file {} not found").format(ca_certfile))
|
||||
if not requestpem:
|
||||
raise CreateCertError(
|
||||
_("Request file {} not found").format(requestfile))
|
||||
|
||||
try:
|
||||
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, cakeyfilepem)
|
||||
ca = crypto.load_certificate(crypto.FILETYPE_PEM, cacertpem)
|
||||
req = crypto.load_certificate_request(crypto.FILETYPE_PEM, requestpem)
|
||||
|
||||
cert = crypto.X509()
|
||||
cert.set_version(2)
|
||||
cert.gmtime_adj_notBefore(-60*60*24)
|
||||
cert.gmtime_adj_notAfter(60*60*24*365*20)
|
||||
cert.set_issuer(ca.get_subject())
|
||||
cert.set_subject(req.get_subject())
|
||||
cert.set_pubkey(req.get_pubkey())
|
||||
|
||||
cert.add_extensions([
|
||||
crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'),
|
||||
crypto.X509Extension(b'nsCertType', False, b'client'),
|
||||
crypto.X509Extension(b'keyUsage', False, b'digitalSignature, keyEncipherment'),
|
||||
crypto.X509Extension(b'extendedKeyUsage', False, b'clientAuth'),
|
||||
crypto.X509Extension(b'nsComment', False, 'group:{}'.format(group)),
|
||||
])
|
||||
cert.sign(pkey, 'sha1')
|
||||
|
||||
with writeFile(out_cert) as f:
|
||||
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
|
||||
except crypto.Error as e:
|
||||
raise CreateCertError(str(e))
|
File diff suppressed because it is too large
Load Diff
@ -1,259 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
|
||||
#
|
||||
# Session management
|
||||
#
|
||||
# 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 datetime
|
||||
import threading
|
||||
import random
|
||||
import pickle
|
||||
from calculate.core.server.core_interfaces import CoreServiceInterface
|
||||
from cert_cmd import find_cert_id
|
||||
|
||||
|
||||
class CoreWsdl(CoreServiceInterface):
|
||||
sid_locker = threading.Lock()
|
||||
|
||||
# delete client session from file (close session)
|
||||
@staticmethod
|
||||
def del_sid_from_file(cls, sid):
|
||||
try:
|
||||
# temp file
|
||||
sid_file = cls.sids_file
|
||||
sid_file_t = sid_file + 'temp'
|
||||
|
||||
with cls.sid_locker:
|
||||
fd = open(sid_file, 'r')
|
||||
ft = open(sid_file_t, 'w')
|
||||
while True:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (EOFError, IOError, KeyError):
|
||||
break
|
||||
# Leave all but removed
|
||||
if sid != list_sid[0]:
|
||||
pickle.dump(list_sid, ft)
|
||||
fd.close()
|
||||
ft.close()
|
||||
|
||||
# copy all from temp file
|
||||
ft = open(sid_file_t, 'rb')
|
||||
fd = open(sid_file, 'wb')
|
||||
ft.seek(0)
|
||||
fd.write(ft.read())
|
||||
ft.close()
|
||||
fd.close()
|
||||
# delete temp file
|
||||
os.unlink(sid_file_t)
|
||||
return ['0']
|
||||
except (IOError, EOFError, KeyError, OSError):
|
||||
return ['1']
|
||||
|
||||
# find session id in file
|
||||
@staticmethod
|
||||
def find_sid_in_file(cls, sid):
|
||||
sid_file = cls.sids_file
|
||||
# create, if file not exists
|
||||
with cls.sid_locker:
|
||||
if not os.path.exists(sid_file):
|
||||
temp = open(sid_file, 'w')
|
||||
temp.close()
|
||||
fd = open(sid_file, 'r')
|
||||
while True:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (EOFError, IOError, KeyError):
|
||||
break
|
||||
# if session id found
|
||||
if sid == list_sid[0]:
|
||||
fd.close()
|
||||
return 1
|
||||
fd.close()
|
||||
return 0
|
||||
|
||||
# add session id in file
|
||||
@staticmethod
|
||||
def add_sid_in_file(cls, sid, cert_id, lang):
|
||||
# list Format (session number, cert number, time start session)
|
||||
list_sid = [sid, cert_id, datetime.datetime.now()]
|
||||
# session's file
|
||||
if not os.path.exists(cls.sids):
|
||||
os.mkdir(cls.sids)
|
||||
sids_dir = cls.sids
|
||||
sid_file = sids_dir + "/%d.sid" % sid
|
||||
|
||||
# create session's file
|
||||
with cls.sid_locker:
|
||||
fp = open(sid_file, 'w')
|
||||
sid_list = [sid, 0, 0, lang]
|
||||
pickle.dump(sid_list, fp)
|
||||
fp.close()
|
||||
|
||||
# add session in list sessions
|
||||
fd = open(cls.sids_file, 'a')
|
||||
pickle.dump(list_sid, fd)
|
||||
fd.close()
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def set_sid_lang(cls, sid, lang):
|
||||
sids_dir = cls.sids
|
||||
sid_file = os.path.join(sids_dir, "%d.sid" % sid)
|
||||
with cls.sid_locker:
|
||||
if not os.path.isfile(sid_file):
|
||||
fp = open(sid_file, 'w')
|
||||
fp.close()
|
||||
fd = open(sid_file, 'r')
|
||||
try:
|
||||
list_sid = pickle.load(fd)
|
||||
except (EOFError, KeyError, IOError):
|
||||
list_sid = [sid, 0, 0, lang]
|
||||
fd.close()
|
||||
|
||||
fp = open(sid_file, 'w')
|
||||
list_sid[3] = lang
|
||||
pickle.dump(list_sid, fp)
|
||||
fp.close()
|
||||
|
||||
# issue number of new session (and registered its)
|
||||
@staticmethod
|
||||
def sid_cmp(cls, sid, cert_id, lang):
|
||||
if sid < 0 or sid > cls.max_sid:
|
||||
sid = 0
|
||||
session = 1
|
||||
# if session is new
|
||||
if sid == 0:
|
||||
while True:
|
||||
new_sid = random.randint(1, cls.max_sid)
|
||||
# flag = 1 - exists, 0 - missing in SID_FILE
|
||||
if cls.find_sid_in_file(cls, new_sid) == 0:
|
||||
cls.add_sid_in_file(cls, new_sid, cert_id, lang)
|
||||
sid = new_sid
|
||||
break
|
||||
# if session is old
|
||||
else:
|
||||
# find number in file registered
|
||||
# if not registered
|
||||
if not cls.find_sid_in_file(cls, sid):
|
||||
# add session id in file
|
||||
cls.add_sid_in_file(cls, sid, cert_id, lang)
|
||||
else:
|
||||
cls.set_sid_lang(cls, sid, lang)
|
||||
# set - old session
|
||||
session = 0
|
||||
|
||||
# session id and flag (new or old) session
|
||||
return [sid, session]
|
||||
|
||||
@staticmethod
|
||||
def serv_init_session(cls, sid, lang):
|
||||
day_cert = 600
|
||||
cur_thread = threading.currentThread()
|
||||
certificate = cur_thread.client_cert
|
||||
if certificate is None:
|
||||
return [-3], [0]
|
||||
|
||||
checked_id = find_cert_id(certificate, cls.data_path, cls.certbase)
|
||||
try:
|
||||
if int(checked_id) < 1:
|
||||
return [-4], [0]
|
||||
except ValueError:
|
||||
return [-4], [0]
|
||||
results = []
|
||||
cert_id = checked_id
|
||||
with open(cls.certbase) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
# if in line present certificate id
|
||||
if len(words) > 3:
|
||||
if words[0] == checked_id:
|
||||
results.append(checked_id)
|
||||
date = datetime.datetime.strptime(
|
||||
words[2] + ' ' + words[3], '%Y-%m-%d %H:%M:%S.%f')
|
||||
d = datetime.datetime.now() - date
|
||||
v = day_cert - d.days # How many days left certificate
|
||||
if v < 0:
|
||||
# Method deleted certificate
|
||||
v = -2 # expiry date has passed
|
||||
elif v > 60: # For a long time, is not displayed to
|
||||
# the client
|
||||
v = -1
|
||||
results.append(v)
|
||||
# return results
|
||||
if not results:
|
||||
return [-4], [0]
|
||||
|
||||
return results, cls.sid_cmp(cls, sid, cert_id, lang)
|
||||
|
||||
@staticmethod
|
||||
def serv_sid_info(cls, sid):
|
||||
""" Get information about sid """
|
||||
cert_id = 0
|
||||
results = []
|
||||
sid_file = cls.sids_file
|
||||
with cls.sid_locker:
|
||||
fd = open(sid_file, 'r')
|
||||
while 1:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (IOError, KeyError, EOFError):
|
||||
break
|
||||
# if sid found
|
||||
if sid == list_sid[0]:
|
||||
cert_id = list_sid[1]
|
||||
fd.close()
|
||||
|
||||
# Get information about sid
|
||||
if cert_id == 0:
|
||||
return ["-1"]
|
||||
|
||||
with cls.sid_locker:
|
||||
with open(cls.certbase) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
# if in line present certificate id
|
||||
if words[0] == str(cert_id):
|
||||
# certificate id
|
||||
results.append(words[0])
|
||||
# Date issue certificate
|
||||
results.append(words[2] + ' ' + words[3])
|
||||
# ip
|
||||
results.append(words[4])
|
||||
# mac
|
||||
results.append(words[5])
|
||||
# client type
|
||||
results.append(words[6])
|
||||
if not os.path.exists(cls.sids):
|
||||
os.makedirs(cls.sids)
|
||||
sid_path = cls.sids + "/%d.sid" % sid
|
||||
with open(sid_path) as fs:
|
||||
# read info about session
|
||||
sid_inf = pickle.load(fs)
|
||||
# flag absence client
|
||||
results.append(str(sid_inf[2]))
|
||||
|
||||
return results
|
||||
return ["-2"]
|
@ -1,60 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2011-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 datetime
|
||||
import threading
|
||||
from cert_cmd import find_cert_id
|
||||
# Time life certificate in days
|
||||
DAY_CERT = 600
|
||||
|
||||
|
||||
def serv_post_cert(cls):
|
||||
""" transfer the client certificate """
|
||||
cur_thread = threading.currentThread()
|
||||
certificate = cur_thread.client_cert
|
||||
if certificate is None:
|
||||
return [-3]
|
||||
|
||||
checked_id = find_cert_id(certificate, cls.data_path, cls.certbase)
|
||||
try:
|
||||
if int(checked_id) < 1:
|
||||
return [-2]
|
||||
except ValueError:
|
||||
return [-4]
|
||||
results = []
|
||||
with open(cls.certbase) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
# if in line present certificate id
|
||||
if len(words) > 3:
|
||||
if words[0] == checked_id:
|
||||
results.append(checked_id)
|
||||
date = datetime.datetime.strptime(
|
||||
words[2] + ' ' + words[3], '%Y-%m-%d %H:%M:%S.%f')
|
||||
d = datetime.datetime.now() - date
|
||||
v = DAY_CERT - d.days # How many days left certificate
|
||||
if v < 0:
|
||||
# Method deleted certificate
|
||||
v = -2 # expiry date has passed
|
||||
# For a long time, is not displayed to the client
|
||||
elif v > 60:
|
||||
v = -1
|
||||
results.append(v)
|
||||
return results
|
||||
return [-4]
|
@ -1,412 +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 spyne.server.wsgi import WsgiApplication
|
||||
|
||||
import re
|
||||
import logging
|
||||
import os
|
||||
#cStringIO was moved to io in python3
|
||||
import cStringIO as io
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
import datetime
|
||||
import pickle
|
||||
from loaded_methods import LoadedMethods
|
||||
|
||||
# for OpenSSLAdapter
|
||||
import calculate.contrib
|
||||
from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter
|
||||
|
||||
HTTP_500 = '500 Internal server error'
|
||||
HTTP_200 = '200 OK'
|
||||
HTTP_405 = '405 Method Not Allowed'
|
||||
HTTP_403 = '403 Forbidden'
|
||||
not_log_list = ['post_server_request', 'post_client_request', 'del_sid',
|
||||
'get_server_cert', 'get_client_cert', 'get_entire_frame',
|
||||
'get_crl', 'get_server_host_name', 'get_ca', 'get_table',
|
||||
'post_cert', 'post_sid', 'active_client', 'list_pid',
|
||||
'get_methods', 'get_frame', 'get_progress', 'pid_info']
|
||||
|
||||
|
||||
class ClApplication(WsgiApplication):
|
||||
def __init__(self, app, log=None):
|
||||
super(ClApplication, self).__init__(app)
|
||||
# add object logging
|
||||
self.log = logger
|
||||
|
||||
#verification of compliance certificate and session (sid)
|
||||
def check_cert_sid(self, sid, server):
|
||||
import threading
|
||||
|
||||
curthread = threading.currentThread()
|
||||
cert = curthread.client_cert
|
||||
from cert_cmd import find_cert_id
|
||||
|
||||
cert_id = find_cert_id(cert, server.data_path, server.certbase)
|
||||
cert_id = int(cert_id)
|
||||
if cert_id == 0:
|
||||
return 0
|
||||
|
||||
# session file
|
||||
if not os.path.exists(server.sids):
|
||||
os.system('mkdir %s' % server.sids)
|
||||
|
||||
if not os.path.isfile(server.sids_file):
|
||||
open(server.sids_file, 'w').close()
|
||||
with open(server.sids_file, 'r') as fd:
|
||||
while 1:
|
||||
try:
|
||||
# read all on one record
|
||||
list_sid = pickle.load(fd)
|
||||
except (IOError, EOFError, KeyError):
|
||||
break
|
||||
# find session id in sids file
|
||||
if cert_id == int(list_sid[1]):
|
||||
if int(sid) == int(list_sid[0]):
|
||||
return 1
|
||||
return 0
|
||||
|
||||
# input parameters - certificate and name method
|
||||
def check_rights(self, method_name, req_env, sid):
|
||||
""" check right client certificate for the method """
|
||||
import OpenSSL
|
||||
|
||||
# rmethod = re.compile('[{\w]+[}]')
|
||||
# method_rep = rmethod.findall(method_name)
|
||||
# method_name = method_name.replace(method_rep[0], '')
|
||||
import threading
|
||||
|
||||
curthread = threading.currentThread()
|
||||
|
||||
cert = curthread.client_cert
|
||||
server_cert = curthread.server.ssl_certificate
|
||||
server_key = curthread.server.ssl_private_key
|
||||
certbase = curthread.server.certbase
|
||||
rights = curthread.server.rights
|
||||
group_rights = curthread.server.group_rights
|
||||
data_path = curthread.server.data_path
|
||||
permitted_methods = ['post_server_request', 'post_client_request',
|
||||
'get_server_cert', 'get_client_cert',
|
||||
'get_crl', 'get_server_host_name', 'get_ca']
|
||||
|
||||
if method_name in permitted_methods:
|
||||
return 1
|
||||
if cert is None:
|
||||
if method_name not in permitted_methods:
|
||||
return 0
|
||||
return 1
|
||||
|
||||
if (sid and
|
||||
(method_name in LoadedMethods.rightsMethods or
|
||||
method_name.endswith('_view') and
|
||||
method_name[:-5] in LoadedMethods.rightsMethods)):
|
||||
if not self.check_cert_sid(sid, curthread.server):
|
||||
return 0
|
||||
|
||||
with open(server_cert, 'r') as f:
|
||||
data_server_cert = f.read()
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, data_server_cert)
|
||||
|
||||
with open(server_key, 'r') as f:
|
||||
data_server_key = f.read()
|
||||
Pkey = OpenSSL.crypto.load_privatekey(OpenSSL.SSL.FILETYPE_PEM,
|
||||
data_server_key, 'qqqq')
|
||||
signature = OpenSSL.crypto.sign(Pkey, cert, 'SHA1')
|
||||
try:
|
||||
OpenSSL.crypto.verify(certobj, signature, cert, 'SHA1')
|
||||
except Exception as e:
|
||||
print e
|
||||
return 0
|
||||
if method_name == 'cert_add':
|
||||
return 0
|
||||
certobj_cl = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
try:
|
||||
com = certobj_cl.get_extension(certobj_cl.get_extension_count() - 1)
|
||||
groups = com.get_data().split(':')[1]
|
||||
except IndexError:
|
||||
groups = ""
|
||||
except Exception:
|
||||
return 0
|
||||
groups_list = groups.split(',')
|
||||
# open certificates database
|
||||
if not os.path.exists(certbase):
|
||||
open(certbase, "w").close()
|
||||
from cert_cmd import find_cert_id
|
||||
|
||||
checked_id = find_cert_id(cert, data_path, certbase)
|
||||
cert_id = int(checked_id)
|
||||
count = 0
|
||||
find_flag = False
|
||||
# if certificate found
|
||||
if cert_id > 0:
|
||||
if method_name not in LoadedMethods.rightsMethods:
|
||||
return 1
|
||||
|
||||
# if group = all and not redefined group all
|
||||
if 'all' in groups_list:
|
||||
find_flag = False
|
||||
with open(group_rights, 'r') as fd:
|
||||
t = fd.read()
|
||||
# find all in group_rights file
|
||||
for line in t.splitlines():
|
||||
if not line:
|
||||
continue
|
||||
if line.split()[0] == 'all':
|
||||
find_flag = True
|
||||
break
|
||||
# if not find_flag:
|
||||
# return 1
|
||||
|
||||
for right_param in LoadedMethods.rightsMethods[method_name]:
|
||||
flag = 0
|
||||
try:
|
||||
# check rights
|
||||
if not os.path.exists(rights):
|
||||
open(rights, 'w').close()
|
||||
with open(rights) as fr:
|
||||
t = fr.read()
|
||||
for line in t.splitlines():
|
||||
words = line.split()
|
||||
# first word in line equal name input method
|
||||
if words[0] == right_param:
|
||||
for word in words:
|
||||
try:
|
||||
word = int(word)
|
||||
except ValueError:
|
||||
continue
|
||||
# compare with certificat number
|
||||
if cert_id == word:
|
||||
# if has right
|
||||
count += 1
|
||||
flag = 1
|
||||
break
|
||||
if cert_id == -word:
|
||||
return 0
|
||||
if flag:
|
||||
break
|
||||
|
||||
if flag:
|
||||
break
|
||||
# open file with groups rights
|
||||
if not os.path.exists(group_rights):
|
||||
open(group_rights, 'w').close()
|
||||
with open(group_rights) as fd:
|
||||
t = fd.read()
|
||||
for line in t.splitlines():
|
||||
if not line:
|
||||
continue
|
||||
words = line.split(' ', 1)
|
||||
# first word in line equal name input method
|
||||
if words[0] in groups_list:
|
||||
methods = words[1].split(',')
|
||||
for word in methods:
|
||||
# compare with certificat number
|
||||
if right_param == word.strip():
|
||||
# if has right
|
||||
count += 1
|
||||
flag = 1
|
||||
break
|
||||
if flag:
|
||||
break
|
||||
except Exception:
|
||||
return 0
|
||||
if count == len(LoadedMethods.rightsMethods[method_name]):
|
||||
return 1
|
||||
if not find_flag and 'all' in groups_list:
|
||||
return 1
|
||||
elif method_name in ['post_cert', 'init_session']:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def create_path(self):
|
||||
""" create paths for server files """
|
||||
import threading
|
||||
|
||||
curthread = threading.currentThread()
|
||||
data_path = curthread.server.data_path
|
||||
sids = curthread.server.sids
|
||||
pids = curthread.server.pids
|
||||
cert_path = curthread.server.cert_path
|
||||
if not os.path.exists(sids):
|
||||
if not os.path.exists(data_path):
|
||||
os.makedirs(data_path)
|
||||
os.makedirs(sids)
|
||||
if not os.path.exists(pids):
|
||||
if not os.path.exists(data_path):
|
||||
os.makedirs(data_path)
|
||||
os.makedirs(pids)
|
||||
if not os.path.exists(data_path + '/conf'):
|
||||
if not os.path.exists(data_path):
|
||||
os.makedirs(data_path)
|
||||
os.makedirs(data_path + '/conf')
|
||||
|
||||
if not os.path.exists(data_path + '/conf/right.conf'):
|
||||
open(data_path + '/conf/right.conf', 'w').close()
|
||||
|
||||
if not os.path.exists(data_path + '/conf/group_right.conf'):
|
||||
open(data_path + '/conf/group_right.conf', 'w').close()
|
||||
|
||||
if not os.path.exists(data_path + '/client_certs'):
|
||||
os.makedirs(data_path + '/client_certs')
|
||||
|
||||
if not os.path.exists(data_path + '/server_certs'):
|
||||
os.makedirs(data_path + '/server_certs')
|
||||
|
||||
if not os.path.exists(cert_path):
|
||||
os.makedirs(cert_path)
|
||||
|
||||
|
||||
def get_method_name_from_http(self, http_req_env):
|
||||
retval = None
|
||||
# check HTTP_SOAPACTION
|
||||
retval = http_req_env.get("HTTP_SOAPACTION")
|
||||
|
||||
if retval is not None:
|
||||
if retval.startswith('"') and retval.endswith('"'):
|
||||
retval = retval[1:-1]
|
||||
|
||||
if retval.find('/') >0:
|
||||
retvals = retval.split('/')
|
||||
retval = '{%s}%s' % (retvals[0], retvals[1])
|
||||
|
||||
logger.debug("\033[92m"
|
||||
"Method name from HTTP_SOAPACTION: %r"
|
||||
"\033[0m" % retval)
|
||||
if(not retval):
|
||||
logger.critical("Couldn't get method name from HTTP_SOAPACTION")
|
||||
return retval
|
||||
|
||||
def get_sid_from_soap(self, http_req_env):
|
||||
"""
|
||||
rips sid param from soap request (if there is one)
|
||||
"""
|
||||
if (not "wsgi.input" in http_req_env):
|
||||
return None
|
||||
length = http_req_env.get("CONTENT_LENGTH")
|
||||
input = http_req_env["wsgi.input"]
|
||||
body = input.read(int(length))
|
||||
res = re.search("<ns.:sid>(.*?)<\/ns.:sid>", body)
|
||||
#horrbile hack:
|
||||
#cherrypy provides rfile in req_env which is consumed upon .read() without
|
||||
# workarounds, and both we and spyne need the data on it
|
||||
#so we pass a dummy with the data and read() method on to spyne
|
||||
http_req_env["wsgi.input"] = io.StringIO(body)
|
||||
|
||||
if(res):
|
||||
return int(res.group(1))
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def handle_rpc(self, req_env, start_response):
|
||||
"""
|
||||
Overriding spyne.wsgiApplication method
|
||||
"""
|
||||
import OpenSSL
|
||||
import threading
|
||||
http_resp_headers = {
|
||||
'Content-Type': 'text/xml',
|
||||
'Content-Length': '0',
|
||||
}
|
||||
curthread = threading.currentThread()
|
||||
curthread.REMOTE_ADDR = req_env.get('REMOTE_ADDR')
|
||||
curthread.REMOTE_PORT = req_env.get('REMOTE_PORT')
|
||||
ip = req_env.get('REMOTE_ADDR')
|
||||
self.create_path()
|
||||
sid = self.get_sid_from_soap(req_env)
|
||||
method_name = self.get_method_name_from_http(req_env)
|
||||
if method_name is None:
|
||||
resp = "Could not extract method name from the request!"
|
||||
http_resp_headers['Content-Length'] = str(len(resp))
|
||||
start_response(HTTP_500, http_resp_headers.items())
|
||||
return [resp]
|
||||
|
||||
service = self.app.services[0]
|
||||
import threading
|
||||
|
||||
curthread = threading.currentThread()
|
||||
# check if client certificate exists
|
||||
if not hasattr(curthread, 'client_cert'):
|
||||
curthread.client_cert = None
|
||||
# check rights client certificate for the method
|
||||
check = self.check_rights(method_name, req_env, sid)
|
||||
if not check:
|
||||
if curthread.client_cert:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, curthread.client_cert)
|
||||
finger = certobj.digest('SHA1')
|
||||
if self.log:
|
||||
self.log.debug('%s %s %s forbidden %s'
|
||||
% (datetime.datetime.now().__str__(),
|
||||
finger, ip,
|
||||
method_name[5:]))
|
||||
resp = "Permission denied: " + method_name
|
||||
http_resp_headers['Content-Length'] = str(len(resp))
|
||||
start_response(HTTP_403, http_resp_headers.items())
|
||||
return [resp]
|
||||
|
||||
|
||||
if sid:
|
||||
curthread.lang = service.get_lang(service, sid, method_name)
|
||||
if curthread.client_cert:
|
||||
certobj = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.SSL.FILETYPE_PEM, curthread.client_cert)
|
||||
finger = certobj.digest('SHA1')
|
||||
if (not method_name[5:] in not_log_list and
|
||||
not method_name[5:].endswith('_view')):
|
||||
if self.log:
|
||||
self.log.debug('%s %s %s allowed %s'
|
||||
% (datetime.datetime.now().__str__(),
|
||||
finger, ip,
|
||||
method_name[5:]))
|
||||
|
||||
return super(ClApplication, self).handle_rpc(req_env, start_response)
|
||||
|
||||
class OpenSSLAdapter(pyOpenSSLAdapter):
|
||||
def verify_func(self, connection, x509, errnum, errdepth, ok):
|
||||
# get client certificate
|
||||
import OpenSSL
|
||||
import threading
|
||||
|
||||
curthread = threading.currentThread()
|
||||
if errdepth == 0:
|
||||
curthread.client_cert = OpenSSL.crypto.dump_certificate(
|
||||
OpenSSL.crypto.FILETYPE_PEM, x509)
|
||||
else:
|
||||
curthread.client_cert = None
|
||||
return ok
|
||||
|
||||
def get_context(self):
|
||||
"""Return an SSL.Context from self attributes."""
|
||||
# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
|
||||
import OpenSSL
|
||||
|
||||
c = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD)
|
||||
c.set_options(OpenSSL.SSL.OP_NO_SSLv2 | OpenSSL.SSL.OP_NO_SSLv3)
|
||||
|
||||
# c.set_passwd_cb(lambda *unused: 'qqqq')
|
||||
c.use_privatekey_file(self.private_key)
|
||||
c.set_verify(OpenSSL.SSL.VERIFY_PEER, self.verify_func)
|
||||
|
||||
if self.certificate_chain:
|
||||
c.load_verify_locations(self.certificate_chain)
|
||||
|
||||
c.use_certificate_file(self.certificate)
|
||||
return c
|
@ -1,105 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2021 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.contrib
|
||||
from spyne.service import Service, ServiceMeta
|
||||
from spyne import String, Integer, Array, rpc
|
||||
from func import WsdlMeta
|
||||
from api_types import ReturnedMessage, ViewInfo, ViewParams
|
||||
from spyne.protocol._outbase import OutProtocolBase
|
||||
from api_types import LazyString
|
||||
|
||||
#monkey patch:
|
||||
def to_unicode(self, cls, value, *args, **kwargs):
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
#### PATCH ####################
|
||||
if isinstance(value, LazyString):
|
||||
value = str(value)
|
||||
###############################
|
||||
|
||||
handler = self._to_unicode_handlers[cls]
|
||||
retval = handler(cls, value, *args, **kwargs)
|
||||
|
||||
return retval
|
||||
|
||||
OutProtocolBase.to_unicode = to_unicode
|
||||
|
||||
|
||||
class ServiceMetaAdapter(ServiceMeta):
|
||||
#ref to the created class
|
||||
global_class_ref = None
|
||||
|
||||
#this is used for a localCall
|
||||
class CoreInnerWsdl(ServiceMeta, WsdlMeta):
|
||||
pass
|
||||
|
||||
# Nevermind, following is deprecated:
|
||||
|
||||
#the idea is to decorate methods that need rpc with this
|
||||
#and then find them in make_service and wrap them in funcs without self ref
|
||||
# def rpc_a():
|
||||
# def func(f):
|
||||
# f.wrap_rpc = True
|
||||
# return f
|
||||
# return func
|
||||
|
||||
#wraps a func in rpc decorator
|
||||
#this is needed because Spyne service does not allow self ref in function calls
|
||||
def make_rpc_func_view(func_to_call):
|
||||
def _function(ctx, sid, params):
|
||||
return func_to_call(ServiceMetaAdapter.global_class_ref, sid, params)
|
||||
_function.__name__ = func_to_call.__name__
|
||||
return rpc(Integer, ViewParams, _returns=ViewInfo)(_function)
|
||||
|
||||
def make_rpc_func_vars(func_to_call):
|
||||
def _function(ctx, dv=None, params=None):
|
||||
return func_to_call(ServiceMetaAdapter.global_class_ref, dv, params)
|
||||
_function.__name__ = func_to_call.__name__
|
||||
return staticmethod(_function)
|
||||
|
||||
def make_rpc_func_caller(func_to_call):
|
||||
def _function(ctx, sid, params):
|
||||
return func_to_call(ServiceMetaAdapter.global_class_ref, sid, params)
|
||||
_function.__name__ = func_to_call.__name__
|
||||
info_class = func_to_call.info_class
|
||||
return rpc(Integer, info_class, _returns=Array(ReturnedMessage))(_function)
|
||||
|
||||
def make_service(basic_class, wsdl_core_class_list, outer_wsdl_class_list, service_name):
|
||||
#for Core, rpc methods only present in basic_class, we need others just to have a mono class
|
||||
#for outer wsdl classes, we have to add stateless wrap methods on our own
|
||||
|
||||
saved_pub_methods = basic_class.public_methods
|
||||
|
||||
functions_to_add = {}
|
||||
for klass in outer_wsdl_class_list:
|
||||
for meth in klass.__dict__:
|
||||
if not meth.startswith("__") and not meth == "methods":
|
||||
if meth.endswith("_view"):
|
||||
functions_to_add[meth] = make_rpc_func_view(getattr(klass, meth))
|
||||
elif meth.endswith("_vars"):
|
||||
functions_to_add[meth] = make_rpc_func_vars(getattr(klass, meth))
|
||||
else:
|
||||
functions_to_add[meth] = make_rpc_func_caller(getattr(klass, meth))
|
||||
|
||||
functions_to_add.update({"__metaclass__" : ServiceMetaAdapter})
|
||||
ClService = ServiceMetaAdapter(service_name, tuple([basic_class] + wsdl_core_class_list), functions_to_add)
|
||||
ClService.public_methods.update(saved_pub_methods)
|
||||
#TODO replace with a single ref
|
||||
ServiceMetaAdapter.global_class_ref = ClService
|
||||
basic_class.set_comb_class_ref(ClService)
|
||||
return ClService
|
@ -1,26 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2011-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 action
|
||||
import core
|
||||
import request
|
||||
import certificate
|
||||
import groups
|
||||
import setup_package
|
||||
import variable
|
||||
import backup
|
||||
|
||||
section = "core"
|
@ -1,167 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 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
|
||||
from os import path
|
||||
from calculate.lib.datavars import (Variable, ReadonlyVariable)
|
||||
from calculate.lib.utils.files import get_free_dirname, listDirectory
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
import datetime
|
||||
from action import Actions
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
|
||||
|
||||
class VariableClBackupPath(Variable):
|
||||
"""
|
||||
Путь до каталога, где будет подготавливаться backup
|
||||
"""
|
||||
preferred_dn = '/var/calculate/tmp/backup_prepare'
|
||||
|
||||
def get(self):
|
||||
return get_free_dirname(self.preferred_dn)
|
||||
|
||||
|
||||
class VariableClBackupContentsName(Variable):
|
||||
"""
|
||||
Названия файла CONTENTS в архиве
|
||||
"""
|
||||
value_format = "CONTENTS"
|
||||
|
||||
|
||||
class VariableClBackupRootName(Variable):
|
||||
"""
|
||||
Названия каталога, куда сохраняются конфигурационные файлы
|
||||
"""
|
||||
value_format = "root"
|
||||
|
||||
|
||||
class VariableClBackupFileContents(ReadonlyVariable):
|
||||
"""
|
||||
CONTENTS в архиве настроек
|
||||
"""
|
||||
value_format = "{cl_backup_path}/{cl_backup_contents_name}"
|
||||
|
||||
|
||||
class VariableClBackupIniEnv(Variable):
|
||||
"""
|
||||
Названия файла CONTENTS в архиве [install] init =
|
||||
"""
|
||||
value_format = "{cl_backup_path}/ini.env"
|
||||
|
||||
|
||||
class VariableClBackupBasePath(Variable):
|
||||
"""
|
||||
Директория в которой будет создан архив
|
||||
"""
|
||||
value = "/var/calculate/backup"
|
||||
|
||||
|
||||
class VariableClBackupTime(ReadonlyVariable):
|
||||
"""
|
||||
Переменная содержащая информацию: время создания backup
|
||||
"""
|
||||
|
||||
def init(self):
|
||||
self.label = _("Backup created")
|
||||
|
||||
def get(self):
|
||||
backup_fn = self.Get('cl_backup_file')
|
||||
if backup_fn and path.exists(backup_fn):
|
||||
try:
|
||||
dt = datetime.datetime.strptime(
|
||||
path.basename(backup_fn).rpartition("-")[2],
|
||||
"%Y%m%d%H%M%S.tar.bz2")
|
||||
return dt.strftime("%s")
|
||||
except ValueError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
def humanReadable(self):
|
||||
ts = self.Get()
|
||||
if ts:
|
||||
ret = []
|
||||
backup_tm = datetime.datetime.fromtimestamp(int(ts))
|
||||
now_tm = datetime.datetime.now()
|
||||
backup_diff = now_tm - backup_tm
|
||||
if backup_diff.days:
|
||||
ret.append(_("%d days") % backup_diff.days)
|
||||
minute = 60
|
||||
hour = 60 * minute
|
||||
times = backup_diff.seconds
|
||||
if times >= hour:
|
||||
ret.append(_("%d hours") % (times / hour))
|
||||
times %= hour
|
||||
if times >= minute:
|
||||
ret.append(_("%d minutes") % (times / minute))
|
||||
times %= minute
|
||||
if times:
|
||||
ret.append(_("%d seconds") % times)
|
||||
return _("%s ago") % (" ".join(ret))
|
||||
|
||||
return _("Unknown")
|
||||
|
||||
|
||||
class VariableClBackupFile(Variable):
|
||||
"""
|
||||
Путь до создаваемое архива резервной копии
|
||||
"""
|
||||
|
||||
def init(self):
|
||||
self.label = _("Backup file")
|
||||
|
||||
def get_backup(self):
|
||||
"""
|
||||
Получить путь для подготовки архива настроек
|
||||
:return:
|
||||
"""
|
||||
dn = self.Get('cl_backup_base_path')
|
||||
dt = datetime.datetime.now().strftime(
|
||||
"calculate-backup-%Y%m%d%H%M%S.tar.bz2")
|
||||
return path.join(dn, dt)
|
||||
|
||||
def get_restore(self):
|
||||
"""
|
||||
Получить путь для распаковки архива настроек
|
||||
:return:
|
||||
"""
|
||||
dn = self.Get('cl_backup_base_path')
|
||||
for fn in sorted((x for x in listDirectory(dn, fullPath=True)
|
||||
if x.endswith(".tar.bz2")),
|
||||
reverse=True):
|
||||
# получить самый свежий файл
|
||||
return fn
|
||||
return ""
|
||||
|
||||
def get(self):
|
||||
action = self.Get('cl_action')
|
||||
if action == Actions.Backup:
|
||||
return self.get_backup()
|
||||
elif action == Actions.BackupRestore:
|
||||
return self.get_restore()
|
||||
|
||||
class VariableClBackupVerboseSet(Variable):
|
||||
"""
|
||||
Verbose output for backup
|
||||
"""
|
||||
type = "bool"
|
||||
opt = ["-v", "--verbose"]
|
||||
value = "off"
|
||||
|
||||
def init(self):
|
||||
self.help = _("verbose output")
|
||||
self.label = _("Verbose output")
|
@ -1,794 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2011-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
|
||||
|
||||
from calculate.lib.datavars import VariableError, DataVarsError
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
|
||||
|
||||
_ = lambda x: x
|
||||
setLocalTranslate('cl_core3', sys.modules[__name__])
|
||||
__ = getLazyLocalTranslate(_)
|
||||
|
||||
import setup_package
|
||||
import server.certificate as certificate
|
||||
import server.groups as groups
|
||||
import server.request as request
|
||||
import set_vars
|
||||
from backup import Backup, BackupError
|
||||
from calculate.core.utils.cl_backup import ClBackupAction
|
||||
from calculate.core.utils.cl_backup_restore import ClBackupRestoreAction
|
||||
from calculate.core.server.func import WsdlBase
|
||||
from calculate.core.utils.cl_core_setup import ClCoreSetupAction
|
||||
from calculate.core.utils.cl_core_patch import ClCorePatchAction
|
||||
from calculate.core.utils.cl_config import ClConfigAction
|
||||
from calculate.core.utils.cl_core_dispatch import ClCoreDispatchAction
|
||||
from calculate.core.utils.cl_core_view_cert import ClCoreViewCert
|
||||
from calculate.core.utils.cl_core_group import (
|
||||
ClCoreGroupShow, ClCoreGroupMod, ClCoreGroupAdd, ClCoreGroupDel)
|
||||
from calculate.core.utils.cl_core_request import (
|
||||
ClCoreRequestShow, ClCoreRequestConfirm, ClCoreRequestDel)
|
||||
from calculate.core.utils.cl_core_variables import (ClCoreVariables,
|
||||
ClCoreVariablesShow)
|
||||
from calculate.core.utils.cl_core_custom import ClCoreCustomAction
|
||||
from calculate.core.utils.cl_core_restart import ClCoreRestartAction
|
||||
from calculate.core.variables.action import Actions
|
||||
|
||||
|
||||
class Wsdl(WsdlBase):
|
||||
methods = [
|
||||
#
|
||||
# Настройка пакета во время установки (cl-core-setup)
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_setup",
|
||||
# категория метода
|
||||
'category': __('Configuration'),
|
||||
# заголовок метода
|
||||
'title': __("Configure a Package"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-setup,'
|
||||
'preferences-desktop-default-applications',
|
||||
# метод присутствует в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-setup',
|
||||
# права для запуска метода
|
||||
'rights': ['setup_package'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClCoreSetupAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError,
|
||||
setup_package.SetupPackageError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'merge', 'cl_verbose_set': "on"},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Configure a package"),
|
||||
normal=('cl_core_pkg_name',),
|
||||
expert=('cl_core_pkg_category',
|
||||
'cl_core_pkg_version_opt',
|
||||
'cl_core_pkg_slot_opt',
|
||||
'cl_core_pkg_path',
|
||||
'cl_core_arch_machine',
|
||||
'cl_templates_locate',
|
||||
'cl_core_pkg_system_set',
|
||||
'cl_core_pkg_desktop_set',
|
||||
'cl_core_pkg_root_set',
|
||||
'cl_verbose_set',
|
||||
'cl_dispatch_conf'),
|
||||
next_label=_("Run"))]},
|
||||
#
|
||||
# Патч исходников пакета (cl-core-patch)
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_patch",
|
||||
# категория метода
|
||||
'category': __('Configuration'),
|
||||
# заголовок метода
|
||||
'title': __("Patch"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метода нет в графической консоли
|
||||
'gui': False,
|
||||
# консольная команда
|
||||
'command': 'cl-core-patch',
|
||||
# права для запуска метода
|
||||
'rights': ['configure'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClCorePatchAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError,
|
||||
setup_package.SetupPackageError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'patch',
|
||||
'cl_protect_use_set!': 'off'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Configure a package"),
|
||||
normal=('cl_core_pkg_name',),
|
||||
expert=('cl_core_pkg_category',
|
||||
'cl_core_pkg_version',
|
||||
'cl_core_pkg_slot',
|
||||
'cl_core_pkg_path',
|
||||
'cl_core_arch_machine',
|
||||
'cl_templates_locate',
|
||||
'cl_verbose_set'),
|
||||
next_label=_("Run"))]},
|
||||
#
|
||||
# Обновление конфигурационных файлов (cl-dispatch-conf)
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_dispatch",
|
||||
# категория метода
|
||||
'category': __('Update '),
|
||||
# заголовок метода
|
||||
'title': __("Update Settings"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-dispatch,edit-find-replace,computer',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-dispatch-conf',
|
||||
# права для запуска метода
|
||||
'rights': ['configure'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClCoreDispatchAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError,
|
||||
setup_package.SetupPackageError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'dispatch'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': []},
|
||||
#
|
||||
# Отобразить сертификаты
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_view_cert",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Show Certificates"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-view-cert,certificate-server,'
|
||||
'application-certificate',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-view-cert',
|
||||
# права для запуска метода
|
||||
'rights': ['certificates'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Certificate': certificate.Certificate},
|
||||
# описание действия
|
||||
'action': ClCoreViewCert,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {
|
||||
'cl_page_max!': lambda dv: len(dv.Get('cl_list_cert_id'))},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Certificates"),
|
||||
normal=('cl_page_count', 'cl_page_offset'),
|
||||
next_label=_("Next"))]},
|
||||
#
|
||||
# Отобразить детали сертификата
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_detail_view_cert",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Certificate Details"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# права для запуска метода
|
||||
'rights': ['certificates'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {},
|
||||
# описание действия
|
||||
'action': None,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Certificate details"),
|
||||
normal=('cl_cert_id', 'cl_cert_groups',
|
||||
'cl_cert_perms'),
|
||||
custom_buttons=[('but0', _("Back"),
|
||||
"core_view_cert",
|
||||
"button")])]},
|
||||
#
|
||||
# Группы
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_group_show",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Show Groups"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-group-show,user-group-properties,'
|
||||
'view-certificate-import,application-certificate',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-group-show',
|
||||
# права для запуска метода
|
||||
'rights': ['core_group'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Groups': groups.Groups},
|
||||
# описание действия
|
||||
'action': ClCoreGroupShow,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {
|
||||
'cl_page_max!': lambda dv: len(dv.Choice('cl_core_group'))},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Groups"),
|
||||
normal=('cl_page_count', 'cl_page_offset'),
|
||||
next_label=_("Next"))]},
|
||||
#
|
||||
# Отобразить детали группы
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_detail_group",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Group Details"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# права для запуска метода
|
||||
'rights': ['core_group'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {},
|
||||
# описание действия
|
||||
'action': None,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Group details"),
|
||||
normal=(
|
||||
'cl_core_group',
|
||||
'cl_core_group_rights'),
|
||||
custom_buttons=[('but0', _("Back"),
|
||||
"core_group_show",
|
||||
"button"),
|
||||
('but1', _("Change"),
|
||||
"core_group_mod",
|
||||
"button"),
|
||||
('but2', _("Delete"),
|
||||
"core_group_del",
|
||||
"button")])]},
|
||||
#
|
||||
# Изменить группу
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_group_mod",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Modify Group"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-groupmod',
|
||||
# права для запуска метода
|
||||
'rights': ['core_group'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Groups': groups.Groups},
|
||||
# описание действия
|
||||
'action': ClCoreGroupMod,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'modify'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Modify group"),
|
||||
normal=(
|
||||
'cl_core_group',
|
||||
'cl_core_group_rights'),
|
||||
next_label=_("Done"),
|
||||
custom_buttons=[('but2', _("Confirm"),
|
||||
'core_change_group',
|
||||
"button")])]},
|
||||
#
|
||||
# Добавить группу
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_group_add",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Add a Group"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-groupadd',
|
||||
# права для запуска метода
|
||||
'rights': ['core_group'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Groups': groups.Groups},
|
||||
# описание действия
|
||||
'action': ClCoreGroupAdd,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'add'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Add a group"),
|
||||
normal=(
|
||||
'cl_core_group',
|
||||
'cl_core_group_rights'),
|
||||
next_label=_("Add"))]},
|
||||
#
|
||||
# Удалить группу
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_group_del",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Delete the Group"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-groupdel',
|
||||
# права для запуска метода
|
||||
'rights': ['core_group'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Groups': groups.Groups},
|
||||
# описание действия
|
||||
'action': ClCoreGroupDel,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'delete'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Delete the group"),
|
||||
normal=('cl_core_group',),
|
||||
next_label=_("Delete"))]},
|
||||
#
|
||||
# Запрос на сертификат
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_request_show",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Show Requests"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-request-show,view-certificate-import,'
|
||||
'application-certificate',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-request-show',
|
||||
# права для запуска метода
|
||||
'rights': ['request'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Request': request.Request},
|
||||
# описание действия
|
||||
'action': ClCoreRequestShow,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {
|
||||
'cl_page_max!': lambda dv: len(dv.Get('cl_list_req_id'))},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Show requests"),
|
||||
normal=('cl_page_count', 'cl_page_offset'),
|
||||
next_label=_("Next"))]},
|
||||
#
|
||||
# Отобразить детали запроса
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_detail_request",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Request Details"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# права для запуска метода
|
||||
'rights': ['request'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {},
|
||||
# описание действия
|
||||
'action': None,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Group details"),
|
||||
normal=('cl_req_id', 'cl_req_user_name',
|
||||
'cl_req_ip',
|
||||
'cl_req_mac', 'cl_req_date',
|
||||
'cl_req_location',
|
||||
'cl_req_group'),
|
||||
custom_buttons=[('but0', _("Back"),
|
||||
"core_request_show",
|
||||
"button"),
|
||||
('but1', _("Confirm"),
|
||||
"core_request_confirm",
|
||||
"button"),
|
||||
('but2', _("Delete"),
|
||||
"core_request_del",
|
||||
"button")])]},
|
||||
#
|
||||
# Удалить запрос
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_request_del",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Delete the Request"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-request-del',
|
||||
# права для запуска метода
|
||||
'rights': ['request'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Request': request.Request},
|
||||
# описание действия
|
||||
'action': ClCoreRequestDel,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'delete'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Delete the request"),
|
||||
normal=('cl_req_id',),
|
||||
next_label=_("Delete"))]},
|
||||
#
|
||||
# Подтвердить запрос
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_request_confirm",
|
||||
# категория метода
|
||||
# 'category':__('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Confirm the Request"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-request-confirm',
|
||||
# права для запуска метода
|
||||
'rights': ['request'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Request': request.Request},
|
||||
# описание действия
|
||||
'action': ClCoreRequestConfirm,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'confirm'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Delete the request"),
|
||||
normal=('cl_req_id', 'cl_req_group'),
|
||||
next_label=_("Delete"))]},
|
||||
#
|
||||
# установить переменные
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_variables",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Setup Variables"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-variables,applications-versioncontrol,'
|
||||
'text-x-preview,text-x-makefile',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-variables',
|
||||
# права для запуска метода
|
||||
'rights': ['setup_variables'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Variables': set_vars.Variables},
|
||||
# описание действия
|
||||
'action': ClCoreVariables,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Setup variables"),
|
||||
normal=('cl_variable_data',),
|
||||
next_label=_("Save"))]},
|
||||
#
|
||||
# отобразить переменные
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_variables_show",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("View Variables"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метод в графической консоли
|
||||
'gui': False,
|
||||
# консольная команда
|
||||
'command': 'cl-core-variables-show',
|
||||
# права для запуска метода
|
||||
'rights': ['configure'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Variables': set_vars.Variables},
|
||||
# описание действия
|
||||
'action': ClCoreVariablesShow,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Setup variables"),
|
||||
normal=(
|
||||
'cl_variable_filter',
|
||||
'cl_variable_show'),
|
||||
next_label=_("Show"))]},
|
||||
#
|
||||
# Выполнить настройку пакета (cl-config)
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_config",
|
||||
# категория метода
|
||||
'category': __('Configuration'),
|
||||
# заголовок метода
|
||||
'title': __("Config"),
|
||||
# иконка для графической консоли
|
||||
'image': None,
|
||||
# метода нет в графической консоли
|
||||
'gui': False,
|
||||
# консольная команда
|
||||
'command': 'cl-config',
|
||||
# права для запуска метода
|
||||
'rights': ['configure'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClConfigAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError,
|
||||
setup_package.SetupPackageError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'config', 'cl_verbose_set': "on"},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Configure a package"),
|
||||
normal=('cl_core_pkg_name',),
|
||||
expert=('cl_core_pkg_category',
|
||||
'cl_core_pkg_version_opt',
|
||||
'cl_core_pkg_slot_opt',
|
||||
'cl_templates_locate',
|
||||
'cl_verbose_set'),
|
||||
next_label=_("Run"))]},
|
||||
#
|
||||
# отобразить переменные
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_custom",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Custom Action"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-custom,gnome-desktop-config,desktop-config',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-custom',
|
||||
# права для запуска метода
|
||||
'rights': ['custom_configure'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClCoreCustomAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_verbose_set': "on", 'cl_human_edit_set': "on"},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("Custom action"),
|
||||
normal=(
|
||||
'ac_custom_name', 'cl_human_edit_set',
|
||||
'cl_verbose_set'),
|
||||
expert=(
|
||||
'ur_core_login', 'cl_core_arch_machine',
|
||||
'cl_templates_locate',
|
||||
'cl_dispatch_conf'),
|
||||
next_label=_("Run"))]},
|
||||
#
|
||||
# перезапустить сервис calculate core
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "core_restart",
|
||||
# категория метода
|
||||
'category': __('Utilities'),
|
||||
# заголовок метода
|
||||
'title': __("Restart calculate-core"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-core-restart,view-refresh',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-core-restart',
|
||||
# права для запуска метода
|
||||
'rights': ['core_restart'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'UpdateConfigs': setup_package.UpdateConfigs},
|
||||
# описание действия
|
||||
'action': ClCoreRestartAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': 'restart'},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': []},
|
||||
#
|
||||
# создание резервной копии настроек
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "backup",
|
||||
# категория метода
|
||||
'category':__('Backup'),
|
||||
# заголовок метода
|
||||
'title': __("Backup"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-backup',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-backup',
|
||||
# права для запуска метода
|
||||
'rights': ['backup'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Backup': Backup},
|
||||
# описание действия
|
||||
'action': ClBackupAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (BackupError, VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': Actions.Backup},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("System backup"),
|
||||
normal=('cl_backup_verbose_set',),
|
||||
next_label=_("Run"))]},
|
||||
#
|
||||
# восстановление настроек из резервной копии
|
||||
#
|
||||
{
|
||||
# идентификатор метода
|
||||
'method_name': "backup_restore",
|
||||
# категория метода
|
||||
'category':__('Backup'),
|
||||
# заголовок метода
|
||||
'title': __("Restore"),
|
||||
# иконка для графической консоли
|
||||
'image': 'calculate-backup-restore',
|
||||
# метод в графической консоли
|
||||
'gui': True,
|
||||
# консольная команда
|
||||
'command': 'cl-backup-restore',
|
||||
# права для запуска метода
|
||||
'rights': ['backup'],
|
||||
# объект содержащий модули для действия
|
||||
'logic': {'Backup': Backup},
|
||||
# описание действия
|
||||
'action': ClBackupRestoreAction,
|
||||
# объект переменных
|
||||
'datavars': "core",
|
||||
'native_error': (BackupError, VariableError, DataVarsError),
|
||||
# значения по умолчанию для переменных этого метода
|
||||
'setvars': {'cl_action!': Actions.BackupRestore,
|
||||
'core.cl_backup_action': Actions.Restore},
|
||||
# описание груп (список лямбда функций)
|
||||
'groups': [
|
||||
lambda group: group(_("System restore"),
|
||||
normal=('cl_backup_verbose_set',),
|
||||
brief=('cl_backup_file', 'cl_backup_time'),
|
||||
next_label=_("Run"))],
|
||||
'brief': {'next': __("Run"),
|
||||
'name': __("System restore")}},
|
||||
]
|
Loading…
Reference in new issue