home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / ufw / util.py < prev   
Encoding:
Python Source  |  2009-03-18  |  12.8 KB  |  526 lines

  1. #
  2. # util.py: utility functions for ufw
  3. #
  4. # Copyright (C) 2008-2009 Canonical Ltd.
  5. #
  6. #    This program is free software: you can redistribute it and/or modify
  7. #    it under the terms of the GNU General Public License version 3,
  8. #    as published by the Free Software Foundation.
  9. #
  10. #    This program is distributed in the hope that it will be useful,
  11. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #    GNU General Public License for more details.
  14. #
  15. #    You should have received a copy of the GNU General Public License
  16. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  17. #
  18.  
  19. import errno
  20. import os
  21. import re
  22. import shutil
  23. import socket
  24. import struct
  25. import subprocess
  26. import sys
  27. from tempfile import mkstemp
  28.  
  29. debugging = False
  30.  
  31.  
  32. def get_services_proto(port):
  33.     '''Get the protocol for a specified port from /etc/services'''
  34.     proto = ""
  35.     try:
  36.         socket.getservbyname(port)
  37.     except Exception:
  38.         raise
  39.  
  40.     try:
  41.         socket.getservbyname(port, "tcp")
  42.         proto = "tcp"
  43.     except Exception:
  44.         pass
  45.  
  46.     try:
  47.         socket.getservbyname(port, "udp")
  48.         if proto == "tcp":
  49.             proto = "any"
  50.         else:
  51.             proto = "udp"
  52.     except Exception:
  53.         pass
  54.  
  55.     return proto
  56.  
  57.  
  58. def parse_port_proto(str):
  59.     '''Parse port or port and protocol'''
  60.     port = ""
  61.     proto = ""
  62.     tmp = str.split('/')
  63.     if len(tmp) == 1:
  64.         port = tmp[0]
  65.         proto = "any"
  66.     elif len(tmp) == 2:
  67.         port = tmp[0]
  68.         proto = tmp[1]
  69.     else:
  70.         raise ValueError
  71.     return (port, proto)
  72.  
  73.  
  74. def valid_address6(addr):
  75.     '''Verifies if valid IPv6 address'''
  76.     if not socket.has_ipv6:
  77.         warn("python does not have IPv6 support.")
  78.         return False
  79.  
  80.     # quick and dirty test
  81.     if len(addr) > 43 or not re.match(r'^[a-fA-F0-9:\./]+$', addr):
  82.         return False
  83.  
  84.     net = addr.split('/')
  85.     try:
  86.         socket.inet_pton(socket.AF_INET6, net[0])
  87.     except Exception:
  88.         return False
  89.  
  90.     if len(net) > 2:
  91.         return False
  92.     elif len(net) == 2:
  93.         # Check netmask specified via '/'
  94.         if not _valid_cidr_netmask(net[1], True):
  95.             return False
  96.  
  97.     return True
  98.  
  99.  
  100. def valid_address4(addr):
  101.     '''Verifies if valid IPv4 address'''
  102.     # quick and dirty test
  103.     if len(addr) > 31 or not re.match(r'^[0-9\./]+$', addr):
  104.         return False
  105.  
  106.     net = addr.split('/')
  107.     try:
  108.         socket.inet_pton(socket.AF_INET, net[0])
  109.         if not _valid_dotted_quads(net[0], False):
  110.             return False
  111.     except Exception:
  112.         return False
  113.  
  114.     if len(net) > 2:
  115.         return False
  116.     elif len(net) == 2:
  117.         # Check netmask specified via '/'
  118.         if not valid_netmask(net[1], False):
  119.             return False
  120.  
  121.     return True
  122.  
  123.  
  124. def valid_netmask(nm, v6):
  125.     '''Verifies if valid cidr or dotted netmask'''
  126.     return _valid_cidr_netmask(nm, v6) or _valid_dotted_quads(nm, v6)
  127.  
  128.  
  129. #
  130. # valid_address()
  131. #    version="6" tests if a valid IPv6 address
  132. #    version="4" tests if a valid IPv4 address
  133. #    version="any" tests if a valid IP address (IPv4 or IPv6)
  134. #
  135. def valid_address(addr, version="any"):
  136.     '''Validate IP addresses'''
  137.     if version == "6":
  138.         return valid_address6(addr)
  139.     elif version == "4":
  140.         return valid_address4(addr)
  141.     elif version == "any":
  142.         return valid_address4(addr) or valid_address6(addr)
  143.  
  144.     raise ValueError
  145.  
  146.  
  147. def normalize_address(orig, v6):
  148.     '''Convert address to standard form. Use no netmask for IP addresses. If
  149.        If netmask is specified and not all 1's, for IPv4 use cidr if possible, 
  150.        otherwise dotted netmask and for IPv6, use cidr.
  151.     '''
  152.     net = []
  153.     changed = False
  154.     version = "4"
  155.     if v6:
  156.         version = "6"
  157.  
  158.     if '/' in orig:
  159.         net = orig.split('/')
  160.         # Remove host netmasks
  161.         if v6 and net[1] == "128":
  162.             del net[1]
  163.         elif not v6:
  164.             if net[1] == "32" or net[1] == "255.255.255.255":
  165.                 del net[1]
  166.     else:
  167.         net.append(orig)
  168.  
  169.     if not v6 and len(net) == 2 and _valid_dotted_quads(net[1], v6):
  170.         try:
  171.             net[1] = _dotted_netmask_to_cidr(net[1], v6)
  172.         except Exception:
  173.             # Not valid cidr, so just use the dotted quads
  174.             pass
  175.  
  176.     addr = net[0]
  177.     if len(net) == 2:
  178.         addr += "/" + net[1]
  179.         if not v6:
  180.             network = _address4_to_network(addr)
  181.             if network != addr:
  182.                 dbg_msg = "Using '%s' for address '%s'" % (network, addr)
  183.                 debug(dbg_msg)
  184.                 addr = network
  185.                 changed = True
  186.  
  187.     if not valid_address(addr, version):
  188.         dbg_msg = "Invalid address '%s'" % (addr)
  189.         debug(dbg_msg)
  190.         raise ValueError
  191.  
  192.     return (addr, changed)
  193.  
  194.  
  195. def open_file_read(f):
  196.     '''Opens the specified file read-only'''
  197.     try:
  198.         orig = open(f, 'r')
  199.     except Exception:
  200.         raise
  201.  
  202.     return orig
  203.  
  204.  
  205. def open_files(f):
  206.     '''Opens the specified file read-only and a tempfile read-write.'''
  207.     try:
  208.         orig = open_file_read(f)
  209.     except Exception:
  210.         raise
  211.  
  212.     try:
  213.         (tmp, tmpname) = mkstemp()
  214.     except Exception:
  215.         orig.close()
  216.         raise
  217.  
  218.     return { "orig": orig, "origname": f, "tmp": tmp, "tmpname": tmpname }
  219.  
  220.  
  221. def close_files(fns, update = True):
  222.     '''Closes the specified files (as returned by open_files), and update
  223.        original file with the temporary file.
  224.     '''
  225.     fns['orig'].close()
  226.     os.close(fns['tmp'])
  227.  
  228.     if update:
  229.         try:
  230.             shutil.copystat(fns['origname'], fns['tmpname'])
  231.             shutil.copy(fns['tmpname'], fns['origname'])
  232.         except Exception:
  233.             raise
  234.  
  235.     try:
  236.         os.unlink(fns['tmpname'])
  237.     except OSError, e:
  238.         raise
  239.  
  240.  
  241. def cmd(command):
  242.     '''Try to execute the given command.'''
  243.     debug(command)
  244.     try:
  245.         sp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  246.     except OSError, e:
  247.         return [127, str(e)]
  248.  
  249.     out = sp.communicate()[0]
  250.     return [sp.returncode,out]
  251.  
  252.  
  253. def cmd_pipe(command1, command2):
  254.     '''Try to pipe command1 into command2.'''
  255.     try:
  256.         sp1 = subprocess.Popen(command1, stdout=subprocess.PIPE)
  257.         sp2 = subprocess.Popen(command2, stdin=sp1.stdout)
  258.     except OSError, e:
  259.         return [127, str(e)]
  260.  
  261.     out = sp2.communicate()[0]
  262.     return [sp2.returncode,out]
  263.  
  264.  
  265. def error(msg, exit=True):
  266.     '''Print error message and exit'''
  267.     try:
  268.         print >> sys.stderr, "ERROR: %s" % (msg)
  269.     except IOError:
  270.         pass
  271.  
  272.     if exit:
  273.         sys.exit(1)
  274.  
  275.  
  276. def warn(msg):
  277.     '''Print warning message'''
  278.     try:
  279.         print >> sys.stderr, "WARN: %s" % (msg)
  280.     except IOError:
  281.         pass
  282.  
  283.  
  284. def msg(msg, output=sys.stdout):
  285.     '''Print message'''
  286.     try:
  287.         print >> output, "%s" % (msg)
  288.     except IOError:
  289.         pass
  290.  
  291.  
  292. def debug(msg):
  293.     '''Print debug message'''
  294.     if debugging:
  295.         try:
  296.             print >> sys.stderr, "DEBUG: %s" % (msg)
  297.         except IOError:
  298.             pass
  299.  
  300.  
  301. def word_wrap(text, width):
  302.     '''
  303.     A word-wrap function that preserves existing line breaks
  304.     and most spaces in the text. Expects that existing line
  305.     breaks are posix newlines (\n).
  306.     '''
  307.     return reduce(lambda line, word, width=width: '%s%s%s' %
  308.                   (line,
  309.                    ' \n'[(len(line)-line.rfind('\n')-1
  310.                          + len(word.split('\n',1)[0]
  311.                               ) >= width)],
  312.                    word),
  313.                   text.split(' ')
  314.                  )
  315.  
  316.  
  317. def wrap_text(text):
  318.     '''Word wrap to a specific width'''
  319.     return word_wrap(text, 75)
  320.  
  321.  
  322. def human_sort(list):
  323.     '''Sorts list of strings into numeric order, with text case-insensitive.
  324.        Modifies list in place.
  325.  
  326.        Eg:
  327.        [ '80', 'a222', 'a32', 'a2', 'b1', '443', 'telnet', '3', 'http', 'ZZZ']
  328.  
  329.        sorts to:
  330.        ['3', '80', '443', 'a2', 'a32', 'a222', 'b1', 'http', 'telnet', 'ZZZ']
  331.     '''
  332.     norm = lambda t: int(t) if t.isdigit() else t.lower()
  333.     list.sort(key=lambda k: [ norm(c) for c in re.split('([0-9]+)', k)])
  334.  
  335.  
  336. def get_ppid(p=os.getpid()):
  337.     '''Finds parent process id for pid based on /proc/<pid>/stat. See
  338.        'man 5 proc' for details.
  339.     '''
  340.     try:
  341.         pid = int(p)
  342.     except:
  343.         raise ValueError("pid must be an integer")
  344.  
  345.     name = os.path.join("/proc", str(pid), "stat")
  346.     if not os.path.isfile(name):
  347.         raise IOError("Couldn't find '%s'" % (name))
  348.  
  349.     try:
  350.         ppid = file(name).readlines()[0].split()[3]
  351.     except Exception:
  352.         raise
  353.  
  354.     return int(ppid)
  355.  
  356.  
  357. def under_ssh(pid=os.getpid()):
  358.     '''Determine if current process is running under ssh'''
  359.     try:
  360.         ppid = get_ppid(pid)
  361.     except IOError, e:
  362.         warn_msg = _("Couldn't find pid (is /proc mounted?)")
  363.         warn(warn_msg)
  364.         return False
  365.     except Exception:
  366.         err_msg = _("Couldn't find parent pid for '%s'") % (str(pid))
  367.         raise ValueError(err_msg)
  368.  
  369.     # pid '1' is 'init' and '0' is the kernel. This should still work when
  370.     # pid randomization is in use, but needs to be checked.
  371.     if pid == 1 or ppid <= 1:
  372.         return False
  373.  
  374.     path = os.path.join("/proc", str(ppid), "stat")
  375.     if not os.path.isfile(path):
  376.         err_msg = _("Couldn't find '%s'") % (path)
  377.         raise ValueError(err_msg)
  378.  
  379.     try:
  380.         exe = file(path).readlines()[0].split()[1]
  381.     except:
  382.         err_msg = _("Could not find executable for '%s'") % (path)
  383.         raise ValueError(err_msg)
  384.     debug("under_ssh: exe is '%s'" % (exe))
  385.  
  386.     if exe == "(sshd)":
  387.         return True
  388.     else:
  389.         return under_ssh(ppid)
  390.  
  391.  
  392. #
  393. # Internal helper functions
  394. #
  395. def _valid_cidr_netmask(nm, v6):
  396.     '''Verifies cidr netmasks'''
  397.     num = 32
  398.     if v6:
  399.         num = 128
  400.  
  401.     if not re.match(r'^[0-9]+$', nm) or int(nm) < 0 or int(nm) > num:
  402.         return False
  403.  
  404.     return True
  405.  
  406.  
  407. def _valid_dotted_quads(nm, v6):
  408.     '''Verifies dotted quad ip addresses and netmasks'''
  409.     if v6:
  410.         return False
  411.     else:
  412.         if re.match(r'^[0-9]+\.[0-9\.]+$', nm):
  413.             quads = re.split('\.', nm)
  414.             if len(quads) != 4:
  415.                 return False
  416.             for q in quads:
  417.                 if not q or int(q) < 0 or int(q) > 255:
  418.                     return False
  419.         else:
  420.             return False
  421.  
  422.     return True
  423.  
  424. #
  425. # _dotted_netmask_to_cidr()
  426. # Returns:
  427. #   cidr integer (0-32 for ipv4 and 0-128 for ipv6)
  428. #
  429. # Raises exception if cidr cannot be found
  430. #
  431. def _dotted_netmask_to_cidr(nm, v6):
  432.     '''Convert netmask to cidr. IPv6 dotted netmasks are not supported.'''
  433.     cidr = ""
  434.     if v6:
  435.         raise ValueError
  436.     else:
  437.         if not _valid_dotted_quads(nm, v6):
  438.             raise ValueError
  439.  
  440.         mbits = 0
  441.         bits = long(struct.unpack('>L',socket.inet_aton(nm))[0])
  442.         found_one = False
  443.         for n in range(32):
  444.             if (bits >> n) & 1 == 1:
  445.                 found_one = True
  446.             else:
  447.                 if found_one:
  448.                     mbits = -1
  449.                     break
  450.                 else:
  451.                     mbits += 1
  452.  
  453.         if mbits >= 0 and mbits <= 32:
  454.             cidr = str(32 - mbits)
  455.  
  456.     if not _valid_cidr_netmask(cidr, v6):
  457.         raise ValueError
  458.  
  459.     return cidr
  460.  
  461.  
  462. #
  463. # _cidr_to_dotted_netmask()
  464. # Returns:
  465. #   dotted netmask string
  466. #
  467. # Raises exception if dotted netmask cannot be found
  468. #
  469. def _cidr_to_dotted_netmask(cidr, v6):
  470.     '''Convert cidr to netmask. IPv6 dotted netmasks not supported.'''
  471.     nm = ""
  472.     if v6:
  473.         raise ValueError
  474.     else:
  475.         if not _valid_cidr_netmask(cidr, v6):
  476.             raise ValueError
  477.         bits = 0L
  478.         for n in range(32):
  479.             if n < int(cidr):
  480.                 bits |= 1<<31 - n
  481.         nm = socket.inet_ntoa(struct.pack('>L', bits))
  482.  
  483.     if not _valid_dotted_quads(nm, v6):
  484.         raise ValueError
  485.  
  486.     return nm
  487.  
  488. def _address4_to_network(addr):
  489.     '''Convert an IPv4 address and netmask to a network address'''
  490.     if '/' not in addr:
  491.         debug("_address4_to_network: skipping address without a netmask")
  492.         return addr
  493.  
  494.     tmp = addr.split('/')
  495.     if len(tmp) != 2 or not _valid_dotted_quads(tmp[0], False):
  496.         raise ValueError
  497.  
  498.     host = tmp[0]
  499.     orig_nm = tmp[1]
  500.  
  501.     nm = orig_nm
  502.     if _valid_cidr_netmask(nm, False):
  503.         try:
  504.             nm = _cidr_to_dotted_netmask(nm, False)
  505.         except Exception:
  506.             raise
  507.  
  508.     # Now have dotted quad host and nm, find the network
  509.     host_bits = long(struct.unpack('>L',socket.inet_aton(host))[0])
  510.     nm_bits = long(struct.unpack('>L',socket.inet_aton(nm))[0])
  511.  
  512.     network_bits = host_bits & nm_bits
  513.     network = socket.inet_ntoa(struct.pack('>L', network_bits))
  514.  
  515.     return network + "/" + orig_nm
  516.  
  517. def get_iptables_version():
  518.     '''Return iptables version'''
  519.     exe = 'iptables'
  520.     (rc, out) = cmd([exe, '-V'])
  521.     if rc != 0:
  522.         raise OSError(errno.ENOENT, "Error running '%s'" % (exe))
  523.     tmp = re.split('\s', out)
  524.     return re.sub('^v', '', tmp[1])
  525.  
  526.