Create git repository, add files

master3.3
Спиридонов Денис 13 years ago
commit 4358820e9e

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

@ -0,0 +1,323 @@
#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys, time
#import time
from sid_func import client_sid
from function import get_sid, get_ip_mac_type
import re, OpenSSL
from create_cert import generateRSAKey, makePKey, makeRequest,\
passphrase_callback
import hashlib
from client_class import HTTPSClientCertTransport
from cert_verify import VerifyError
import urllib2
from calculate.core.datavars import DataVarsCore
VERSION = 0.11
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 Server Database!")
#name = raw_input (_(" Delete certificate and Create new? [y]/n: "))
#if name != "n":
#delete_old_cert(client)
#sys.exit()
print _('Add certificate to server Database...')
ip, mac, client_type = get_ip_mac_type()
print ip, mac, client_type
cert_id = client.service.cert_add(mac, client_type)
print _("Your certificate ID = %s") %cert_id
sys.exit(1)
client_sid(sid, client, cert_id = results[0][0])
if results[0][0] == -3:
print _("Certificate not send!")
else:
print _(" Your certifitate id = %d") %(results[0][0])
try:
if results[0][1] == -2:
print _("expiry date certificate has passed")
elif results[0][1] > 0:
print _("shelf life expires after %d days") \
%(results[0][1])
except:
pass
#Creation of secret key of the client
def new_key_req(key, cert_path, server_host_name, auto = False):
from create_cert import generateRSAKey, makePKey, makeRequest,\
passphrase_callback
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 = 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 have sent a request to sign the certificate.")
print _("request id = %s") %open(cert_path + 'req_id', 'r').read()
ans = raw_input (_("Send new request? y/[n]: "))
if not ans.lower() in ['y','yes']:
return 0
port = raw_input (_("Enter port: "))
try:
port = int(port)
except:
print _('Port must be int')
return 1
url = "https://%s:%d/?wsdl" %(by_host, port)
print '"%s\n'% url, _("connect...")
from suds.client import Client
#try:
client = Client(url, \
transport = HTTPSClientCertTransport(None, None, cert_path))
#except (KeyboardInterrupt, urllib2.URLError), e:
#print _("\nClose. Connecting 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 _('secret key and request exists')
ask = raw_input(_("Create new secret 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 = open(csr_file).read()
res = client.service.post_client_request(request = data, ip = ip,\
mac = mac, client_type = client_type)
if int(res) < 0:
print _("This server can not sign certificate!")
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 was not sent or deleted file %s") \
%(cert_path + 'req_id')
return 1
fc = open(cert_path + 'req_id', 'r')
req_id = fc.read()
fc.close()
print '\n', _("URL has form"), "https://%s:[port]/?wsdl" \
%args.from_host
port = raw_input (_("Enter port: "))
try:
port = int(port)
except:
print _('Port must be int')
return 1
url = "https://%s:%d/?wsdl" %(args.from_host, port)
print '%s\n' %url, _("connect...")
from suds.client import Client
try:
client = Client(url, \
transport = HTTPSClientCertTransport(None, None, cert_path))
except KeyboardInterrupt:
print _("Close. Connecting Error.")
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 = open(cert_path + server_host_name + '.csr').read()
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 _('Request to sign is rejected!')
return 1
elif cert == '2':
print _("Request for the signing has not yet reviewed.")
print _("Your request id = %s") %req_id
return 1
elif cert == '3':
print _("Request on signature does not match sent earlier.")
return 1
elif cert == '4':
print _("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 save. 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 open(system_ca_db, 'r').read():
return 0
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_md5 = cl_client_cert_dir + "/ca/cert_list"
md5 = hashlib.md5()
md5.update(ca_root)
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, 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 _('Not found field "CN" in certificate!')
return 1
fd = open(cl_client_cert_dir + '/ca/' + filename, 'w')
fd.write(ca_root)
fd.close()
user_root_cert = clVars.Get('cl_user_root_cert')
user_root_cert = user_root_cert.replace("~",homePath)
fa = open(user_root_cert, 'a')
fa.write(ca_root)
fa.close()
print _("filename = "), filename
print _("CERTIFICATE ADD")
else:
print _("file with ca certificates 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 key --gen-cert-by "
"HOST for generate new certificate or key --get-cert-from "
"HOST for get new certificate from 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 in server!")
return -1
if s[0][0] == "-2":
print _("Error input certificate ID!")
return -2
if s[0][0] == "Permission denied":
print _("Permission denied %s") % s[0][1]
return -3
print _("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:
print _("Error certificate id")
return 1
try:
sid = get_sid(client.SID_FILE)
if cert_id > 0:
cert_right_inf(client, sid, cert_id)
else:
print _("Enter correctly cert id!")
except Exception, e:
if e[0][0] == 403:
print _('Permission denied')
else:
print e
#print _("Error get data")
return 1
return 0

@ -0,0 +1,292 @@
#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os, re, glob
import OpenSSL
from calculate.core.datavars import DataVarsCore
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):
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:
if not flag:
print _("field CN and L in CA certificate are incorrect!")
return 0
crl_file = crl_path + host
else:
if not flag:
print _( "field CN and L in CA certificate are incorrect!")
return 0
if not os.path.exists(crl_file):
if not flag:
print _("This certificate can not 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 is 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 = open(user_root_cert, 'r').read()
else: user_ca_certs = ''
if os.path.exists(glob_root_cert):
glob_ca_certs = open(glob_root_cert, 'r').read()
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
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()
for subj in Subject:
if subj[0] == 'L':
url = "https://" + subj[1] +"/?wsdl"
if subj[0] == 'CN':
CN = subj[1]
if 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()
except VerifyError, e:
print e.value
#rm_ca_from_trusted(ca)
sys.exit()
except:
pass
if 'new_crl' in locals():
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')
#if os.path.exists(CRL_file):
#os.unlink(CRL_file)
continue
if os.path.exists(CRL_file):
if open(CRL_file, 'r').read() == new_crl:
continue
fd = open(CRL_file, 'w')
fd.write(new_crl)
fd.close()
print _("CRL add")
find_ca_in_crl (CRL_path, all_ca_certs_list)
def find_ca_in_crl (CRL_path, all_ca_certs_list):
CRL_name_list = glob.glob(CRL_path + '*')
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]
serverSerial = 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:
continue
revoked_objects = crl_object.get_revoked()
for rvk in revoked_objects:
if serverSerial == 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_list = os.path.join(system_ca_dir, 'cert_list')
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
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 == open(filename, 'r').read():
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 = open(user_ca_db, 'r').read()
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 delete from user trusted certificate")
fd = open(user_ca_db, 'w')
for cert in new_user_ca_certs:
fd.write(cert)
fd.close()
if not os.path.exists(system_ca_db):
open(system_ca_db, 'w')
system_ca_certs = open(system_ca_db, 'r').read()
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 delete from system trusted certificate")
fd = open(system_ca_db, 'w')
for cert in new_system_ca_certs:
fd.write(cert)
fd.close()
return 0

@ -0,0 +1,378 @@
#!/usr/bin/python
#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from suds import WebFault
from suds.transport import TransportError
from calculate.core.client.client_class import Client_suds
import traceback as tb
import time, logging
import os, sys
import re, threading
from function import create_obj, get_sid, analysis, get_entire_frame, clear
from pid_information import client_list_methods, client_list_pid
from cert_func import client_post_auth, client_post_request, client_get_cert, \
client_post_cert
from cert_verify import get_CRL, VerifyError
from sid_func import client_del_sid
from calculate.lib.datavars import DataVars
from calculate.core.datavars import DataVarsCore
from calculate.core.client.client_class import HTTPSClientCertTransport
t = time
def client_login (client):
login = raw_input ("Login: ")
password = raw_input ("password: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(login):
print _("input error")
return 2
print client.service.cl_login(login = login, password = password)
except (Exception) , e:
sys.stdout.flush()
for i in e.message:
sys.stdout.write(str(i) + ' ')
def client_useradd (client):
user_name = raw_input ("User name: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(user_name):
print _("input error")
return 2
print client.service.cl_unix_useradd(param = user_name)
except:
print _("create error")
def client_userdel (client):
user_name = raw_input ("User name: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(user_name):
print _("input error")
return 2
print client.service.cl_unix_userdel(param = user_name)
except:
print _("deleted error")
def client_shut (client):
try:
temp = client.service.server_shutdown()
if ( temp == 1):
print _("Server shutting down...")
except:
print _("Connection error! ")
return 1
def client_signal(client):
Vars = DataVarsCore()
Vars.importCore()
Vars.flIniFile()
try:
client_active = Vars.Get('cl_core_client_active_period')
except:
client_active = 15
while True:
if os.path.exists(client.SID_FILE) :
fi = open(client.SID_FILE, 'r')
temp = fi.read()
fi.close()
sid = int(temp)
else:
sid = 0
try:
reply = client.service.active_client(sid)
except:
print _('no connection to server!')
sys.exit()
time.sleep(float(client_active))
#url = 'http://localhost:8888/TestService/?wsdl'
def test(client, com=None):
if not com:
method_name = 'test'
else:
method_name = com
view = client.service[0][method_name + '_view']()
#print '==>', view
cr = create_obj(client, method_name)
#print 'ddd',cr
#print type (cr)
list_param = dir (cr)
param_list = []
for param in list_param:
if not param.startswith('_'):
param_list.append(param)
for Group in view.groups.GroupField:
print "GroupField name : ", Group.name
for field in Group.fields.Field:
if field.element == 'input':
if field.type == 'str':
cr[field.name] = raw_input(field.label)
if field.type == 'int':
while True:
try:
var = raw_input(field.label)
cr[field.name] = int (var)
break
except (TypeError, ValueError):
print 'Это не целое число'
elif field.element == 'bool':
while 1:
bool_var = raw_input(field.label+' (y/n): ')
if bool_var.lower() in ['y','yes']:
cr[field.name] = True
break
if bool_var.lower() in ['n','no']:
cr[field.name] = False
break
print _('Enter "Yes" or "No"!')
elif field.element == 'check':
choice = field.choice[0]
while 1:
print _('Select one: ')
for i in range(1,len(choice)+1):
print choice[i-1], ' - %d' %i
try:
bool_var = int (raw_input(field.label))
if bool_var > 0:
cr[field.name] = choice[bool_var - 1]
print 'your choice %s' %cr[field.name]
break
except:
pass
#field.choice
#print field.help
sid = get_sid(client.SID_FILE)
s = client.service[0][method_name](sid, cr)
analysis(client, sid, s)
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument(
'--method', type=str, dest='method',
help=_('call method'))
parser.add_argument(
'-l', '--lang', type=str, dest='lang',
help=_('language for translate'))
parser.add_argument(
'-p', '--port', type=int, default = '8888', dest='port',
help=_('port number'))
parser.add_argument(
'--host', type=str, default = 'localhost', dest='host',
help=_('host destination'))
parser.add_argument(
'--gen-cert-by', type=str, dest='by_host',
help=_('post request a signed certificate by server'))
parser.add_argument(
'--get-cert-from', type=str, dest='from_host',
help=_('get signed certificate from server'))
parser.add_argument(
'--cert-path', type=str, dest='path_to_cert',
help=_('path to cert and key file'))
return parser.parse_args()
def https_server(client, signaling, url):
client_post_auth(client)
signaling.start()
client_list_methods(client)
get_entire_frame(client)
#create_obj(client, "install_system")
while True:
try:
command = raw_input ('\n'+_("Command: "))
except KeyboardInterrupt:
print
sys.exit(1)
if (command == 'halt' or command == 'server_shutdown'):
client_shut(client)
#elif (command == 'say_hello' or command == 'say'):
#client_say_hello(client)
#elif (command == 'say_hello2' or command == 'say2'):
#client_say_hello2(client)
elif (command == 'server_start' or command == 'run'):
if os.path.exists(client.CERT_KEY) and\
os.path.exists(client.CERT_FILE) :
client = Client_suds(url,\
transport = HTTPSClientCertTransport(client.CERT_KEY,\
client.CERT_FILE))
#If the certificate file misses
else:
CERT_FILE = None
CERT_KEY = None
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE))
elif (command == 'login' or command == 'cl-login'):
client_login(client)
elif command in ['q', 'quit', 'exit']:
print _("Closing") + "\n"
signaling._Thread__stop()
time.sleep(0.3)
num = client_list_pid(client)
if num:
print _('at closing session, '
'data %d processes will be deleted!') %num
c = raw_input (_("Close your session y/[n]: "))
if c in ['y', 'yes', 'Y', 'YES']:
client_del_sid(client)
#signaling.killed = True
# client_shut(client)
return 0
else:
print _("Input Error")
#t.sleep(1)
#def http_server(client):
#pass
def main():
clear()
#password = getpass(prompt="Password: ")
logging.basicConfig(level=logging.FATAL)
logging.getLogger('suds.client').setLevel(logging.FATAL)
logging.getLogger('suds.transport').setLevel(logging.FATAL)
logging.getLogger('suds.transport.http').setLevel(logging.FATAL)
logging.getLogger('suds.umx.typed').setLevel(logging.ERROR)
clVars = DataVars()
clVars.flIniFile()
clVarsCore = DataVarsCore()
clVarsCore.importCore()
clVarsCore.flIniFile()
homePath = clVarsCore.Get('ur_home_path')
print _('path to cert and key file')
args = parse()
# translate
if args.lang:
print 'code not found!!!!'
port = args.port
host = args.host
path_to_cert = args.path_to_cert
if not path_to_cert:
path_to_cert = clVarsCore.Get('cl_client_cert_dir')
path_to_cert = path_to_cert.replace("~",homePath)
getCRL = threading.Thread(target=get_CRL, args = (path_to_cert, ))
getCRL.start()
if args.by_host:
client_post_request (path_to_cert, args.by_host)
return 0
if args.from_host:
client_get_cert (path_to_cert, args)
return 0
url = "https://%s:%d/?wsdl" %(host, port)
print "url = %s" %url
try:
client = Client_suds(url, \
transport = HTTPSClientCertTransport(None,None, path_to_cert))
server_host_name = client.service.get_server_host_name()
del (client)
except Exception, e:
print 'get host name error', e
#print _("Connection Error. Failure verification server.")
sys.exit(1)
try:
import glob
all_cert_list = glob.glob(os.path.join(path_to_cert, '*.crt'))
fit_cert_list = []
for client_cert_path in all_cert_list:
client_cert = client_cert_path.replace(path_to_cert, '')
client_cert_name = client_cert.replace('.crt', '')
if server_host_name.endswith(client_cert_name):
fit_cert_list.append(client_cert_name)
fit_cert_list.sort(key = len)
Connect_Error = 1
for i in range (0, len(fit_cert_list)):
#print 'fit_cert_list = ',fit_cert_list
cert_name = fit_cert_list.pop()
CERT_FILE = path_to_cert + cert_name + '.crt'
CERT_KEY = path_to_cert + cert_name + '.key'
try:
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\
path_to_cert))
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
client_post_cert(client)
Connect_Error = 0
except VerifyError, e:
print e.value
Connect_Error = 1
except Exception, e:
print e
Connect_Error = 1
#sys.exit()
if Connect_Error == 0:
break
#If the certificate file misses
if Connect_Error:
print 'CONNECT ERROR'
CERT_FILE = None
CERT_KEY = None
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\
path_to_cert))
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
Vars = DataVarsCore()
Vars.importCore()
Vars.flIniFile()
try:
client.frame_period = Vars.Get('cl_core_get_frame_period')
except:
client.frame_period = 2
signaling = threading.Thread(target=client_signal, args = (client, ))
signaling.setDaemon(True)
client.port = port
https_server(client, signaling, url)
#----------------------------------------------------
except WebFault, f:
print _("Exception: %s") %f
print f.fault
except TransportError, te:
print _("Exception: %s") %te
except Exception, e:
print _("Exception: %s") %e
tb.print_exc()

@ -0,0 +1,542 @@
#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import urllib2 as u2
import os, sys
from suds.transport.http import HttpTransport
import httplib
from httplib import HTTPConnection
import socket, ssl
import OpenSSL, hashlib
from calculate.core.datavars import DataVarsCore
from calculate.lib.datavars import DataVars
from suds.client import Client
from suds.cache import ObjectCache
from cert_verify import verify, get_CRL
from suds.options import Options
#import cert_func.verify
flag = 0
class Client_suds(Client):
def __init__(self, url, **kwargs):
Client.__init__(self, url, **kwargs)
options = Options()
options.cache = ObjectCache(days=0)
def set_parameters (self, path_to_cert, CERT_FILE, PKEY_FILE):
self.path_to_cert = path_to_cert
print 'CERT_FILE =', CERT_FILE
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:
print _("Certificate not found in client")
return None
try:
fd = open(self.trusted_path + filename, 'r')
store_cert = fd.read()
fd.close()
if store_cert == server_cert:
return filename
except:
print _("Error open 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()
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 open(system_ca_db, 'r').read():
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 open(user_root_cert, 'r').read():
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 _('Not found field "CN" in 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 ADD")
else:
print _("file with ca certificates 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 _('Server certificate is not valid')
sys.exit()
if cert == '2':
print _('CA not found on server')
sys.exit()
try:
certobj = OpenSSL.crypto.load_certificate \
(OpenSSL.SSL.FILETYPE_PEM, cert)
except:
print _("Error. Certificate not added to trusted")
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 CA certificates 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()
#def add_ca_cert(self, cert, list_ca_certs, prev_host = None):
#certobj = OpenSSL.crypto.load_certificate \
#(OpenSSL.SSL.FILETYPE_PEM, cert)
#Issuer = certobj.get_issuer().get_components()
#for item in Issuer:
#if item[0] == 'L':
#print '\nNetwork adress : ', item[1]
#current_host = item[1]
##print prev_host, item[1]
#try:
#host, port = item[1].split(':')
#port = int(port)
#except:
#print _("Network adress must be host:port. port must be int")
#return 1
#try:
#ca_cert = ssl.get_server_certificate(addr = (host, port))
#except:
#print _("Connection aborted!")
#sys.exit()
#certobj = OpenSSL.crypto.load_certificate \
#(OpenSSL.SSL.FILETYPE_PEM, ca_cert)
#print _("\nFingerprint = %s") % certobj.digest('SHA1')
#print _("Serial Number = "), certobj.get_serial_number()
#Issuer = certobj.get_issuer().get_components()
#print _("\nIssuer")
#for i in Issuer:
#print "%s : %s" %(i[0], i[1])
#Subject = certobj.get_subject().get_components()
#print _("\nSubject")
#for subj in Subject:
#print "%s : %s" %(subj[0], subj[1])
#if prev_host == item[1]:
#'''
#получить корневой сертификат и проверить его на рутовость
#'''
#print _("\nThis is root certificate!")
#print _("Add all CA certificates to trusted?\n"
#"ATTENTION! It allows access to all those who "
#"signed these certificates.\n"
#"This may affect your safety!")
#ans = raw_input (_("Add all CA certificates to trusted? "
#"y/[n]:"))
#if ans.lower() in ['y','yes']:
#self.add_all_ca_cert(list_ca_certs)
#else:
#print _("Certificate not added to trusted")
#sys.exit()
#ans = raw_input (_("\nNext? y/[n]: "))
#if not ans.lower() in ['y','yes']:
#print _("Exit")
#sys.exit()
#list_ca_certs.append(ca_cert)
#self.add_ca_cert(cert, self.list_ca_certs, current_host)
#print _("In this certificate not found field 'L' (Network adress)")
# add certificate server in trusted
def add_server_cert(self, cert):
print _("Untrusted Server Certificate!")
certobj = OpenSSL.crypto.load_certificate \
(OpenSSL.SSL.FILETYPE_PEM, cert)
print _("\nFingerprint = %s") % certobj.digest('SHA1')
print _("Serial Number = "), certobj.get_serial_number()
Issuer = certobj.get_issuer().get_components()
print _("\nIssuer")
for i in Issuer:
print "%s : %s" %(i[0], i