Statistics
| Branch: | Tag: | Revision:

root / lib / ssh.py @ 8fd1bfa9

History | View | Annotate | Download (8.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 82122173 Iustin Pop
37 82122173 Iustin Pop
38 33993ab8 René Nussbaumer
def FormatParamikoFingerprint(fingerprint):
39 697a3d61 Manuel Franceschini
  """Format paramiko PKey fingerprint.
40 33993ab8 René Nussbaumer

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

45 33993ab8 René Nussbaumer
  """
46 33993ab8 René Nussbaumer
  assert len(fingerprint) % 2 == 0
47 33993ab8 René Nussbaumer
  return ":".join(re.findall(r"..", fingerprint.lower()))
48 33993ab8 René Nussbaumer
49 33993ab8 René Nussbaumer
50 70d9e3d8 Iustin Pop
def GetUserFiles(user, mkdir=False):
51 70d9e3d8 Iustin Pop
  """Return the paths of a user's ssh files.
52 70d9e3d8 Iustin Pop

53 70d9e3d8 Iustin Pop
  The function will return a triplet (priv_key_path, pub_key_path,
54 70d9e3d8 Iustin Pop
  auth_key_path) that are used for ssh authentication. Currently, the
55 70d9e3d8 Iustin Pop
  keys used are DSA keys, so this function will return:
56 70d9e3d8 Iustin Pop
  (~user/.ssh/id_dsa, ~user/.ssh/id_dsa.pub,
57 70d9e3d8 Iustin Pop
  ~user/.ssh/authorized_keys).
58 70d9e3d8 Iustin Pop

59 70d9e3d8 Iustin Pop
  If the optional parameter mkdir is True, the ssh directory will be
60 70d9e3d8 Iustin Pop
  created if it doesn't exist.
61 70d9e3d8 Iustin Pop

62 70d9e3d8 Iustin Pop
  Regardless of the mkdir parameters, the script will raise an error
63 70d9e3d8 Iustin Pop
  if ~user/.ssh is not a directory.
64 70d9e3d8 Iustin Pop

65 70d9e3d8 Iustin Pop
  """
66 70d9e3d8 Iustin Pop
  user_dir = utils.GetHomeDir(user)
67 70d9e3d8 Iustin Pop
  if not user_dir:
68 70d9e3d8 Iustin Pop
    raise errors.OpExecError("Cannot resolve home of user %s" % user)
69 70d9e3d8 Iustin Pop
70 c4feafe8 Iustin Pop
  ssh_dir = utils.PathJoin(user_dir, ".ssh")
71 5bae14d9 Guido Trotter
  if mkdir:
72 5bae14d9 Guido Trotter
    utils.EnsureDirs([(ssh_dir, constants.SECURE_DIR_MODE)])
73 70d9e3d8 Iustin Pop
  elif not os.path.isdir(ssh_dir):
74 898a6d45 Michael Hanselmann
    raise errors.OpExecError("Path %s is not a directory" % ssh_dir)
75 70d9e3d8 Iustin Pop
76 c4feafe8 Iustin Pop
  return [utils.PathJoin(ssh_dir, base)
77 70d9e3d8 Iustin Pop
          for base in ["id_dsa", "id_dsa.pub", "authorized_keys"]]
78 70d9e3d8 Iustin Pop
79 70d9e3d8 Iustin Pop
80 c92b310a Michael Hanselmann
class SshRunner:
81 c92b310a Michael Hanselmann
  """Wrapper for SSH commands.
82 a8083063 Iustin Pop

83 a8083063 Iustin Pop
  """
84 b43dcc5a Manuel Franceschini
  def __init__(self, cluster_name, ipv6=False):
85 b43dcc5a Manuel Franceschini
    """Initializes this class.
86 b43dcc5a Manuel Franceschini

87 b43dcc5a Manuel Franceschini
    @type cluster_name: str
88 b43dcc5a Manuel Franceschini
    @param cluster_name: name of the cluster
89 b43dcc5a Manuel Franceschini
    @type ipv6: bool
90 b43dcc5a Manuel Franceschini
    @param ipv6: If true, force ssh to use IPv6 addresses only
91 b43dcc5a Manuel Franceschini

92 b43dcc5a Manuel Franceschini
    """
93 56bece1f Iustin Pop
    self.cluster_name = cluster_name
94 b43dcc5a Manuel Franceschini
    self.ipv6 = ipv6
95 1ff08570 Michael Hanselmann
96 652d6694 Michael Hanselmann
  def _BuildSshOptions(self, batch, ask_key, use_cluster_key,
97 2892a4c9 Iustin Pop
                       strict_host_check, private_key=None, quiet=True):
98 bf75f132 Iustin Pop
    """Builds a list with needed SSH options.
99 bf75f132 Iustin Pop

100 bf75f132 Iustin Pop
    @param batch: same as ssh's batch option
101 bf75f132 Iustin Pop
    @param ask_key: allows ssh to ask for key confirmation; this
102 bf75f132 Iustin Pop
        parameter conflicts with the batch one
103 bf75f132 Iustin Pop
    @param use_cluster_key: if True, use the cluster name as the
104 bf75f132 Iustin Pop
        HostKeyAlias name
105 bf75f132 Iustin Pop
    @param strict_host_check: this makes the host key checking strict
106 4403ff8d René Nussbaumer
    @param private_key: use this private key instead of the default
107 2892a4c9 Iustin Pop
    @param quiet: whether to enable -q to ssh
108 bf75f132 Iustin Pop

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

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

165 c41eea6e Iustin Pop
    @param hostname: the target host, string
166 c41eea6e Iustin Pop
    @param user: user to auth as
167 c41eea6e Iustin Pop
    @param command: the command
168 c41eea6e Iustin Pop
    @param batch: if true, ssh will run in batch mode with no prompting
169 c41eea6e Iustin Pop
    @param ask_key: if true, ssh will run with
170 c41eea6e Iustin Pop
        StrictHostKeyChecking=ask, so that we can connect to an
171 c41eea6e Iustin Pop
        unknown host (not valid in batch mode)
172 c41eea6e Iustin Pop
    @param use_cluster_key: whether to expect and use the
173 c41eea6e Iustin Pop
        cluster-global SSH key
174 c41eea6e Iustin Pop
    @param strict_host_check: whether to check the host's SSH key at all
175 4403ff8d René Nussbaumer
    @param private_key: use this private key instead of the default
176 2892a4c9 Iustin Pop
    @param quiet: whether to enable -q to ssh
177 c41eea6e Iustin Pop

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

180 c92b310a Michael Hanselmann
    """
181 2892a4c9 Iustin Pop
    argv = [constants.SSH]
182 652d6694 Michael Hanselmann
    argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key,
183 2892a4c9 Iustin Pop
                                      strict_host_check, private_key,
184 2892a4c9 Iustin Pop
                                      quiet=quiet))
185 8f07f831 Michael Hanselmann
    if tty:
186 f724a702 Balazs Lecz
      argv.extend(["-t", "-t"])
187 c92b310a Michael Hanselmann
    argv.extend(["%s@%s" % (user, hostname), command])
188 c92b310a Michael Hanselmann
    return argv
189 c92b310a Michael Hanselmann
190 54ab6aec Michael Hanselmann
  def Run(self, *args, **kwargs):
191 c92b310a Michael Hanselmann
    """Runs a command on a remote node.
192 c92b310a Michael Hanselmann

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

196 c41eea6e Iustin Pop
    Args: see SshRunner.BuildCmd.
197 c92b310a Michael Hanselmann

198 a4ccecf6 Michael Hanselmann
    @rtype: L{utils.process.RunResult}
199 a4ccecf6 Michael Hanselmann
    @return: the result as from L{utils.process.RunCmd()}
200 c92b310a Michael Hanselmann

201 c92b310a Michael Hanselmann
    """
202 54ab6aec Michael Hanselmann
    return utils.RunCmd(self.BuildCmd(*args, **kwargs))
203 c92b310a Michael Hanselmann
204 c92b310a Michael Hanselmann
  def CopyFileToNode(self, node, filename):
205 c92b310a Michael Hanselmann
    """Copy a file to another node with scp.
206 c92b310a Michael Hanselmann

207 c41eea6e Iustin Pop
    @param node: node in the cluster
208 c41eea6e Iustin Pop
    @param filename: absolute pathname of a local file
209 c92b310a Michael Hanselmann

210 c41eea6e Iustin Pop
    @rtype: boolean
211 c41eea6e Iustin Pop
    @return: the success of the operation
212 a8083063 Iustin Pop

213 c92b310a Michael Hanselmann
    """
214 c92b310a Michael Hanselmann
    if not os.path.isabs(filename):
215 23828f1c Iustin Pop
      logging.error("File %s must be an absolute path", filename)
216 c92b310a Michael Hanselmann
      return False
217 a8083063 Iustin Pop
218 1d544ba3 Michael Hanselmann
    if not os.path.isfile(filename):
219 23828f1c Iustin Pop
      logging.error("File %s does not exist", filename)
220 1d544ba3 Michael Hanselmann
      return False
221 1d544ba3 Michael Hanselmann
222 2892a4c9 Iustin Pop
    command = [constants.SCP, "-p"]
223 652d6694 Michael Hanselmann
    command.extend(self._BuildSshOptions(True, False, True, True))
224 c92b310a Michael Hanselmann
    command.append(filename)
225 8062638d Manuel Franceschini
    if netutils.IP6Address.IsValid(node):
226 8062638d Manuel Franceschini
      node = netutils.FormatAddress((node, None))
227 8062638d Manuel Franceschini
228 c92b310a Michael Hanselmann
    command.append("%s:%s" % (node, filename))
229 a8083063 Iustin Pop
230 c92b310a Michael Hanselmann
    result = utils.RunCmd(command)
231 a8083063 Iustin Pop
232 c92b310a Michael Hanselmann
    if result.failed:
233 9dc45ab1 Michael Hanselmann
      logging.error("Copy to node %s failed (%s) error '%s',"
234 9dc45ab1 Michael Hanselmann
                    " command was '%s'",
235 23828f1c Iustin Pop
                    node, result.fail_reason, result.output, result.cmd)
236 a8083063 Iustin Pop
237 c92b310a Michael Hanselmann
    return not result.failed
238 a8083063 Iustin Pop
239 c92b310a Michael Hanselmann
  def VerifyNodeHostname(self, node):
240 c92b310a Michael Hanselmann
    """Verify hostname consistency via SSH.
241 a8083063 Iustin Pop

242 c92b310a Michael Hanselmann
    This functions connects via ssh to a node and compares the hostname
243 c92b310a Michael Hanselmann
    reported by the node to the name with have (the one that we
244 c92b310a Michael Hanselmann
    connected to).
245 a8083063 Iustin Pop

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

250 c41eea6e Iustin Pop
    @param node: nodename of a host to check; can be short or
251 c41eea6e Iustin Pop
        full qualified hostname
252 a8083063 Iustin Pop

253 c41eea6e Iustin Pop
    @return: (success, detail), where:
254 c41eea6e Iustin Pop
        - success: True/False
255 c41eea6e Iustin Pop
        - detail: string with details
256 a8083063 Iustin Pop

257 c92b310a Michael Hanselmann
    """
258 ebcd61bb Iustin Pop
    retval = self.Run(node, "root", "hostname --fqdn", quiet=False)
259 a8083063 Iustin Pop
260 c92b310a Michael Hanselmann
    if retval.failed:
261 c92b310a Michael Hanselmann
      msg = "ssh problem"
262 c92b310a Michael Hanselmann
      output = retval.output
263 c92b310a Michael Hanselmann
      if output:
264 c92b310a Michael Hanselmann
        msg += ": %s" % output
265 a162cf5b Iustin Pop
      else:
266 a162cf5b Iustin Pop
        msg += ": %s (no output)" % retval.fail_reason
267 099c52ad Iustin Pop
      logging.error("Command %s failed: %s", retval.cmd, msg)
268 c92b310a Michael Hanselmann
      return False, msg
269 a8083063 Iustin Pop
270 c92b310a Michael Hanselmann
    remotehostname = retval.stdout.strip()
271 a8083063 Iustin Pop
272 c92b310a Michael Hanselmann
    if not remotehostname or remotehostname != node:
273 31821208 Iustin Pop
      if node.startswith(remotehostname + "."):
274 31821208 Iustin Pop
        msg = "hostname not FQDN"
275 31821208 Iustin Pop
      else:
276 2175e25d Manuel Franceschini
        msg = "hostname mismatch"
277 31821208 Iustin Pop
      return False, ("%s: expected %s but got %s" %
278 31821208 Iustin Pop
                     (msg, node, remotehostname))
279 a8083063 Iustin Pop
280 c92b310a Michael Hanselmann
    return True, "host matches"
281 75a5f456 Michael Hanselmann
282 75a5f456 Michael Hanselmann
283 7688d0d3 Michael Hanselmann
def WriteKnownHostsFile(cfg, file_name):
284 75a5f456 Michael Hanselmann
  """Writes the cluster-wide equally known_hosts file.
285 75a5f456 Michael Hanselmann

286 75a5f456 Michael Hanselmann
  """
287 a3f9f296 Guido Trotter
  utils.WriteFile(file_name, mode=0600,
288 7688d0d3 Michael Hanselmann
                  data="%s ssh-rsa %s\n" % (cfg.GetClusterName(),
289 75a5f456 Michael Hanselmann
                                            cfg.GetHostKey()))