Revision 7ebd876f lib/utils/text.py

b/lib/utils/text.py
40 40
#: MAC checker regexp
41 41
_MAC_CHECK_RE = re.compile("^([0-9a-f]{2}:){5}[0-9a-f]{2}$", re.I)
42 42

  
43
#: Shell param checker regexp
44
_SHELLPARAM_REGEX = re.compile(r"^[-a-zA-Z0-9._+/:%@]+$")
45

  
43 46

  
44 47
def MatchNameComponent(key, name_list, case_sensitive=True):
45 48
  """Try to match a name against a list.
......
442 445
    self.flush()
443 446
    if self._buffer:
444 447
      self._line_fn(self._buffer)
448

  
449

  
450
def IsValidShellParam(word):
451
  """Verifies is the given word is safe from the shell's p.o.v.
452

  
453
  This means that we can pass this to a command via the shell and be
454
  sure that it doesn't alter the command line and is passed as such to
455
  the actual command.
456

  
457
  Note that we are overly restrictive here, in order to be on the safe
458
  side.
459

  
460
  @type word: str
461
  @param word: the word to check
462
  @rtype: boolean
463
  @return: True if the word is 'safe'
464

  
465
  """
466
  return bool(_SHELLPARAM_REGEX.match(word))
467

  
468

  
469
def BuildShellCmd(template, *args):
470
  """Build a safe shell command line from the given arguments.
471

  
472
  This function will check all arguments in the args list so that they
473
  are valid shell parameters (i.e. they don't contain shell
474
  metacharacters). If everything is ok, it will return the result of
475
  template % args.
476

  
477
  @type template: str
478
  @param template: the string holding the template for the
479
      string formatting
480
  @rtype: str
481
  @return: the expanded command line
482

  
483
  """
484
  for word in args:
485
    if not IsValidShellParam(word):
486
      raise errors.ProgrammerError("Shell argument '%s' contains"
487
                                   " invalid characters" % word)
488
  return template % args

Also available in: Unified diff