Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 42d49574

History | View | Annotate | Download (9.6 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 ebcd61bb Iustin Pop
# Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Module encapsulating ssh functionality.
23 a8083063 Iustin Pop

24 a8083063 Iustin Pop
"""
25 a8083063 Iustin Pop
26 a8083063 Iustin Pop
27 a8083063 Iustin Pop
import os
28 9c034cbe Iustin Pop
import logging
29 33993ab8 René Nussbaumer
import re
30 a8083063 Iustin Pop
31 a8083063 Iustin Pop
from ganeti import utils
32 a8083063 Iustin Pop
from ganeti import errors
33 82122173 Iustin Pop
from ganeti import constants
34 8062638d Manuel Franceschini
from ganeti import netutils
35 8fd1bfa9 Michael Hanselmann
from ganeti import pathutils
36 cffbbae7 Michael Hanselmann
from ganeti import vcluster
37 82122173 Iustin Pop
38 82122173 Iustin Pop
39 33993ab8 René Nussbaumer
def FormatParamikoFingerprint(fingerprint):
40 697a3d61 Manuel Franceschini
  """Format paramiko PKey fingerprint.
41 33993ab8 René Nussbaumer

42 33993ab8 René Nussbaumer
  @type fingerprint: str
43 33993ab8 René Nussbaumer
  @param fingerprint: PKey fingerprint
44 697a3d61 Manuel Franceschini
  @return: The string hex representation of the fingerprint
45 33993ab8 René Nussbaumer

46 33993ab8 René Nussbaumer
  """
47 33993ab8 René Nussbaumer
  assert len(fingerprint) % 2 == 0
48 33993ab8 René Nussbaumer
  return ":".join(re.findall(r"..", fingerprint.lower()))
49 33993ab8 René Nussbaumer
50 33993ab8 René Nussbaumer
51 8a3c9e8a Michael Hanselmann
def GetUserFiles(user, mkdir=False, kind=constants.SSHK_DSA,
52 d12b9f66 Michael Hanselmann
                 _homedir_fn=None):
53 8a3c9e8a Michael Hanselmann
  """Return the paths of a user's SSH files.
54 8a3c9e8a Michael Hanselmann

55 8a3c9e8a Michael Hanselmann
  @type user: string
56 8a3c9e8a Michael Hanselmann
  @param user: Username
57 8a3c9e8a Michael Hanselmann
  @type mkdir: bool
58 8a3c9e8a Michael Hanselmann
  @param mkdir: Whether to create ".ssh" directory if it doesn't exist
59 8a3c9e8a Michael Hanselmann
  @type kind: string
60 8a3c9e8a Michael Hanselmann
  @param kind: One of L{constants.SSHK_ALL}
61 8a3c9e8a Michael Hanselmann
  @rtype: tuple; (string, string, string)
62 8a3c9e8a Michael Hanselmann
  @return: Tuple containing three file system paths; the private SSH key file,
63 8a3c9e8a Michael Hanselmann
    the public SSH key file and the user's C{authorized_keys} file
64 8a3c9e8a Michael Hanselmann
  @raise errors.OpExecError: When home directory of the user can not be
65 8a3c9e8a Michael Hanselmann
    determined
66 8a3c9e8a Michael Hanselmann
  @raise errors.OpExecError: Regardless of the C{mkdir} parameters, this
67 8a3c9e8a Michael Hanselmann
    exception is raised if C{~$user/.ssh} is not a directory
68 70d9e3d8 Iustin Pop

69 70d9e3d8 Iustin Pop
  """
70 d12b9f66 Michael Hanselmann
  if _homedir_fn is None:
71 d12b9f66 Michael Hanselmann
    _homedir_fn = utils.GetHomeDir
72 d12b9f66 Michael Hanselmann
73 8a3c9e8a Michael Hanselmann
  user_dir = _homedir_fn(user)
74 70d9e3d8 Iustin Pop
  if not user_dir:
75 8a3c9e8a Michael Hanselmann
    raise errors.OpExecError("Cannot resolve home of user '%s'" % user)
76 8a3c9e8a Michael Hanselmann
77 8a3c9e8a Michael Hanselmann
  if kind == constants.SSHK_DSA:
78 8a3c9e8a Michael Hanselmann
    suffix = "dsa"
79 8a3c9e8a Michael Hanselmann
  elif kind == constants.SSHK_RSA:
80 8a3c9e8a Michael Hanselmann
    suffix = "rsa"
81 8a3c9e8a Michael Hanselmann
  else:
82 8a3c9e8a Michael Hanselmann
    raise errors.ProgrammerError("Unknown SSH key kind '%s'" % kind)
83 70d9e3d8 Iustin Pop
84 c4feafe8 Iustin Pop
  ssh_dir = utils.PathJoin(user_dir, ".ssh")
85 5bae14d9 Guido Trotter
  if mkdir:
86 5bae14d9 Guido Trotter
    utils.EnsureDirs([(ssh_dir, constants.SECURE_DIR_MODE)])
87 70d9e3d8 Iustin Pop
  elif not os.path.isdir(ssh_dir):
88 898a6d45 Michael Hanselmann
    raise errors.OpExecError("Path %s is not a directory" % ssh_dir)
89 70d9e3d8 Iustin Pop
90 c4feafe8 Iustin Pop
  return [utils.PathJoin(ssh_dir, base)
91 8a3c9e8a Michael Hanselmann
          for base in ["id_%s" % suffix, "id_%s.pub" % suffix,
92 8a3c9e8a Michael Hanselmann
                       "authorized_keys"]]
93 70d9e3d8 Iustin Pop
94 70d9e3d8 Iustin Pop
95 c92b310a Michael Hanselmann
class SshRunner:
96 c92b310a Michael Hanselmann
  """Wrapper for SSH commands.
97 a8083063 Iustin Pop

98 a8083063 Iustin Pop
  """
99 b43dcc5a Manuel Franceschini
  def __init__(self, cluster_name, ipv6=False):
100 b43dcc5a Manuel Franceschini
    """Initializes this class.
101 b43dcc5a Manuel Franceschini

102 b43dcc5a Manuel Franceschini
    @type cluster_name: str
103 b43dcc5a Manuel Franceschini
    @param cluster_name: name of the cluster
104 b43dcc5a Manuel Franceschini
    @type ipv6: bool
105 b43dcc5a Manuel Franceschini
    @param ipv6: If true, force ssh to use IPv6 addresses only
106 b43dcc5a Manuel Franceschini

107 b43dcc5a Manuel Franceschini
    """
108 56bece1f Iustin Pop
    self.cluster_name = cluster_name
109 b43dcc5a Manuel Franceschini
    self.ipv6 = ipv6
110 1ff08570 Michael Hanselmann
111 652d6694 Michael Hanselmann
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
112 2892a4c9 Iustin Pop
                       strict_host_check, private_key=None, quiet=True):
113 bf75f132 Iustin Pop
    """Builds a list with needed SSH options.
114 bf75f132 Iustin Pop

115 bf75f132 Iustin Pop
    @param batch: same as ssh's batch option
116 bf75f132 Iustin Pop
    @param ask_key: allows ssh to ask for key confirmation; this
117 bf75f132 Iustin Pop
        parameter conflicts with the batch one
118 bf75f132 Iustin Pop
    @param use_cluster_key: if True, use the cluster name as the
119 bf75f132 Iustin Pop
        HostKeyAlias name
120 bf75f132 Iustin Pop
    @param strict_host_check: this makes the host key checking strict
121 4403ff8d René Nussbaumer
    @param private_key: use this private key instead of the default
122 2892a4c9 Iustin Pop
    @param quiet: whether to enable -q to ssh
123 bf75f132 Iustin Pop

124 bf75f132 Iustin Pop
    @rtype: list
125 a4ccecf6 Michael Hanselmann
    @return: the list of options ready to use in L{utils.process.RunCmd}
126 bf75f132 Iustin Pop

127 bf75f132 Iustin Pop
    """
128 f6d9f4c3 Michael Hanselmann
    options = [
129 f6d9f4c3 Michael Hanselmann
      "-oEscapeChar=none",
130 f6d9f4c3 Michael Hanselmann
      "-oHashKnownHosts=no",
131 8fd1bfa9 Michael Hanselmann
      "-oGlobalKnownHostsFile=%s" % pathutils.SSH_KNOWN_HOSTS_FILE,
132 f6d9f4c3 Michael Hanselmann
      "-oUserKnownHostsFile=/dev/null",
133 b427788e Iustin Pop
      "-oCheckHostIp=no",
134 f6d9f4c3 Michael Hanselmann
      ]
135 f6d9f4c3 Michael Hanselmann
136 f6d9f4c3 Michael Hanselmann
    if use_cluster_key:
137 56bece1f Iustin Pop
      options.append("-oHostKeyAlias=%s" % self.cluster_name)
138 f6d9f4c3 Michael Hanselmann
139 2892a4c9 Iustin Pop
    if quiet:
140 2892a4c9 Iustin Pop
      options.append("-q")
141 2892a4c9 Iustin Pop
142 4403ff8d René Nussbaumer
    if private_key:
143 4403ff8d René Nussbaumer
      options.append("-i%s" % private_key)
144 4403ff8d René Nussbaumer
145 652d6694 Michael Hanselmann
    # TODO: Too many boolean options, maybe convert them to more descriptive
146 652d6694 Michael Hanselmann
    # constants.
147 652d6694 Michael Hanselmann
148 f6d9f4c3 Michael Hanselmann
    # Note: ask_key conflicts with batch mode
149 f6d9f4c3 Michael Hanselmann
    if batch:
150 f6d9f4c3 Michael Hanselmann
      if ask_key:
151 f6d9f4c3 Michael Hanselmann
        raise errors.ProgrammerError("SSH call requested conflicting options")
152 f6d9f4c3 Michael Hanselmann
153 652d6694 Michael Hanselmann
      options.append("-oBatchMode=yes")
154 652d6694 Michael Hanselmann
155 652d6694 Michael Hanselmann
      if strict_host_check:
156 652d6694 Michael Hanselmann
        options.append("-oStrictHostKeyChecking=yes")
157 652d6694 Michael Hanselmann
      else:
158 652d6694 Michael Hanselmann
        options.append("-oStrictHostKeyChecking=no")
159 f6d9f4c3 Michael Hanselmann
160 e66d9f1a Iustin Pop
    else:
161 e66d9f1a Iustin Pop
      # non-batch mode
162 e66d9f1a Iustin Pop
163 e66d9f1a Iustin Pop
      if ask_key:
164 e66d9f1a Iustin Pop
        options.append("-oStrictHostKeyChecking=ask")
165 e66d9f1a Iustin Pop
      elif strict_host_check:
166 e66d9f1a Iustin Pop
        options.append("-oStrictHostKeyChecking=yes")
167 e66d9f1a Iustin Pop
      else:
168 e66d9f1a Iustin Pop
        options.append("-oStrictHostKeyChecking=no")
169 f6d9f4c3 Michael Hanselmann
170 b43dcc5a Manuel Franceschini
    if self.ipv6:
171 b43dcc5a Manuel Franceschini
      options.append("-6")
172 b43dcc5a Manuel Franceschini
173 f6d9f4c3 Michael Hanselmann
    return options
174 1ff08570 Michael Hanselmann
175 8f07f831 Michael Hanselmann
  def BuildCmd(self, hostname, user, command, batch=True, ask_key=False,
176 4403ff8d René Nussbaumer
               tty=False, use_cluster_key=True, strict_host_check=True,
177 2892a4c9 Iustin Pop
               private_key=None, quiet=True):
178 c92b310a Michael Hanselmann
    """Build an ssh command to execute a command on a remote node.
179 c92b310a Michael Hanselmann

180 c41eea6e Iustin Pop
    @param hostname: the target host, string
181 c41eea6e Iustin Pop
    @param user: user to auth as
182 c41eea6e Iustin Pop
    @param command: the command
183 c41eea6e Iustin Pop
    @param batch: if true, ssh will run in batch mode with no prompting
184 c41eea6e Iustin Pop
    @param ask_key: if true, ssh will run with
185 c41eea6e Iustin Pop
        StrictHostKeyChecking=ask, so that we can connect to an
186 c41eea6e Iustin Pop
        unknown host (not valid in batch mode)
187 c41eea6e Iustin Pop
    @param use_cluster_key: whether to expect and use the
188 c41eea6e Iustin Pop
        cluster-global SSH key
189 c41eea6e Iustin Pop
    @param strict_host_check: whether to check the host's SSH key at all
190 4403ff8d René Nussbaumer
    @param private_key: use this private key instead of the default
191 2892a4c9 Iustin Pop
    @param quiet: whether to enable -q to ssh
192 c41eea6e Iustin Pop

193 c41eea6e Iustin Pop
    @return: the ssh call to run 'command' on the remote host.
194 c92b310a Michael Hanselmann

195 c92b310a Michael Hanselmann
    """
196 2892a4c9 Iustin Pop
    argv = [constants.SSH]
197 652d6694 Michael Hanselmann
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
198 2892a4c9 Iustin Pop
                                      strict_host_check, private_key,
199 2892a4c9 Iustin Pop
                                      quiet=quiet))
200 8f07f831 Michael Hanselmann
    if tty:
201 f724a702 Balazs Lecz
      argv.extend(["-t", "-t"])
202 cffbbae7 Michael Hanselmann
203 cffbbae7 Michael Hanselmann
    argv.append("%s@%s" % (user, hostname))
204 cffbbae7 Michael Hanselmann
205 cffbbae7 Michael Hanselmann
    # Insert variables for virtual nodes
206 cffbbae7 Michael Hanselmann
    argv.extend("export %s=%s;" %
207 cffbbae7 Michael Hanselmann
                (utils.ShellQuote(name), utils.ShellQuote(value))
208 cffbbae7 Michael Hanselmann
                for (name, value) in
209 cffbbae7 Michael Hanselmann
                  vcluster.EnvironmentForHost(hostname).items())
210 cffbbae7 Michael Hanselmann
211 cffbbae7 Michael Hanselmann
    argv.append(command)
212 cffbbae7 Michael Hanselmann
213 c92b310a Michael Hanselmann
    return argv
214 c92b310a Michael Hanselmann
215 54ab6aec Michael Hanselmann
  def Run(self, *args, **kwargs):
216 c92b310a Michael Hanselmann
    """Runs a command on a remote node.
217 c92b310a Michael Hanselmann

218 c92b310a Michael Hanselmann
    This method has the same return value as `utils.RunCmd()`, which it
219 c92b310a Michael Hanselmann
    uses to launch ssh.
220 c92b310a Michael Hanselmann

221 c41eea6e Iustin Pop
    Args: see SshRunner.BuildCmd.
222 c92b310a Michael Hanselmann

223 a4ccecf6 Michael Hanselmann
    @rtype: L{utils.process.RunResult}
224 a4ccecf6 Michael Hanselmann
    @return: the result as from L{utils.process.RunCmd()}
225 c92b310a Michael Hanselmann

226 c92b310a Michael Hanselmann
    """
227 54ab6aec Michael Hanselmann
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
228 c92b310a Michael Hanselmann
229 c92b310a Michael Hanselmann
  def CopyFileToNode(self, node, filename):
230 c92b310a Michael Hanselmann
    """Copy a file to another node with scp.
231 c92b310a Michael Hanselmann

232 c41eea6e Iustin Pop
    @param node: node in the cluster
233 c41eea6e Iustin Pop
    @param filename: absolute pathname of a local file
234 c92b310a Michael Hanselmann

235 c41eea6e Iustin Pop
    @rtype: boolean
236 c41eea6e Iustin Pop
    @return: the success of the operation
237 a8083063 Iustin Pop

238 c92b310a Michael Hanselmann
    """
239 c92b310a Michael Hanselmann
    if not os.path.isabs(filename):
240 23828f1c Iustin Pop
      logging.error("File %s must be an absolute path", filename)
241 c92b310a Michael Hanselmann
      return False
242 a8083063 Iustin Pop
243 1d544ba3 Michael Hanselmann
    if not os.path.isfile(filename):
244 23828f1c Iustin Pop
      logging.error("File %s does not exist", filename)
245 1d544ba3 Michael Hanselmann
      return False
246 1d544ba3 Michael Hanselmann
247 2892a4c9 Iustin Pop
    command = [constants.SCP, "-p"]
248 652d6694 Michael Hanselmann
    command.extend(self._BuildSshOptions(True, False, True, True))
249 c92b310a Michael Hanselmann
    command.append(filename)
250 8062638d Manuel Franceschini
    if netutils.IP6Address.IsValid(node):
251 8062638d Manuel Franceschini
      node = netutils.FormatAddress((node, None))
252 8062638d Manuel Franceschini
253 cffbbae7 Michael Hanselmann
    command.append("%s:%s" % (node, vcluster.ExchangeNodeRoot(node, filename)))
254 a8083063 Iustin Pop
255 c92b310a Michael Hanselmann
    result = utils.RunCmd(command)
256 a8083063 Iustin Pop
257 c92b310a Michael Hanselmann
    if result.failed:
258 9dc45ab1 Michael Hanselmann
      logging.error("Copy to node %s failed (%s) error '%s',"
259 9dc45ab1 Michael Hanselmann
                    " command was '%s'",
260 23828f1c Iustin Pop
                    node, result.fail_reason, result.output, result.cmd)
261 a8083063 Iustin Pop
262 c92b310a Michael Hanselmann
    return not result.failed
263 a8083063 Iustin Pop
264 c92b310a Michael Hanselmann
  def VerifyNodeHostname(self, node):
265 c92b310a Michael Hanselmann
    """Verify hostname consistency via SSH.
266 a8083063 Iustin Pop

267 c92b310a Michael Hanselmann
    This functions connects via ssh to a node and compares the hostname
268 c92b310a Michael Hanselmann
    reported by the node to the name with have (the one that we
269 c92b310a Michael Hanselmann
    connected to).
270 a8083063 Iustin Pop

271 c92b310a Michael Hanselmann
    This is used to detect problems in ssh known_hosts files
272 5bbd3f7f Michael Hanselmann
    (conflicting known hosts) and inconsistencies between dns/hosts
273 c92b310a Michael Hanselmann
    entries and local machine names
274 a8083063 Iustin Pop

275 c41eea6e Iustin Pop
    @param node: nodename of a host to check; can be short or
276 c41eea6e Iustin Pop
        full qualified hostname
277 a8083063 Iustin Pop

278 c41eea6e Iustin Pop
    @return: (success, detail), where:
279 c41eea6e Iustin Pop
        - success: True/False
280 c41eea6e Iustin Pop
        - detail: string with details
281 a8083063 Iustin Pop

282 c92b310a Michael Hanselmann
    """
283 cffbbae7 Michael Hanselmann
    cmd = ("if test -z \"$GANETI_HOSTNAME\"; then"
284 cffbbae7 Michael Hanselmann
           "  hostname --fqdn;"
285 cffbbae7 Michael Hanselmann
           "else"
286 cffbbae7 Michael Hanselmann
           "  echo \"$GANETI_HOSTNAME\";"
287 cffbbae7 Michael Hanselmann
           "fi")
288 052783ff Michael Hanselmann
    retval = self.Run(node, constants.SSH_LOGIN_USER, cmd, quiet=False)
289 a8083063 Iustin Pop
290 c92b310a Michael Hanselmann
    if retval.failed:
291 c92b310a Michael Hanselmann
      msg = "ssh problem"
292 c92b310a Michael Hanselmann
      output = retval.output
293 c92b310a Michael Hanselmann
      if output:
294 c92b310a Michael Hanselmann
        msg += ": %s" % output
295 a162cf5b Iustin Pop
      else:
296 a162cf5b Iustin Pop
        msg += ": %s (no output)" % retval.fail_reason
297 099c52ad Iustin Pop
      logging.error("Command %s failed: %s", retval.cmd, msg)
298 c92b310a Michael Hanselmann
      return False, msg
299 a8083063 Iustin Pop
300 c92b310a Michael Hanselmann
    remotehostname = retval.stdout.strip()
301 a8083063 Iustin Pop
302 c92b310a Michael Hanselmann
    if not remotehostname or remotehostname != node:
303 31821208 Iustin Pop
      if node.startswith(remotehostname + "."):
304 31821208 Iustin Pop
        msg = "hostname not FQDN"
305 31821208 Iustin Pop
      else:
306 2175e25d Manuel Franceschini
        msg = "hostname mismatch"
307 31821208 Iustin Pop
      return False, ("%s: expected %s but got %s" %
308 31821208 Iustin Pop
                     (msg, node, remotehostname))
309 a8083063 Iustin Pop
310 c92b310a Michael Hanselmann
    return True, "host matches"
311 75a5f456 Michael Hanselmann
312 75a5f456 Michael Hanselmann
313 7688d0d3 Michael Hanselmann
def WriteKnownHostsFile(cfg, file_name):
314 75a5f456 Michael Hanselmann
  """Writes the cluster-wide equally known_hosts file.
315 75a5f456 Michael Hanselmann

316 75a5f456 Michael Hanselmann
  """
317 a3f9f296 Guido Trotter
  utils.WriteFile(file_name, mode=0600,
318 7688d0d3 Michael Hanselmann
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
319 75a5f456 Michael Hanselmann
                                            cfg.GetHostKey()))