From 3dd26c94fe3a7b109b837f7925fa753de8667554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=83=D0=BA=D0=B8=D0=BD=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Fri, 12 Feb 2010 11:58:35 +0300 Subject: [PATCH] reorganization of the library --- pym/cl_libserver.py | 89 --------------------- pym/server/encrypt.py | 178 +++++++++++++++++++++++++++++++++++++++++ pym/server/services.py | 87 -------------------- pym/server/users.py | 3 +- 4 files changed, 180 insertions(+), 177 deletions(-) delete mode 100644 pym/cl_libserver.py create mode 100644 pym/server/encrypt.py diff --git a/pym/cl_libserver.py b/pym/cl_libserver.py deleted file mode 100644 index 58eb4cf..0000000 --- a/pym/cl_libserver.py +++ /dev/null @@ -1,89 +0,0 @@ -#-*- coding: utf-8 -*- - -# Copyright 2008-2010 Mir Calculate Ltd. http://www.calculate-linux.org -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import sys -import os -import hashlib -import crypt -import string -from random import choice -from base64 import urlsafe_b64encode as b64encode - -from cl_print import color_print -import cl_lang - -from server.utils import copyDir - -tr = cl_lang.lang() -tr.setLocalDomain('cl_lib') -tr.setLanguage(sys.modules[__name__]) - - -class shareServer(color_print): - """Класс хранения общих методов используемых для настройки сервисов""" - - def __GenCryptSalt__(self): - """Генерация соли для хеширования пароля (CRYPT)""" - chars = string.letters + string.digits + "./" - salt = "" - for i in range(2): - salt = salt + choice(chars) - return salt - - def getHashPasswd(self, password, crypt): - """Генерация хеша пароля, - - Поддерживаемые алгоритмы шифрования пароля: - plain, md5, smd5, crypt, sha, ssha - """ - if not password: - self.printERROR(_("ERROR") + " getHashPasswd: " +\ - _("password empty")) - return False - - hashPwd = "" - if crypt == "plain": - hashPwd = password - - elif crypt == "md5": - h = hashlib.md5(password) - hashPwd = "{MD5}" + b64encode(h.digest()) - - elif crypt == "smd5": - salt = os.urandom(4) - h = hashlib.md5(password) - h.update(salt) - hashPwd = "{SMD5}" + b64encode(h.digest() + salt) - - elif crypt == "crypt": - salt = self.__GenCryptSalt__() - hashPwd = "{CRYPT}" + crypt.crypt(password, salt) - - elif crypt == "sha": - h = hashlib.sha1(password) - hashPwd = "{SHA}" + b64encode(h.digest()) - - elif crypt == "ssha": - salt = os.urandom(4) - h = hashlib.sha1(password) - h.update(salt) - hashPwd = "{SSHA}" + b64encode(h.digest() + salt) - - else: - self.printERROR(_("ERROR") + " getHashPasswd: " +\ - _("Can not support '%s' crypto algoritm")%crypt) - return False - return hashPwd diff --git a/pym/server/encrypt.py b/pym/server/encrypt.py new file mode 100644 index 0000000..4dfbcfe --- /dev/null +++ b/pym/server/encrypt.py @@ -0,0 +1,178 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2010 Mir Calculate Ltd. http://www.calculate-linux.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import os +import hashlib +import crypt +import string +import time +from random import choice +from base64 import urlsafe_b64encode as b64encode +from cl_print import color_print +from server.users import users +from server.utils import execProg +import cl_lang +# Перевод модуля +tr = cl_lang.lang() +tr.setLocalDomain('cl_lib') +tr.setLanguage(sys.modules[__name__]) + + +class encrypt(color_print): + """Класс хранения общих методов используемых для настройки сервисов + + Методы шифрования, создания сертификатов и.т. д + """ + + def __GenCryptSalt__(self): + """Генерация соли для хеширования пароля (CRYPT)""" + chars = string.letters + string.digits + "./" + salt = "" + for i in range(2): + salt = salt + choice(chars) + return salt + + def getHashPasswd(self, password, crypt): + """Генерация хеша пароля, + + Поддерживаемые алгоритмы шифрования пароля: + plain, md5, smd5, crypt, sha, ssha + """ + if not password: + self.printERROR(_("ERROR") + " getHashPasswd: " +\ + _("password empty")) + return False + + hashPwd = "" + if crypt == "plain": + hashPwd = password + + elif crypt == "md5": + h = hashlib.md5(password) + hashPwd = "{MD5}" + b64encode(h.digest()) + + elif crypt == "smd5": + salt = os.urandom(4) + h = hashlib.md5(password) + h.update(salt) + hashPwd = "{SMD5}" + b64encode(h.digest() + salt) + + elif crypt == "crypt": + salt = self.__GenCryptSalt__() + hashPwd = "{CRYPT}" + crypt.crypt(password, salt) + + elif crypt == "sha": + h = hashlib.sha1(password) + hashPwd = "{SHA}" + b64encode(h.digest()) + + elif crypt == "ssha": + salt = os.urandom(4) + h = hashlib.sha1(password) + h.update(salt) + hashPwd = "{SSHA}" + b64encode(h.digest() + salt) + + else: + self.printERROR(_("ERROR") + " getHashPasswd: " +\ + _("Can not support '%s' crypto algoritm")%crypt) + return False + return hashPwd + + def createCertificate(self, sslCountry="US", + sslState="California", + sslLocality="Santa Barbara", + sslOrganization="SSL Server", + sslUnit="For Testing Purposes Only", + sslCommonName="localhost", + sslEmail="root@localhost", + nsCertType="server", + sslDays=730, + sslBits=1024, + userName="root",groupName="root", + certFile="/tmp/server.pem", + certFileMode=0400, + keyFile="/tmp/server.key", + keyFileMode=0400): + """Создает сертификат""" + certAndKeyFiles = [certFile, keyFile] + foundCertFiles = filter(lambda x: os.path.exists(x), certAndKeyFiles) + if len(foundCertFiles)==2: + return True + # Удаляем файл сертификата + map(lambda x: os.remove(x), foundCertFiles) + # Объект для работы с пользователями + usersObj = users() + # получаем id и gid пользователя + uidAndGid = usersObj.getUserUidAndGid(userName, groupName) + if not uidAndGid: + return False + uid, gid = uidAndGid + textCnf="""[ req ] +prompt = no +default_bits = %s +distinguished_name = req_dn + +[ req_dn ] +C = %s +ST = %s +L = %s +O = %s +OU = %s +CN = %s +emailAddress = %s + +[ cert_type ] +nsCertType = %s +"""%(sslBits, sslCountry, sslState, sslLocality, sslOrganization, sslUnit, + sslCommonName, sslEmail, nsCertType) + # генерируем название файла конфигурации + strData = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())) + cnfFile = "/tmp/%s.cnf" %strData + sslFile = "/usr/bin/openssl" + if not os.path.exists(sslFile): + self.printERROR(_("Can not found %s")%sslFile) + return False + # Cоздание директорий + for fileName in certAndKeyFiles: + dirName = os.path.split(fileName)[0] + if not os.path.exists(dirName): + self.createUserDir(0, 0, dirName, 0755) + # Создание конфигурационного файла + usersObj.createUserFile(cnfFile, textCnf, 0, 0, 0600) + # Создание сертификата + textLine = execProg(\ + "%s req -new -x509 -nodes -config %s -days %s -out %s -keyout %s"\ + %(sslFile, cnfFile, sslDays, certFile, keyFile)) + # Удаление конфигурационного файла + if os.path.exists(cnfFile): + os.remove(cnfFile) + # Меняем права + if os.path.exists(certFile): + os.chown(certFile, uid,gid) + os.chmod(certFile, certFileMode) + if os.path.exists(keyFile): + os.chown(keyFile, uid,gid) + os.chmod(keyFile, keyFileMode) + if textLine == False: + self.printERROR(_("Can not create certificate %s")%certFile) + return False + # Проверка сертификата + textLine = execProg("%s x509 -subject -fingerprint -noout -in %s"\ + %(sslFile, certFile)) + if textLine == False: + self.printERROR(_("Can not create certificate %s")%certFile) + return False + return True \ No newline at end of file diff --git a/pym/server/services.py b/pym/server/services.py index 62bd022..9b6d63a 100644 --- a/pym/server/services.py +++ b/pym/server/services.py @@ -21,7 +21,6 @@ import time from cl_print import color_print from cl_template import template from server.utils import execProg -from server.users import users # Перевод модуля import cl_lang tr = cl_lang.lang() @@ -476,89 +475,3 @@ This command is not allowed.")) This command is not allowed.")) return False return True - - def createCertificate(self, sslCountry="US", - sslState="California", - sslLocality="Santa Barbara", - sslOrganization="SSL Server", - sslUnit="For Testing Purposes Only", - sslCommonName="localhost", - sslEmail="root@localhost", - nsCertType="server", - sslDays=730, - sslBits=1024, - userName="root",groupName="root", - certFile="/tmp/server.pem", - certFileMode=0400, - keyFile="/tmp/server.key", - keyFileMode=0400): - """Создает сертификат""" - certAndKeyFiles = [certFile, keyFile] - foundCertFiles = filter(lambda x: os.path.exists(x), certAndKeyFiles) - if len(foundCertFiles)==2: - return True - # Удаляем файл сертификата - map(lambda x: os.remove(x), foundCertFiles) - # Объект для работы с пользователями - usersObj = users() - # получаем id и gid пользователя - uidAndGid = usersObj.getUserUidAndGid(userName, groupName) - if not uidAndGid: - return False - uid, gid = uidAndGid - textCnf="""[ req ] -prompt = no -default_bits = %s -distinguished_name = req_dn - -[ req_dn ] -C = %s -ST = %s -L = %s -O = %s -OU = %s -CN = %s -emailAddress = %s - -[ cert_type ] -nsCertType = %s -"""%(sslBits, sslCountry, sslState, sslLocality, sslOrganization, sslUnit, - sslCommonName, sslEmail, nsCertType) - # генерируем название файла конфигурации - strData = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())) - cnfFile = "/tmp/%s.cnf" %strData - sslFile = "/usr/bin/openssl" - if not os.path.exists(sslFile): - self.printERROR(_("Can not found %s")%sslFile) - return False - # Cоздание директорий - for fileName in certAndKeyFiles: - dirName = os.path.split(fileName)[0] - if not os.path.exists(dirName): - self.createUserDir(0, 0, dirName, 0755) - # Создание конфигурационного файла - self.createUserFile(cnfFile, textCnf, 0, 0, 0600) - # Создание сертификата - textLine = execProg(\ - "%s req -new -x509 -nodes -config %s -days %s -out %s -keyout %s"\ - %(sslFile, cnfFile, sslDays, certFile, keyFile)) - # Удаление конфигурационного файла - if os.path.exists(cnfFile): - os.remove(cnfFile) - # Меняем права - if os.path.exists(certFile): - os.chown(certFile, uid,gid) - os.chmod(certFile, certFileMode) - if os.path.exists(keyFile): - os.chown(keyFile, uid,gid) - os.chmod(keyFile, keyFileMode) - if textLine == False: - self.printERROR(_("Can not create certificate %s")%certFile) - return False - # Проверка сертификата - textLine = execProg("%s x509 -subject -fingerprint -noout -in %s"\ - %(sslFile, certFile)) - if textLine == False: - self.printERROR(_("Can not create certificate %s")%certFile) - return False - return True \ No newline at end of file diff --git a/pym/server/users.py b/pym/server/users.py index e815eb1..f12517d 100644 --- a/pym/server/users.py +++ b/pym/server/users.py @@ -133,7 +133,8 @@ in a sambaDomainName', import grp gid = grp.getgrnam(groupName)[2] except: - self.printERROR(_("Can not found user %s in this system")%groupName) + self.printERROR(_("Can not found group %s in this system")\ + %groupName) return () return (uid, gid)