GNS3 Docker Images
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

do_auth.py 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. #!/usr/bin/env python
  2. # vim: ts=4:sw=4:expandtab
  3. """
  4. do_auth is a Python program to work as an authorization script for the
  5. ``tac_plus`` TACACS+ daemon to allow greater flexibility in TACACS+
  6. authentication and authorization. For more information on tac_plus please see
  7. http://shrubbery.net/tac_plus.
  8. It allows a user to be part of many predefined groups that can allow different
  9. access to different devices based on device IP address, usernmae, and source IP
  10. address.
  11. Do not play with do_auth until you have a firm grasp on ``tac_plus`` and the
  12. syntax for ``do_auth.ini``!
  13. Users
  14. =====
  15. To define users you must specify a ``[users]`` section. A user must be assigned
  16. to one or more groups, one per line::
  17. [users]
  18. homer =
  19. simpson_group
  20. television_group
  21. stimpy =
  22. television_group
  23. Groups
  24. ======
  25. Groups are assigned to users in the ``[users]`` section. Groups are defined in
  26. brackets, and can have any name. Each group can have up to eight options as
  27. defined below:
  28. host_deny
  29. (Optional) Deny any user coming from this host.
  30. host_allow
  31. (Mandatory if -i is specified) Allow users from this range.
  32. device_deny
  33. (Optional) Deny any device with this IP.
  34. device_permit
  35. (Mandatory if -d is specified) Allow this range.
  36. command_deny
  37. (Optional) Deny these commands.
  38. command_permit
  39. (Mandatory) Allow these commands.
  40. av_pairs
  41. (Advanced - Use with care) List of av pairs to replace if found.
  42. exit_val
  43. (Advanced - Use with care) hard code return value.
  44. These options are parsed in order until a match is found. For login authentication,
  45. the commands section is not parsed. If a match is not found, or a deny is
  46. found, we move on to the next group. At the end, we have an implicit deny if no
  47. groups match.
  48. An simple example is as follows::
  49. [users]
  50. homer =
  51. simpson_group
  52. television_group
  53. stimpy =
  54. television_group
  55. [simpson_group]
  56. host_deny =
  57. 1.1.1.1
  58. 1.1.1.2
  59. host_allow =
  60. 1.1.1.*
  61. device_permit =
  62. 10.1.1.*
  63. command_permit =
  64. .*
  65. [television_group]
  66. host_allow =
  67. .*
  68. device_permit =
  69. .*
  70. command_permit =
  71. show.*
  72. Example tac_plus config line::
  73. after authorization "/usr/bin/python /root/do_auth.pyc -i $address -fix_crs_bug -u $user -d $name -l /root/log.txt -f /root/do_auth.ini"
  74. The following ``av_pair`` example will replace any ``priv-lvl`` with
  75. ``priv-lvl=1`` **only** if passed. Think of it as a find/replace function::
  76. av_pairs =
  77. priv-lvl=1
  78. Brocade devices
  79. ---------------
  80. Brocade has a vendor-specific attribute called ``brocade-privlvl``. It maps
  81. ``priv-lvl`` to ``brocade-privlvl``, but the result is an account that has some
  82. privileges. Here is an example of how to map ``brocade-privlvl=5`` which has no
  83. modification rights. Unfortunately, it also requires you to specify the IP
  84. addresses of your
  85. Brocade devices.
  86. You could also put ``priv-lvl=15,brocade-privlvl=5`` or whatever your tac_plus
  87. deamon is passing. As long as the A/V pairs match the results are the same. In
  88. this example, we essentially replace the whole ``av_pair`` resulting in the user
  89. having read-only access.
  90. To work the Brocade-specific group must be above the other groups::
  91. [brocade_readonly]
  92. host_allow =
  93. .*
  94. device_permit =
  95. 192.168.1.*
  96. command_permit =
  97. .*
  98. av_pairs =
  99. priv-lvl,brocade-privlvl=5
  100. Cisco Nexus devices
  101. -------------------
  102. Due to a slight change in the Nexus, ``do_auth`` is able to identify a device as
  103. a Cisco Nexus. In ``tac_plus.conf``, do the following::
  104. service = exec {
  105. priv-lvl = 1
  106. shell:roles=\"\\"network-operator\\""
  107. idletime = 3
  108. timeout = 15
  109. }
  110. after authorization "<do_auth yada yada>"
  111. This configuration **WILL NOT** work without ``do_auth``, however, with
  112. ``do_auth`` the ``shell:roles`` A/V pair will only be sent to Nexus switches,
  113. allowing your other devices to work correctly. These roles can also be modified
  114. in a ``do_auth`` group, as below::
  115. av_pairs =
  116. priv-lvl=15
  117. shell:roles="network-admin"
  118. NOTE: You **must** use double quotes to get ``tac_plus`` to correctly pass
  119. "network-operator" in the ``service`` definition example above. Unless you are
  120. explicitly modifying the attribute with ``do_auth`` in ``av_pairs``, it will be
  121. adjusted for you!
  122. HP Procurve devices
  123. -------------------
  124. This is the worst TACACS+ implementation I've ever seen and is the whole reason
  125. for the ``exit_val`` group option. This is to work around the incorrect
  126. implementation by HP. NOT MY FAULT!
  127. Setting ``exit_val`` to ``0`` makes it work (the Procurve doesn't like
  128. ``AUTHOR_STATUS_PASS_REPL``). Unfortunately, this means you need to define your
  129. Procurves in a distinct group and it must be the **very first**
  130. group defined::
  131. [fix_procurve]
  132. host_allow =
  133. .*
  134. device_permit =
  135. 192.168.1.*
  136. command_permit =
  137. .*
  138. exit_val =
  139. 0
  140. Known Issues
  141. ============
  142. You must know your regular expressions. If you enter a bad expression, such as
  143. "*." instead of ".*", Python's "re" module will freak out and not evaluate the
  144. expression.
  145. Caveats
  146. =======
  147. Ordering of groups is crucial. One group can not take away what another group
  148. grants. If a match is not found, it will go on to the next group. If a deny is
  149. matched, it will go on to the next group. The groups should go from
  150. most-specific to least-specific.
  151. For example::
  152. [users]
  153. homer =
  154. simpson_group
  155. television_group
  156. stimpy =
  157. television_group
  158. [simpson_group]
  159. host_deny =
  160. 1.1.1.1
  161. 1.1.1.2
  162. host_allow =
  163. 1.1.1.*
  164. device_permit =
  165. 10.1.1.*
  166. command_permit =
  167. .*
  168. [television_group]
  169. host_allow =
  170. .*
  171. device_permit =
  172. .*
  173. command_permit =
  174. show.*
  175. In this example, if ``television_group`` was put before ``simpson_group``,
  176. ``simpson_group`` would never be called because ``televsion_group`` catches
  177. everything in ``device_permit``.
  178. License
  179. =======
  180. This program is free software; you can redistribute it and/or modify it under
  181. the terms of the GNU General Public License version 3 or any later version as
  182. published by the Free Software Foundation, http://www.gnu.org/
  183. This program is distributed in the hope that it will be useful, but WITHOUT ANY
  184. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  185. PARTICULAR PURPOSE. See LICENSE in the ``do_auth`` source distribution for more
  186. details.
  187. """
  188. __author__ = 'Dan Schmidt, Jathan McCollum'
  189. __maintainer__ = 'Dan Schmidt, Jathan McCollum'
  190. __email__ = 'daniel.schmidt@wyo.gov'
  191. __copyright__ = 'Dan Schmidt'
  192. __license__ = 'GPL-3.0'
  193. __version__ = '1.13'
  194. try:
  195. import configparser
  196. except ImportError:
  197. import ConfigParser as configparser
  198. import logging
  199. import optparse
  200. import os
  201. import sys
  202. import re
  203. from time import strftime
  204. try:
  205. from os import getgrouplist as os_getgrouplist
  206. got_getgrouplist = True
  207. from pwd import getpwnam as pwd_getpwnam
  208. from grp import getgrgid as grp_getgrgid
  209. except ImportError:
  210. got_getgrouplist = False
  211. # Defaults
  212. CONFIG = 'do_auth.ini'
  213. LOG_FILE = '/dev/null'
  214. LOG_LEVEL = logging.INFO
  215. LOG_FORMAT = "%(asctime)s [%(levelname)s]: %(message)s"
  216. DEBUG = os.getenv('DEBUG', False)
  217. # Placeholder for global logging object
  218. log = None
  219. # Only display debug messages if we've set the DEBUG env variable
  220. if DEBUG:
  221. LOG_LEVEL = logging.DEBUG
  222. # FIXME(jathan): This is a quick hack to prevent the Juniper a/v pair for
  223. # 'user-permissions' to not be converted, because it is allowed to have a
  224. # comma-separated attribute value! This will be addressed generally in v2.0!
  225. SKIP_CONVERT = ['user-permissions']
  226. # Functions
  227. def _setup_logging(filename=LOG_FILE, format=LOG_FORMAT, level=LOG_LEVEL):
  228. """Returns a logging object. Intended to be called by main before any
  229. logging occurs."""
  230. logging.basicConfig(
  231. level=level,
  232. format=format,
  233. filename=filename
  234. )
  235. return logging.getLogger(__name__)
  236. def dprint(*args, **kwargs):
  237. """Pretty-print the passed in values if global ``DEBUG`` is set."""
  238. if DEBUG:
  239. for a in args:
  240. print(a)
  241. for k,v in kwargs.items():
  242. print('%s = %s' % (k.upper(), v))
  243. if args and kwargs:
  244. print('')
  245. def _product(*args, **kwds):
  246. """
  247. Adapted from itertools.product
  248. Ref: http://docs.python.org/2/library/itertools.html#itertools.product
  249. product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
  250. product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
  251. """
  252. pools = list(map(tuple, args)) * kwds.get('repeat', 1)
  253. result = [[]]
  254. for pool in pools:
  255. result = [x+[y] for x in result for y in pool]
  256. for prod in result:
  257. yield tuple(prod)
  258. # itertools.product() wasn't added until Python 2.6, so this is so we can
  259. # support Python 2.3+
  260. try:
  261. from itertools import product
  262. except ImportError:
  263. product = _product
  264. def get_attribute(config, the_section, the_option, filename):
  265. """
  266. Fetches a section by name from the config and returns a list of attributes.
  267. I really don't want to deal with these exceptions more than once filename
  268. is only used in log statements.
  269. """
  270. log.debug('get_attributes(%s)' % locals())
  271. if not config.has_section(the_section):
  272. log.critical("Section '%s' does not exist in %s" % (the_section, filename))
  273. sys.exit(1)
  274. if not config.has_option(the_section, the_option):
  275. log.critical("Option '%s' does not exist in section %s in file %s" % (the_option, the_section, filename))
  276. sys.exit(1)
  277. # Should not have any exceptions - BUT, just in case
  278. try:
  279. attributes = config.get(the_section, the_option)
  280. except configparser.NoSectionError:
  281. log.critical("Section '%s' Doesn't Exist!" % (the_section))
  282. sys.exit(1)
  283. except configparser.DuplicateSectionError:
  284. log.critical("Duplicate section '%s'" % (the_section))
  285. sys.exit(1)
  286. except configparser.NoOptionError:
  287. log.critical("'%s' not found in section '%s'" % (the_option, the_section))
  288. sys.exit(1)
  289. # TODO (dan): Finish exceptions.
  290. except configparser.ParsingError:
  291. log.critical("Can't parse file '%s'! (You got me)" % (filename))
  292. sys.exit(1)
  293. # This is only executed if no exceptions were thrown
  294. else:
  295. log.debug('attributes BEFORE = %r' % attributes)
  296. attributes = attributes.splitlines()
  297. log.debug('attributes AFTER = %r' % attributes)
  298. # Strip empty lines
  299. new_attributes = [line for line in attributes if line != '']
  300. log.debug('new_attributes = %s' % new_attributes)
  301. return new_attributes
  302. # Can't make it part of get_attribute... oh well...
  303. # We need someway to check to see if a username exists with out exit(1)
  304. def check_username(config, user_name):
  305. """
  306. Check if a username exists in the config. Pukes if the config doesn't
  307. even have a "users" section.
  308. """
  309. log.debug('check_username(%s)' % locals())
  310. if not config.has_section('users'):
  311. log.critical("users section doesn't exist!")
  312. sys.exit(1)
  313. return config.has_option('users', user_name)
  314. def match_it(the_section, the_option, match_item, config, filename):
  315. """
  316. If match item in our_list, true, else false
  317. Example:
  318. If deny section has a match for 10.1.1.1, return True, else False.
  319. If the section doesn't exist, we assume an implicit deny/false
  320. """
  321. if config.has_option(the_section,the_option):
  322. our_list = get_attribute(config, the_section, the_option, filename)
  323. for item in our_list:
  324. if re.match(item, match_item):
  325. return True
  326. return False
  327. class DoAuthOptionParser(optparse.OptionParser):
  328. """
  329. A custom OptionParser to work with tac_plus post-authorization:
  330. - Always exit 1 on option errors vs. the default of 2.
  331. - Log output to the log file.
  332. """
  333. def error(self, msg):
  334. """Print a usage message using 'msg' to stderr and exit 1."""
  335. # Use the global log if it exists, else instantiate it.
  336. global log
  337. print(log)
  338. if log is None:
  339. log = _setup_logging(filename=self.values.log_file)
  340. log.critical(msg)
  341. self.print_usage(sys.stderr)
  342. self.exit(1, "%s: error: %s\n" % (self.get_prog_name(), msg))
  343. def is_i_before_f(argv, parser):
  344. """
  345. Make sure -i always comes before -f. This is for the CRS workaround.
  346. :param argv:
  347. The argument list passed to the parser
  348. :param parser:
  349. An OptionParser object
  350. """
  351. # Get long/short option names for -f and -l
  352. fopt = parser.get_option('-f')
  353. flags = fopt._short_opts + fopt._long_opts
  354. iopt = parser.get_option('-i')
  355. ilags = iopt._short_opts + iopt._long_opts
  356. # Iterate over the flag names and check their position in argv and make
  357. # sure that -i always comes before -f.
  358. for f, i in product(flags, ilags):
  359. dprint('Checking %s against %s' % (f, i))
  360. if (f in argv and i in argv) and (argv.index(f) < argv.index(i)):
  361. parser.error("%s must be specified after %s in the argument list." % (f, i))
  362. return True
  363. def parse_args(argv=None):
  364. """
  365. Self-explanatory.
  366. :param argv:
  367. The argument list passed to the parser
  368. """
  369. if argv is None:
  370. argv = sys.argv
  371. dprint(argv=argv)
  372. usage = 'usage: %prog -u <username> [-i <ip-addr>] [-d <device>] [-f <config-file>] [-l <log-file>] [-D|--debug]'
  373. desc = 'do_auth is a Python program to work as an authorization script for the ``tac_plus`` TACACS+ daemon to allow greater flexibility in TACACS+ authentication and authorization. For more information on tac_plus please see http://shrubbery.net/tac_plus.'
  374. ver ='%prog ' + __version__
  375. parser = DoAuthOptionParser(usage=usage, description=desc, version=ver)
  376. parser.add_option('-u', '--username', metavar='<username>',
  377. help='(Mandatory) Username. [$user]')
  378. parser.add_option('-i', '--ip-addr', metavar='<ip-addr>',
  379. help="""(Optional) IP address of user. If not specified, all host_ entries are ignored and can be omitted. [$address] (Note: If you use IOS-XR, you MUST add '-fix_crs_bug' after $address due to a bug in IOS-XR)""")
  380. parser.add_option('-d', '--device', metavar='<device>',
  381. help="""(Optional) Device address. If not specified, all device_ entries are ignored and can be omitted. [$name]""")
  382. parser.add_option('-f', '--config-file', metavar='<config-file>',
  383. default=CONFIG, help='Config filename. (default: %s)' %
  384. CONFIG)
  385. parser.add_option('-l', '--log-file', metavar='<log-file>', default=LOG_FILE,
  386. help='Log filename. (default: %s)' % LOG_FILE)
  387. parser.add_option('--docs', action='store_true', default=False,
  388. help='Display usage docs and exit.')
  389. parser.add_option('-D', '--debug', action='store_true', default=False,
  390. help="""Debug mode. Allows you to call the program without reading from stdin. Useful to test your configuration before going live. Sets a default command of "show users wides".""")
  391. opts, args = parser.parse_args()
  392. dprint('\nBefore:', opts=opts, args=args)
  393. if opts.docs:
  394. parser.exit(1, __doc__)
  395. # Make sure username is provided, log, and exit if isn't.
  396. if opts.username is None:
  397. msg = 'Username not provided. Argument -u/--username is required!'
  398. parser.error(msg)
  399. # Make sure -u, -i, -f are all provided, despite being labeled as optional?
  400. #if len(argv) < 7:
  401. # print __doc__
  402. # sys.exit(1)
  403. # Make sure that -i always comes before -f
  404. is_i_before_f(argv, parser)
  405. # Support legacy '-fix_crs_bug' option so it does not conflict with '-f' option
  406. if opts.config_file == 'ix_crs_bug' and opts.ip_addr:
  407. opts.ip_addr = '-fix_crs_bug'
  408. opts.config_file = CONFIG
  409. dprint('\nAfter:', opts=opts, args=args)
  410. return opts, args
  411. def main():
  412. # Defaults
  413. global log # So we can use and modify the global logging object
  414. opts, _args = parse_args()
  415. filename = opts.config_file
  416. log_name = opts.log_file
  417. user_name = opts.username
  418. ip_addr = opts.ip_addr
  419. device = opts.device
  420. is_debug = opts.debug
  421. # DEBUG before we have a logging object.
  422. if is_debug:
  423. print('filename: %r' % filename)
  424. print('log_name: %r' % log_name)
  425. # Define our logging object
  426. log = _setup_logging(filename=log_name)
  427. # DEBUG! We at least got CALLED (and the logger works!)
  428. log.debug('Hello World!')
  429. # Read AV pairs
  430. av_pairs = []
  431. if not is_debug:
  432. for line in sys.stdin:
  433. av_pairs.append(line)
  434. log.debug('AV pairs: %r' % av_pairs)
  435. else:
  436. # Default Debug command is "show users wide"
  437. # Later versions will allow this to be set
  438. av_pairs.append("service=shell\n")
  439. av_pairs.append("cmd=show\n")
  440. av_pairs.append("cmd-arg=users\n")
  441. av_pairs.append("cmd-arg=wide\n")
  442. av_pairs.append("cmd-arg=<cr>\n")
  443. # DEBUG - print av_pairs
  444. for item in av_pairs:
  445. log.debug('AV item: %r' % item)
  446. # Function to make cmd's readable
  447. # Not very good, but will do for now
  448. # I don't use any other service other than shell to test!
  449. the_command = ""
  450. return_pairs = ""
  451. if not len(av_pairs) > 0:
  452. log.info('No av pairs!!')
  453. if device:
  454. log.info('Device:%s' % device)
  455. log.critical('Did you forget "default service = permit" in tac_plus.conf?')
  456. log.critical('Confused - exiting(1)!')
  457. sys.exit(1)
  458. if (av_pairs[0] == "service=shell\n"):
  459. # $**@ Nexus!
  460. if av_pairs[1] == ("cmd=\n"): # #&*@ Nexus!
  461. if len(av_pairs) > 2:
  462. # DEBUG
  463. log.debug('Nexus pairs found')
  464. return_pairs = av_pairs[2:] # strip the "cmd=" for consistency
  465. #
  466. # Commands - Concatenate to a readable command
  467. #
  468. elif av_pairs[1].startswith("cmd="):
  469. our_command = av_pairs[1].split("=")
  470. the_command = our_command[1].strip('\n')
  471. if len(av_pairs) > 2:
  472. i = 2
  473. our_command = av_pairs[i].split("=")
  474. if len(our_command[1]) > 1:
  475. while not (our_command[1] == "<cr>\n"):
  476. the_command = the_command + " " + our_command[1].strip('\n')
  477. i = i + 1
  478. if i == len(av_pairs): # Firewalls don't give a <cr>!!
  479. break
  480. our_command = av_pairs[i].split("=")
  481. while our_command[0] == '\n':
  482. i = i +1
  483. if i == len(av_pairs):
  484. our_command = ['break_loop', "<cr>\n"]
  485. break
  486. our_command = av_pairs[i].split("=")
  487. if len(our_command) == 1:
  488. our_command = ['cmd-arg'] + our_command
  489. # DEBUG - We got the command
  490. log.debug('Got command: %r' % the_command)
  491. #
  492. # Login - Get av_pairs to pass back to tac_plus
  493. #
  494. # (Note: during debugging, you may see AV pairs whose separator
  495. # character is a * instead of a = sign, meaning that the value in a pair
  496. # is optional. An = sign indicates a mandatory value. A * denotes an
  497. # optional value).
  498. elif av_pairs[1].startswith("cmd*"): # Anybody know why it's "cmd*"?
  499. if len(av_pairs) > 2:
  500. return_pairs = av_pairs[2:] # You MUST strip the "cmd*" av-pair
  501. # Definitely not a Nexus, so strip any Nexus pair
  502. for item in return_pairs:
  503. if item.startswith("shell:roles"):
  504. return_pairs.remove(item)
  505. else:
  506. return_pairs = av_pairs
  507. config = configparser.SafeConfigParser()
  508. try:
  509. config.readfp(open(filename))
  510. except (IOError, configparser.ParsingError):
  511. log.critical("Can't open/parse config file: '%s'" % (filename))
  512. sys.exit(1)
  513. log.debug('Got config: %s' % config)
  514. the_section = "users"
  515. # If the user doesn't exist, just use the default settings
  516. # Kind of a hack, but it works because we only get_attribute on user_name once.
  517. # We have the : in there which we can use to split if required
  518. log.debug('Checking username: %s' % user_name)
  519. if not check_username(config, user_name):
  520. log.debug('username not found; searching for default')
  521. user_name = (user_name + ":(default)")
  522. groups = get_attribute(config, "users", "default", filename)
  523. else:
  524. log.debug('username found in config')
  525. groups = get_attribute(config, "users", user_name, filename)
  526. if '_nss' in groups and got_getgrouplist:
  527. log.debug('Got special group _nss and have getgrouplist, importing nss groups')
  528. try:
  529. pwd_user = pwd_getpwnam(user_name)
  530. os_group = os_getgrouplist(user_name, pwd_user[3])
  531. for gid in os_group:
  532. try:
  533. group = grp_getgrgid(gid)
  534. groups.append(group[0])
  535. except KeyError:
  536. # group not found in nss
  537. pass
  538. except KeyError:
  539. log.debug('User not found in NSS')
  540. log.debug('NSS Groups: %s' % (groups))
  541. log.debug('About to check groups')
  542. for this_group in groups:
  543. # Check $address
  544. if ip_addr:
  545. # 'host_deny' attribute
  546. if match_it(this_group, "host_deny", ip_addr, config, filename):
  547. if this_group == groups[-1]:
  548. log.info("User '%s' denied from source '%s' in '%s'->'%s'"
  549. % (user_name, ip_addr, this_group, "host_deny"))
  550. sys.exit(1)
  551. else:
  552. # HUM... afterthought. We need it to continue if more groups exist
  553. continue
  554. # 'host_allow' attribute
  555. if not match_it(this_group, "host_allow", ip_addr, config, filename):
  556. # Stupid IOS-XR bug in which $address is not passed by the
  557. # device. This workaround just gives us a value to check and is
  558. # ignored otherwise.
  559. if ip_addr == "-fix_crs_bug":
  560. pass
  561. elif this_group == groups[-1]:
  562. log.info("User '%s' not allowed from source '%s' in '%s'->'%s'"
  563. % (user_name, ip_addr, this_group, "host_allow"))
  564. sys.exit(1)
  565. else:
  566. continue
  567. # Check $name
  568. if device:
  569. # 'device_deny' attribute
  570. if match_it(this_group, "device_deny", device, config, filename):
  571. if this_group == groups[-1]:
  572. log.info("User '%s' denied access to device '%s' in '%s'->'%s'"
  573. % (user_name, device, this_group, "device_deny"))
  574. sys.exit(1)
  575. else:
  576. continue
  577. # 'device_permit' attribute
  578. if not match_it(this_group, "device_permit", device, config, filename):
  579. if this_group == groups[-1]:
  580. log.info("User '%s' not allowed access to device '%s' in '%s'->'%s'"
  581. % (user_name, device, this_group, "device_permit"))
  582. sys.exit(1)
  583. else:
  584. continue
  585. # Attempt to modify return pairs
  586. log.debug('About to modify return pairs.')
  587. want_tac_pairs = False
  588. if config.has_option(this_group, "av_pairs"):
  589. temp_av_pairs = get_attribute(config, this_group, "av_pairs", filename)
  590. log.debug('temp_av_pairs = %r', temp_av_pairs)
  591. log.debug('return_pairs = %r', return_pairs)
  592. for idx, item in enumerate(return_pairs):
  593. # TODO (jathan): Turn av_pairs into a dict, not a list of
  594. # strings... Write a function to convert back and forth. We
  595. # also need to be able to account for optional pairs that may
  596. # be sent by the device ('*' delimited)
  597. splt = item.split('=')
  598. if len(splt) > 1:
  599. # DEBUG
  600. attr, value = splt
  601. log.debug('%s: %s' % (attr, value))
  602. # TODO (jathan): item, splt, item2? Need better var names...
  603. for item2 in temp_av_pairs:
  604. item2 = item2.strip()
  605. # Pair replacing logic. This is used to convert pairs
  606. # (e.g. priv-lvl,brocade-privlvl=5
  607. # If attribute we're working w/ is whitelisted in
  608. # 'SKIP_CONVERT', then don't try to convert it.
  609. if attr not in SKIP_CONVERT and item2.find(',') > -1:
  610. # => ['priv-lvl', 'brocade-privlvl=5']
  611. # If there's a comma, this means we might want to
  612. # replace the pair.
  613. splt2 = item2.split(',')
  614. if len(splt2) > 1:
  615. if splt[0] == splt2[0]:
  616. want_tac_pairs = True
  617. return_pairs[idx] = splt2[1]
  618. else:
  619. splt2 = item2.split('=')
  620. if len(splt2) > 1:
  621. if splt[0] == splt2[0].strip(): # Strip needed?
  622. want_tac_pairs = True
  623. # DEBUG
  624. pair = '%s=%s' % (splt2[0].strip(), splt2[1].strip())
  625. log.debug("Replacing pairs %s" % pair)
  626. return_pairs[idx] = pair
  627. # Some devices implement TACACS+ so poorly that you shouldn't even TRY to
  628. # mess with them. Like Procurves.
  629. exit_val = '2'
  630. if config.has_option(this_group, "exit_val"):
  631. return_val = get_attribute(config, this_group, "exit_val", filename)
  632. return_val = return_val[0] # more than 1 = they're stupid
  633. exit_val = return_val.strip()
  634. # The previous 4 statements are to deny, it we passed them, proceed
  635. # If we are logging in, return pairs, if not, go no to check the command
  636. # Yes, simply printing them is how you return them
  637. # First, let's make sure we're doing 'service = shell'. If not, just
  638. # allow it. I currently have little knowledge of cmd's sent by other
  639. # services which is why this code is a little kludgy.
  640. log.debug('Return pairs: %s' % return_pairs)
  641. if return_pairs:
  642. splt = av_pairs[0].split('=') # Removed service in return_pairs
  643. if len(splt) > 1:
  644. if not splt[1].strip() == 'shell':
  645. log.info("User '%s' granted non-shell access to device '%s' in group '%s' from '%s'"
  646. % (user_name, device, this_group, ip_addr))
  647. return_pairs = av_pairs[2:] # Cut the first two?
  648. # DEBUG
  649. for item in return_pairs:
  650. log.debug("Returning: %s" % item.strip())
  651. print(item.strip('\n'))
  652. if want_tac_pairs:
  653. log.debug("Exiting status %s" % exit_val)
  654. sys.exit(int(exit_val))
  655. else:
  656. log.debug("Exiting status 0")
  657. sys.exit(0) # Don't even TRY to mess with the tac pairs
  658. else:
  659. log.debug("No return_pairs.")
  660. # Proceed with shell stuff
  661. if not len(the_command) > 0:
  662. log.debug("Proceeding with shell processing.")
  663. for item in return_pairs:
  664. # DEBUG
  665. log.debug("Returning: %s" % item.strip())
  666. print(item.strip('\n'))
  667. log.info("User '%s' granted access to device '%s' in group '%s' from '%s'"
  668. % (user_name, device, this_group, ip_addr))
  669. # DEBUG
  670. log.debug("Exiting status %s" % exit_val)
  671. sys.exit(int(exit_val))
  672. # Check command
  673. else:
  674. if match_it(this_group, "command_deny", the_command, config, filename):
  675. if this_group == groups[-1]:
  676. log.info("User '%s' denied command '%s' to device '%s' in '%s'->'%s'"
  677. % (user_name, the_command, device, this_group, "command_deny"))
  678. sys.exit(1)
  679. else:
  680. continue
  681. elif match_it(this_group, "command_permit", the_command, config, filename):
  682. log.info("User '%s' allowed command '%s' to device '%s' in '%s'->'%s'"
  683. % (user_name, the_command, device, this_group, "command_permit"))
  684. sys.exit(0)
  685. # Exit & log if last group
  686. else:
  687. if this_group == groups[-1]:
  688. log.info("User '%s' not allowed command '%s' to device '%s' in any group"
  689. % (user_name, the_command, device))
  690. #Hum... This only works if it's the last group/only group.
  691. sys.exit(1)
  692. else:
  693. continue
  694. # Implicit deny at the end. This should never happen, but in case it ever
  695. # does, it's not failing silently and you will know! :)
  696. log.info("User '%s' not allowed access to device '%s' from '%s' in any group"
  697. % (user_name, device, ip_addr))
  698. sys.exit(1)
  699. if __name__ == "__main__":
  700. main()