/usr/lib/python2.7/dist-packages/passlib/handlers/cisco.py is in python-passlib 1.7.0-2.
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 | """passlib.handlers.cisco - Cisco password hashes"""
#=============================================================================
# imports
#=============================================================================
# core
from binascii import hexlify, unhexlify
from hashlib import md5
import logging; log = logging.getLogger(__name__)
from warnings import warn
# site
# pkg
from passlib.utils import right_pad_string, to_unicode
from passlib.utils.binary import h64
from passlib.utils.compat import unicode, u, join_byte_values, \
join_byte_elems, iter_byte_values, uascii_to_str
import passlib.utils.handlers as uh
# local
__all__ = [
"cisco_pix",
"cisco_type7",
]
#=============================================================================
# cisco pix firewall hash
#=============================================================================
class cisco_pix(uh.TruncateMixin, uh.HasUserContext, uh.StaticHandler):
"""This class implements the password hash used by (older) Cisco PIX firewalls,
and follows the :ref:`password-hash-api`.
It does a single round of hashing, and relies on the username
as the salt.
The :meth:`~passlib.ifc.PasswordHash.hash`, :meth:`~passlib.ifc.PasswordHash.genhash`, and :meth:`~passlib.ifc.PasswordHash.verify` methods
have the following extra keyword:
:type user: str
:param user:
String containing name of user account this password is associated with.
This is *required* in order to correctly hash passwords associated
with a user account on the Cisco device, as it is used to salt
the hash.
Conversely, this *must* be omitted or set to ``""`` in order to correctly
hash passwords which don't have an associated user account
(such as the "enable" password).
:param bool truncate_error:
By default, this will silently truncate passwords larger than 16 bytes.
Setting ``truncate_error=True`` will cause :meth:`~passlib.ifc.PasswordHash.hash`
to raise a :exc:`~passlib.exc.PasswordTruncateError` instead.
.. versionadded:: 1.7
.. versionadded:: 1.6
"""
#===================================================================
# class attrs
#===================================================================
#--------------------
# PasswordHash
#--------------------
name = "cisco_pix"
setting_kwds = ("truncate_error",)
#--------------------
# GenericHandler
#--------------------
checksum_size = 16
checksum_chars = uh.HASH64_CHARS
#--------------------
# TruncateMixin
#--------------------
truncate_size = 16
#--------------------
# custom
#--------------------
#: control flag signalling "cisco_asa" mode
_is_asa = False
#===================================================================
# methods
#===================================================================
def _calc_checksum(self, secret):
# This function handles both the cisco_pix & cisco_asa formats:
# * PIX had a limit of 16 character passwords, and always appended the username.
# * ASA 7.0 (2005) increases this limit to 32, and conditionally appends the username.
# The two behaviors are controlled based on the _is_asa class-level flag.
asa = self._is_asa
# XXX: No idea what unicode policy is, but all examples are
# 7-bit ascii compatible, so using UTF-8.
if isinstance(secret, unicode):
secret = secret.encode("utf-8")
seclen = len(secret)
# check for truncation (during .hash() calls only)
if self.use_defaults:
self._check_truncate_policy(secret)
# PIX/ASA: Per-user accounts use the first 4 chars of the username as the salt,
# whereas global "enable" passwords don't have any salt at all.
# ASA only: Don't append user if password is 28 or more characters.
user = self.user
if user and not (asa and seclen > 27):
if isinstance(user, unicode):
user = user.encode("utf-8")
secret += user[:4]
# PIX: null-pad or truncate to 16 bytes.
# ASA: increase to 32 bytes if password is 13 or more characters.
if asa and seclen > 12:
padsize = 32
else:
padsize = 16
secret = right_pad_string(secret, padsize)
# md5 digest
hash = md5(secret).digest()
# drop every 4th byte
hash = join_byte_elems(c for i,c in enumerate(hash) if i & 3 < 3)
# encode using Hash64
return h64.encode_bytes(hash).decode("ascii")
#===================================================================
# eoc
#===================================================================
class cisco_asa(cisco_pix):
"""
This class implements the password hash used by Cisco ASA/PIX 7.0 and newer (2005).
Aside from a different internal algorithm, it's use and format is identical
to the older :class:`cisco_pix` class.
For passwords less than 13 characters, this should be identical to :class:`!cisco_pix`,
but will generate a different hash for anything larger
(See the `Format & Algorithm`_ section for the details).
Unlike cisco_pix, this will truncate passwords larger than 32 bytes.
.. versionadded:: 1.7
"""
#===================================================================
# class attrs
#===================================================================
#--------------------
# PasswordHash
#--------------------
name = "cisco_asa"
#--------------------
# TruncateMixin
#--------------------
truncate_size = 32
#--------------------
# cisco_pix
#--------------------
_is_asa = True
#===================================================================
# eoc
#===================================================================
#=============================================================================
# type 7
#=============================================================================
class cisco_type7(uh.GenericHandler):
"""This class implements the Type 7 password encoding used by Cisco IOS,
and follows the :ref:`password-hash-api`.
It has a simple 4-5 bit salt, but is nonetheless a reversible encoding
instead of a real hash.
The :meth:`~passlib.ifc.PasswordHash.using` method accepts the following optional keywords:
:type salt: int
:param salt:
This may be an optional salt integer drawn from ``range(0,16)``.
If omitted, one will be chosen at random.
:type relaxed: bool
:param relaxed:
By default, providing an invalid value for one of the other
keywords will result in a :exc:`ValueError`. If ``relaxed=True``,
and the error can be corrected, a :exc:`~passlib.exc.PasslibHashWarning`
will be issued instead. Correctable errors include
``salt`` values that are out of range.
Note that while this class outputs digests in upper-case hexadecimal,
it will accept lower-case as well.
This class also provides the following additional method:
.. automethod:: decode
"""
#===================================================================
# class attrs
#===================================================================
#--------------------
# PasswordHash
#--------------------
name = "cisco_type7"
setting_kwds = ("salt",)
#--------------------
# GenericHandler
#--------------------
checksum_chars = uh.UPPER_HEX_CHARS
#--------------------
# HasSalt
#--------------------
# NOTE: encoding could handle max_salt_value=99, but since key is only 52
# chars in size, not sure what appropriate behavior is for that edge case.
min_salt_value = 0
max_salt_value = 52
#===================================================================
# methods
#===================================================================
@classmethod
def using(cls, salt=None, **kwds):
subcls = super(cisco_type7, cls).using(**kwds)
if salt is not None:
salt = subcls._norm_salt(salt, relaxed=kwds.get("relaxed"))
subcls._generate_salt = staticmethod(lambda: salt)
return subcls
@classmethod
def from_string(cls, hash):
hash = to_unicode(hash, "ascii", "hash")
if len(hash) < 2:
raise uh.exc.InvalidHashError(cls)
salt = int(hash[:2]) # may throw ValueError
return cls(salt=salt, checksum=hash[2:].upper())
def __init__(self, salt=None, **kwds):
super(cisco_type7, self).__init__(**kwds)
if salt is not None:
salt = self._norm_salt(salt)
elif self.use_defaults:
salt = self._generate_salt()
assert self._norm_salt(salt) == salt, "generated invalid salt: %r" % (salt,)
else:
raise TypeError("no salt specified")
self.salt = salt
@classmethod
def _norm_salt(cls, salt, relaxed=False):
"""
validate & normalize salt value.
.. note::
the salt for this algorithm is an integer 0-52, not a string
"""
if not isinstance(salt, int):
raise uh.exc.ExpectedTypeError(salt, "integer", "salt")
if 0 <= salt <= cls.max_salt_value:
return salt
msg = "salt/offset must be in 0..52 range"
if relaxed:
warn(msg, uh.PasslibHashWarning)
return 0 if salt < 0 else cls.max_salt_value
else:
raise ValueError(msg)
@staticmethod
def _generate_salt():
return uh.rng.randint(0, 15)
def to_string(self):
return "%02d%s" % (self.salt, uascii_to_str(self.checksum))
def _calc_checksum(self, secret):
# XXX: no idea what unicode policy is, but all examples are
# 7-bit ascii compatible, so using UTF-8
if isinstance(secret, unicode):
secret = secret.encode("utf-8")
return hexlify(self._cipher(secret, self.salt)).decode("ascii").upper()
@classmethod
def decode(cls, hash, encoding="utf-8"):
"""decode hash, returning original password.
:arg hash: encoded password
:param encoding: optional encoding to use (defaults to ``UTF-8``).
:returns: password as unicode
"""
self = cls.from_string(hash)
tmp = unhexlify(self.checksum.encode("ascii"))
raw = self._cipher(tmp, self.salt)
return raw.decode(encoding) if encoding else raw
# type7 uses a xor-based vingere variant, using the following secret key:
_key = u("dsfd;kfoA,.iyewrkldJKDHSUBsgvca69834ncxv9873254k;fg87")
@classmethod
def _cipher(cls, data, salt):
"""xor static key against data - encrypts & decrypts"""
key = cls._key
key_size = len(key)
return join_byte_values(
value ^ ord(key[(salt + idx) % key_size])
for idx, value in enumerate(iter_byte_values(data))
)
#=============================================================================
# eof
#=============================================================================
|