/usr/lib/python2.7/dist-packages/revelation/util.py is in revelation 0.4.14-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | #
# Revelation - a password manager for GNOME 2
# http://oss.codepoet.no/revelation/
# $Id$
#
# Module with various utility functions
#
#
# Copyright (c) 2003-2006 Erik Grinaker
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import datetime, cracklib, gettext, math, os, random, shlex, string, StringIO, traceback
_ = gettext.gettext
class SubstFormatError(Exception):
"Exception for parse_subst format errors"
pass
class SubstValueError(Exception):
"Exception for missing values in parse_subst"
pass
def check_password(password):
"Checks if a password is valid"
# check for length
if len(password) < 6:
raise ValueError, _('is too short')
# check for entropy
pwlen = len(password)
ent = entropy(password)
idealent = entropy_ideal(pwlen)
if (pwlen < 100 and ent / idealent < 0.8) or (pwlen >= 100 and ent < 5.3):
raise ValueError, _('isn\'t varied enough')
# check the password strength
lc, uc, d, o = 0, 0, 0, 0
for c in password:
if c in string.ascii_lowercase:
lc += 1
elif c in string.ascii_uppercase:
uc += 1
elif c in string.digits:
d += 1
else:
o += 1
classcount = [ lc, uc, d, o ]
classcount.sort()
classcount.reverse()
cred = sum([ count * (1 + (weight ** 2.161 / 10)) for weight, count in zip(range(1, len(classcount) + 1), classcount) ])
if cred < 10:
raise ValueError, _('is too weak')
# check if the password is a palindrome
for i in range(len(password)):
if password[i] != password[-i - 1]:
break
else:
raise ValueError, _('is a palindrome')
# check password with cracklib
try:
if len(password) < 100:
cracklib.FascistCheck(password)
except ValueError, reason:
# modify reason
reason = str(reason).strip()
reason = reason.replace("simplistic/systematic", "systematic")
reason = reason.replace(" dictionary", "")
if reason[:3] == "it ":
reason = reason[3:]
if reason[:5] == "it's ":
reason = "is " + reason[5:]
raise ValueError, reason
except IOError:
pass
def dom_text(node):
"Returns text content of a DOM node"
text = ""
for child in node.childNodes:
if child.nodeType == node.TEXT_NODE:
text += child.nodeValue.encode("utf-8")
return text
def entropy(string):
"Calculates the Shannon entropy of a string"
# get probability of chars in string
prob = [ float(string.count(c)) / len(string) for c in dict.fromkeys(list(string)) ]
# calculate the entropy
entropy = - sum([ p * math.log(p) / math.log(2.0) for p in prob ])
return entropy
def entropy_ideal(length):
"Calculates the ideal Shannon entropy of a string with given length"
prob = 1.0 / length
return -1.0 * length * prob * math.log(prob) / math.log(2.0)
def escape_markup(string):
"Escapes a string so it can be placed in a markup string"
if string is None:
return ""
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
return string
def execute(command):
"Runs a command, returns its status code and output"
p = os.popen(command, "r")
output = p.read()
status = p.close()
if status is None:
status = 0
status = status >> 8
return output, status
def execute_child(command):
"Runs a command as a child, returns its process ID"
items = shlex.split(command.encode("iso-8859-1"), 0)
return os.spawnvp(os.P_NOWAIT, items[0], items)
def generate_password(length, punctuation):
"Generates a password"
# set up character sets
d = string.digits.translate(string.maketrans("", ""), "015")
lc = string.ascii_lowercase.translate(string.maketrans("", ""), "lqg")
uc = string.ascii_uppercase.translate(string.maketrans("", ""), "IOS")
fullset = d + uc + lc
if punctuation:
p = string.punctuation
fullset = fullset + p
charsets = (
( d, 0.15 ),
( uc, 0.24 ),
( lc, 0.24 ),
( p, 0.15 ),
)
else:
charsets = (
( d, 0.15 ),
( uc, 0.24 ),
( lc, 0.24 ),
)
# function for generating password
def genpw(length):
password = []
for set, share in charsets:
password.extend([ random.choice(set) for i in range(int(round(length * share))) ])
while len(password) < length:
password.append(random.choice(fullset))
random.shuffle(password)
return "".join(password)
# check password, and regenerate if needed
while 1:
try:
password = genpw(length)
if length <= 6:
return password
check_password(password)
return password
except ValueError:
continue
def pad_right(string, length, padchar = " "):
"Right-pads a string to a given length"
if string is None:
return None
if len(string) >= length:
return string
return string + ((length - len(string)) * padchar)
def parse_subst(string, map):
"Parses a string for substitution variables"
result = ""
pos = 0
while pos < len(string):
char = string[pos]
next = pos + 1 < len(string) and string[pos + 1] or ""
# handle normal characters
if char != "%":
result += char
pos += 1
# handle % escapes (%%)
elif next == "%":
result += "%"
pos += 2
# handle optional substitution variables
elif next == "?":
if map.has_key(string[pos + 2]):
result += map[string[pos + 2]]
pos += 3
else:
raise SubstFormatError
# handle optional substring expansions
elif next == "(":
try:
result += parse_subst(string[pos + 2:string.index("%)", pos + 1)], map)
except ValueError:
raise SubstFormatError
except SubstValueError:
pass
pos = string.index("%)", pos + 1) + 2
# handle required ("normal") substitution variables
elif map.has_key(next):
if map[next] in [ "", None ]:
raise SubstValueError
result += map[next]
pos += 2
# otherwise, it's a format error
else:
raise SubstFormatError
return result
def random_string(length):
"Generates a random string"
s = ""
for i in range(length):
s += chr(int(random.random() * 255))
return s
def time_period_rough(start, end):
"Returns the rough period from start to end in human-readable format"
if end < start:
return _('%i seconds') % 0
start = datetime.datetime.utcfromtimestamp(float(start))
end = datetime.datetime.utcfromtimestamp(float(end))
delta = end - start
if delta.days >= 365:
period = delta.days / 365
unit = period != 1 and _('years') or _('year')
elif delta.days >= 31 or (end.month != start.month and (end.day > start.day or (end.day == start.day and end.time() >= start.time()))):
period = ((end.year - start.year) * 12) + end.month - start.month
if end.day < start.day or (end.day == start.day and end.time() < start.time()):
period -= 1
unit = period != 1 and _('months') or _('month')
elif delta.days >= 7:
period = delta.days / 7
unit = period != 1 and _('weeks') or _('week')
elif delta.days >= 1:
period = delta.days
unit = period != 1 and _('days') or _('day')
elif delta.seconds >= 3600:
period = delta.seconds / 3600
unit = period != 1 and _('hours') or _('hour')
elif delta.seconds >= 60:
period = delta.seconds / 60
unit = period != 1 and _('minutes') or _('minute')
else:
period = delta.seconds
unit = period != 1 and _('seconds') or _('second')
return "%d %s" % ( period, unit )
def trace_exception(type, value, tb):
"Returns an exception traceback as a string"
trace = StringIO.StringIO()
traceback.print_exception(type, value, tb, None, trace)
return trace.getvalue()
def unescape_markup(string):
"Unescapes a string to get literal values"
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
return string
|