Изменения для шифрования пользовательского профиля

Файлы ini.env (системный или пользовательский) не отображаются в списке
измененных шаблонами файлов.
Добавлена функция подключения шифрованного пользовательского каталога.

Добавлены функции:
elog():получение времени последней записи /var/log/emerge.log

Добавлены переменные:
cl_home_crypt_set: вкл/выкл шифрование пользовательских профилей
ur_home_crypt_set: шифровать или нет пользователя ur_login
master3.3 3.1.6
Mike Hiretsky 11 years ago
parent 57589fa282
commit 833c5c2fc4

@ -3113,18 +3113,25 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction):
return int(val)
return 0
elogFile = '/var/log/emerge.log'
@classmethod
def getLastElog(cls):
# get last timestamp
lastStr = ""
for l in readLinesFile(cls.elogFile):
lastStr = l
return lastStr.partition(':')[0]
def funcElog(self,funArgv, resS, localVars, textTemplateTmp, nameTemp):
"""Function for work with emerge.log"""
# TODO: need remove
return textTemplateTmp
funArgv = funArgv.strip()
rePkg = re.compile(r'completed emerge \(\d+ of \d+\) (\S+)\s',re.S)
logFile = '/var/log/emerge.log'
replace = ""
if funArgv:
lastTimestamp = self.getElogTimestamp()
skip = True
for line in reversed(list(readLinesFile(logFile))):
for line in reversed(list(readLinesFile(self.elogFile))):
timestamp,op,info = line.partition(':')
if timestamp.isdigit() and lastTimestamp and \
int(timestamp) < lastTimestamp:
@ -3136,9 +3143,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction):
replace = pkgInfo['PVR']
break
else:
# get last timestamp
replace = readFile(logFile).rpartition(
'\n')[2].lpartition(':')[0]
replace = self.getLastElog()
textTemplateTmp = textTemplateTmp[:resS.start()] + replace + \
textTemplateTmp[resS.end():]
return textTemplateTmp
@ -5586,7 +5591,9 @@ gettext -d cl_template "$*"
optFile)
if not objHeadNew:
return filesApply
self.templateModify()
if filesApply and not filter(lambda x:"calculate/ini.env" in x,
filesApply):
self.templateModify()
if templateFileType != "bin":
# Вычисляем условные блоки
objHeadNew.body = self.applyTermsTemplate(objHeadNew.body,

@ -27,6 +27,9 @@ import string
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_lib3',sys.modules[__name__])
class CommonError(Exception):
pass
class _error:
# Здесь ошибки, если они есть
error = []
@ -408,3 +411,63 @@ def getGroups(prefix="/"):
map(lambda x:x.split(':')[0],
readLinesFile(path.join(prefix,'etc/group'))))
def mountEcryptfs(userName,userPwd,userDir):
"""
Подключить ecryptfs
Args:
userName: логин пользователя
userPwd: пароль пользователя
userDir: домашний каталог пользователя
"""
from calculate.lib.utils.files import (process,readLinesFile,STDOUT,
isMount)
if ".Private" in isMount(userDir):
return True
# расшифровать passphrase
ecryptUserName = path.join('/home/.ecryptfs', userName)
wrappedPassphraseFile = path.join(ecryptUserName,
".ecryptfs/wrapped-passphrase")
p = process('/usr/bin/ecryptfs-unwrap-passphrase',wrappedPassphraseFile)
p.write(userPwd)
try:
if p.failed():
raise Exception
result = p.readlines()
if len(result) > 1 and "Passphrase:" in result[0] and result[1]:
passphrase = result[1]
else:
raise Exception
except:
raise CommonError("Failed to unwrap passphrase")
# добавить passphrase в ключи ядра
p = process('/usr/bin/ecryptfs-add-passphrase', '--fnek', '-',stderr=STDOUT)
p.write(passphrase)
if not p.success():
raise CommonError(p.read()+"Failed to add passphrase")
# получить сигнатуры шифрования содержимого файлов и имен файлов
try:
ecryptfs_sig, ecryptfs_fnek_sig = \
readLinesFile(path.join(ecryptUserName,".ecryptfs/Private.sig"))
except ValueError:
raise CommonError("Failed to parse Private.sig")
# подключить шифрованный раздел
mountProcess = process('/sbin/mount.ecryptfs',
path.join(ecryptUserName,'.Private'),
userDir,
'-o','ecryptfs_passthrough=n,'
'ecryptfs_cipher=aes,'
'ecryptfs_key_bytes=16,'
'no_sig_cache,'
'ecryptfs_enable_filename_crypto=y,'
'ecryptfs_sig={ecryptfs_sig},'
'ecryptfs_fnek_sig={ecryptfs_fnek_sig},'
'passphrase_passwd_fd=0'.format(
ecryptfs_sig=ecryptfs_sig,
ecryptfs_fnek_sig=ecryptfs_fnek_sig),stderr=STDOUT)
# отправить пароль через stdin
mountProcess.write("passphrase_passwd="+userPwd)
return mountProcess.success()

@ -25,4 +25,4 @@ class VariableClVer(ReadonlyVariable):
"""
Package version
"""
value = "3.1.5.1"
value = "3.1.6"

@ -197,10 +197,8 @@ class VariableClAutoupdateSet(Variable):
def get(self):
if self.Get('cl_dispatch_conf') == 'usenew':
print "ON"
return "on"
else:
print "OFF"
return "off"
class VariableClDispatchConf(Variable):

@ -18,10 +18,11 @@ import os
import socket
import pwd
import grp
from os import environ
from os import environ,path
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.cl_vars_share import varsShare
from calculate.lib.utils.common import getPasswdUsers
from calculate.lib.utils.files import listDirectory
import sys
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_lib3',sys.modules[__name__])
@ -202,3 +203,33 @@ class VariableUrMail(ReadonlyVariable,LdapHelper):
if userInfo:
userMail = userInfo["mail"]
return userMail
class VariableClHomeCryptSet(Variable):
"""
Вкл/выкл шифрование пользовательских профилей
"""
value = "off"
type = "bool"
class VariableUrHomeCryptSet(ReadonlyVariable):
"""
Шифрованный или нет пользовательский профиль
"""
type = "bool"
def get(self):
# если у пользователский профиль настроен как шифрованный
login = self.Get('ur_login')
if login == "root":
return "off"
cryptPath = path.join('/home/.ecryptfs',login,'.ecryptfs')
if path.exists(cryptPath):
return "on"
# если пользовательского профиля нет, то шифровать ли профиль
# узнаем на уровне системы
homeDir = self.Get('ur_home_path')
if not path.exists(homeDir) or not listDirectory(homeDir):
return self.Get('cl_home_crypt_set')
# профиль не шифрованный
return "off"

@ -22,7 +22,7 @@ from distutils.core import setup
from distutils.command.build_scripts import build_scripts
from distutils.command.install_scripts import install_scripts
__version__ = "3.1.4"
__version__ = "3.1.6"
__app__ = "calculate-lib"
module_name = "calculate.lib"

Loading…
Cancel
Save