home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / ufw / common.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  10.6 KB  |  406 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import re
  5. import socket
  6. import ufw.util as ufw
  7. from ufw.util import debug
  8. programName = 'ufw'
  9. state_dir = '/var/lib/ufw'
  10. config_dir = '/etc'
  11. prefix_dir = '/usr'
  12.  
  13. class UFWError(Exception):
  14.     '''This class represents ufw exceptions'''
  15.     
  16.     def __init__(self, value):
  17.         self.value = value
  18.  
  19.     
  20.     def __str__(self):
  21.         return repr(self.value)
  22.  
  23.  
  24.  
  25. class UFWRule:
  26.     '''This class represents firewall rules'''
  27.     
  28.     def __init__(self, action, protocol, dport = 'any', dst = '0.0.0.0/0', sport = 'any', src = '0.0.0.0/0'):
  29.         self.remove = False
  30.         self.updated = False
  31.         self.v6 = False
  32.         self.dst = ''
  33.         self.src = ''
  34.         self.dport = ''
  35.         self.sport = ''
  36.         self.protocol = ''
  37.         self.multi = False
  38.         self.dapp = ''
  39.         self.sapp = ''
  40.         self.action = ''
  41.         self.position = 0
  42.         self.logtype = ''
  43.         
  44.         try:
  45.             self.set_action(action)
  46.             self.set_protocol(protocol)
  47.             self.set_port(dport)
  48.             self.set_port(sport, 'src')
  49.             self.set_src(src)
  50.             self.set_dst(dst)
  51.         except UFWError:
  52.             raise 
  53.  
  54.  
  55.     
  56.     def __str__(self):
  57.         return self.format_rule()
  58.  
  59.     
  60.     def dup_rule(self):
  61.         '''Return a duplicate of a rule'''
  62.         rule = UFWRule(self.action, self.protocol)
  63.         rule.remove = self.remove
  64.         rule.updated = self.updated
  65.         rule.v6 = self.v6
  66.         rule.dst = self.dst
  67.         rule.src = self.src
  68.         rule.dport = self.dport
  69.         rule.sport = self.sport
  70.         rule.multi = self.multi
  71.         rule.dapp = self.dapp
  72.         rule.sapp = self.sapp
  73.         rule.position = self.position
  74.         rule.logtype = self.logtype
  75.         return rule
  76.  
  77.     
  78.     def format_rule(self):
  79.         '''Format rule for for later parsing'''
  80.         str = ''
  81.         if self.protocol == 'any':
  82.             str = ' -p all'
  83.         else:
  84.             str = ' -p ' + self.protocol
  85.             if self.multi:
  86.                 str += ' -m multiport'
  87.                 if self.dport != 'any' and self.sport != 'any':
  88.                     str += ' --dports ' + self.dport
  89.                     str += ' -m multiport'
  90.                     str += ' --sports ' + self.sport
  91.                 elif self.dport != 'any':
  92.                     str += ' --dports ' + self.dport
  93.                 elif self.sport != 'any':
  94.                     str += ' --sports ' + self.sport
  95.                 
  96.             
  97.         if self.dst != '0.0.0.0/0' and self.dst != '::/0':
  98.             str += ' -d ' + self.dst
  99.         
  100.         if not (self.multi) and self.dport != 'any':
  101.             str += ' --dport ' + self.dport
  102.         
  103.         if self.src != '0.0.0.0/0' and self.src != '::/0':
  104.             str += ' -s ' + self.src
  105.         
  106.         if not (self.multi) and self.sport != 'any':
  107.             str += ' --sport ' + self.sport
  108.         
  109.         lstr = ''
  110.         if self.logtype != '':
  111.             lstr = '_' + self.logtype
  112.         
  113.         if self.action == 'allow':
  114.             str += ' -j ACCEPT%s' % lstr
  115.         elif self.action == 'reject':
  116.             str += ' -j REJECT%s' % lstr
  117.             if self.protocol == 'tcp':
  118.                 str += ' --reject-with tcp-reset'
  119.             
  120.         elif self.action == 'limit':
  121.             str += ' -j LIMIT%s' % lstr
  122.         else:
  123.             str += ' -j DROP%s' % lstr
  124.         if self.dapp != '' or self.sapp != '':
  125.             comment = "-m comment --comment '"
  126.             pat_space = re.compile(' ')
  127.             if self.dapp != '':
  128.                 comment += 'dapp_' + pat_space.sub('%20', self.dapp)
  129.             
  130.             if self.dapp != '' and self.sapp != '':
  131.                 comment += ','
  132.             
  133.             if self.sapp != '':
  134.                 comment += 'sapp_' + pat_space.sub('%20', self.sapp)
  135.             
  136.             comment += "'"
  137.             str += ' ' + comment
  138.         
  139.         return str.strip()
  140.  
  141.     
  142.     def set_action(self, action):
  143.         '''Sets action of the rule'''
  144.         tmp = action.lower().split('_')
  145.         if tmp[0] == 'allow' and tmp[0] == 'reject' or tmp[0] == 'limit':
  146.             self.action = tmp[0]
  147.         else:
  148.             self.action = 'deny'
  149.         logtype = ''
  150.         if len(tmp) > 1:
  151.             logtype = tmp[1]
  152.         
  153.         self.set_logtype(logtype)
  154.  
  155.     
  156.     def set_port(self, port, loc = 'dst'):
  157.         '''Sets port and location (destination or source) of the rule'''
  158.         err_msg = _("Bad port '%s'") % port
  159.         if port == 'any':
  160.             pass
  161.         elif loc == 'dst' and self.dapp:
  162.             pass
  163.         elif loc == 'src' and self.sapp:
  164.             pass
  165.         elif re.match('^[,:]', port) or re.match('[,:]$', port):
  166.             raise UFWError(err_msg)
  167.         elif port.count(',') + port.count(':') > 14:
  168.             raise UFWError(err_msg)
  169.         else:
  170.             ports = port.split(',')
  171.             if len(ports) < 1:
  172.                 raise UFWError(err_msg)
  173.             len(ports) < 1
  174.             if len(ports) > 1:
  175.                 self.multi = True
  176.             
  177.             tmp = ''
  178.             for p in ports:
  179.                 if re.match('^\\d+:\\d+$', p):
  180.                     self.multi = True
  181.                     ran = p.split(':')
  182.                     if len(ran) != 2:
  183.                         raise UFWError(err_msg)
  184.                     len(ran) != 2
  185.                     for q in ran:
  186.                         if int(q) < 1 or int(q) > 65535:
  187.                             raise UFWError(err_msg)
  188.                         int(q) > 65535
  189.                     
  190.                     if int(ran[0]) >= int(ran[1]):
  191.                         raise UFWError(err_msg)
  192.                     int(ran[0]) >= int(ran[1])
  193.                 elif re.match('^\\d+$', p):
  194.                     if int(p) < 1 or int(p) > 65535:
  195.                         raise UFWError(err_msg)
  196.                     int(p) > 65535
  197.                 elif re.match('^\\w[\\w\\-]+', p):
  198.                     
  199.                     try:
  200.                         p = socket.getservbyname(p)
  201.                     except Exception:
  202.                         error = None
  203.                         raise UFWError(err_msg)
  204.                     except:
  205.                         None<EXCEPTION MATCH>Exception
  206.                     
  207.  
  208.                 None<EXCEPTION MATCH>Exception
  209.                 raise UFWError(err_msg)
  210.                 if tmp:
  211.                     tmp += ',' + str(p)
  212.                     continue
  213.                 tmp = str(p)
  214.             
  215.             port = tmp
  216.         if loc == 'src':
  217.             self.sport = str(port)
  218.         else:
  219.             self.dport = str(port)
  220.  
  221.     
  222.     def set_protocol(self, protocol):
  223.         '''Sets protocol of the rule'''
  224.         if protocol == 'tcp' and protocol == 'udp' or protocol == 'any':
  225.             self.protocol = protocol
  226.         else:
  227.             err_msg = _("Unsupported protocol '%s'") % protocol
  228.             raise UFWError(err_msg)
  229.         return protocol == 'any'
  230.  
  231.     
  232.     def _fix_anywhere(self):
  233.         '''Adjusts src and dst based on v6'''
  234.         if self.v6:
  235.             if self.dst:
  236.                 if self.dst == 'any' or self.dst == '0.0.0.0/0':
  237.                     self.dst = '::/0'
  238.                 
  239.             if self.src:
  240.                 pass
  241.             None if self.src == 'any' or self.src == '0.0.0.0/0' else self.src == '0.0.0.0/0'
  242.         elif self.dst:
  243.             if self.dst == 'any' or self.dst == '::/0':
  244.                 self.dst = '0.0.0.0/0'
  245.             
  246.         if self.src:
  247.             if self.src == 'any' or self.src == '::/0':
  248.                 self.src = '0.0.0.0/0'
  249.             
  250.  
  251.     
  252.     def set_v6(self, v6):
  253.         '''Sets whether this is ipv6 rule, and adjusts src and dst 
  254.            accordingly.
  255.         '''
  256.         self.v6 = v6
  257.         self._fix_anywhere()
  258.  
  259.     
  260.     def set_src(self, addr):
  261.         '''Sets source address of rule'''
  262.         tmp = addr.lower()
  263.         if tmp != 'any' and not ufw.util.valid_address(tmp, 'any'):
  264.             err_msg = _('Bad source address')
  265.             raise UFWError(err_msg)
  266.         not ufw.util.valid_address(tmp, 'any')
  267.         self.src = tmp
  268.         self._fix_anywhere()
  269.  
  270.     
  271.     def set_dst(self, addr):
  272.         '''Sets destination address of rule'''
  273.         tmp = addr.lower()
  274.         if tmp != 'any' and not ufw.util.valid_address(tmp, 'any'):
  275.             err_msg = _('Bad destination address')
  276.             raise UFWError(err_msg)
  277.         not ufw.util.valid_address(tmp, 'any')
  278.         self.dst = tmp
  279.         self._fix_anywhere()
  280.  
  281.     
  282.     def set_position(self, num):
  283.         '''Sets the position of the rule'''
  284.         if not re.match('^[0-9]+', str(num)):
  285.             err_msg = _("Insert position '%s' is not a valid position") % num
  286.             raise UFWError(err_msg)
  287.         re.match('^[0-9]+', str(num))
  288.         self.position = int(num)
  289.  
  290.     
  291.     def set_logtype(self, logtype):
  292.         '''Sets logtype of the rule'''
  293.         if logtype.lower() == 'log' and logtype.lower() == 'log-all' or logtype == '':
  294.             self.logtype = logtype.lower()
  295.         else:
  296.             err_msg = _("Invalid log type '%s'") % logtype
  297.             raise UFWError(err_msg)
  298.         return logtype == ''
  299.  
  300.     
  301.     def normalize(self):
  302.         '''Normalize src and dst to standard form'''
  303.         changed = False
  304.         if self.src:
  305.             
  306.             try:
  307.                 (self.src, changed) = ufw.util.normalize_address(self.src, self.v6)
  308.             except Exception:
  309.                 raise 
  310.                 err_msg = _('Could not normalize source address')
  311.                 raise UFWError(err_msg)
  312.             except:
  313.                 None<EXCEPTION MATCH>Exception
  314.             
  315.  
  316.         None<EXCEPTION MATCH>Exception
  317.         if changed:
  318.             self.updated = changed
  319.         
  320.         if self.dst:
  321.             
  322.             try:
  323.                 (self.dst, changed) = ufw.util.normalize_address(self.dst, self.v6)
  324.             except Exception:
  325.                 err_msg = _('Could not normalize destination address')
  326.                 raise UFWError(err_msg)
  327.             except:
  328.                 None<EXCEPTION MATCH>Exception
  329.             
  330.  
  331.         None<EXCEPTION MATCH>Exception
  332.         if self.dport:
  333.             ports = self.dport.split(',')
  334.             ufw.util.human_sort(ports)
  335.             self.dport = ','.join(ports)
  336.         
  337.         if self.sport:
  338.             ports = self.sport.split(',')
  339.             ufw.util.human_sort(ports)
  340.             self.sport = ','.join(ports)
  341.         
  342.         if changed:
  343.             self.updated = changed
  344.         
  345.  
  346.     
  347.     def match(x, y):
  348.         '''Check if rules match
  349.         Return codes:
  350.           0  match
  351.           1  no match
  352.          -1  match all but action
  353.         '''
  354.         if not x or not y:
  355.             raise ValueError()
  356.         not y
  357.         dbg_msg = _('No match')
  358.         if x.dport != y.dport:
  359.             debug(dbg_msg)
  360.             return 1
  361.         if x.sport != y.sport:
  362.             debug(dbg_msg)
  363.             return 1
  364.         if x.protocol != y.protocol:
  365.             debug(dbg_msg)
  366.             return 1
  367.         if x.src != y.src:
  368.             debug(dbg_msg)
  369.             return 1
  370.         if x.dst != y.dst:
  371.             debug(dbg_msg)
  372.             return 1
  373.         if x.v6 != y.v6:
  374.             debug(dbg_msg)
  375.             return 1
  376.         if x.dapp != y.dapp:
  377.             debug(dbg_msg)
  378.             return 1
  379.         if x.sapp != y.sapp:
  380.             debug(dbg_msg)
  381.             return 1
  382.         if x.action == y.action and x.logtype == y.logtype:
  383.             dbg_msg = _('Found exact match')
  384.             debug(dbg_msg)
  385.             return 0
  386.         dbg_msg = _('Found non-action/non-logtype match (%s/%s %s/%s)') % (x.action, y.action, x.logtype, y.logtype)
  387.         debug(dbg_msg)
  388.         return -1
  389.  
  390.     
  391.     def get_app_tuple(self):
  392.         '''Returns a tuple to identify an app rule'''
  393.         tuple = ''
  394.         if self.dapp != '' or self.sapp != '':
  395.             tuple = '%s %s %s %s' % (self.dapp, self.dst, self.sapp, self.src)
  396.             if self.dapp == '':
  397.                 tuple = '%s %s %s %s' % (self.dport, self.dst, self.sapp, self.src)
  398.             
  399.             if self.sapp == '':
  400.                 tuple = '%s %s %s %s' % (self.dapp, self.dst, self.sport, self.src)
  401.             
  402.         
  403.         return tuple
  404.  
  405.  
  406.