summaryrefslogtreecommitdiffstats
path: root/awlsim/coreclient/sshtunnel.py
blob: 45d8cff01558e073d9ba424337d36d981f305e1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# -*- coding: utf-8 -*-
#
# AWL simulator - SSH tunnel helper
#
# Copyright 2016-2017 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals
#from awlsim.common.cython_support cimport * #@cy
from awlsim.common.compat import *

from awlsim.common.exceptions import *
from awlsim.common.net import *
from awlsim.common.env import *
from awlsim.common.util import *
from awlsim.common.subprocess_wrapper import *
from awlsim.common.monotonic import * #+cimport

if not osIsWindows:
	import pty
import os
import select
import signal
import time


class SSHTunnel(object):
	"""SSH tunnel helper.
	"""

	SSH_DEFAULT_USER	= "pi"
	SSH_PORT		= 22
	SSH_LOCAL_PORT_START	= 4151 + 10
	SSH_LOCAL_PORT_END	= SSH_LOCAL_PORT_START + 4096
	SSH_DEFAULT_EXECUTABLE	= "ssh"

	def __init__(self, remoteHost, remotePort,
		     sshUser=SSH_DEFAULT_USER,
		     localPort=None,
		     sshExecutable=SSH_DEFAULT_EXECUTABLE,
		     sshPort=SSH_PORT):
		"""Create an SSH tunnel.
		"""
		if osIsWindows:
			# win magic: translate "ssh" to "plink".
			if sshExecutable == "ssh":
				sshExecutable = "plink.exe"
		self.remoteHost = remoteHost
		self.remotePort = remotePort
		self.sshUser = sshUser
		self.localPort = localPort
		self.sshExecutable = sshExecutable
		self.sshPort = sshPort
		self.__sshPid = None
		self.__sshProc = None

	def connect(self, timeout=10.0):
		"""Establish the SSH tunnel.
		"""
		localPort = self.localPort
		if localPort is None:
			localPort = self.SSH_LOCAL_PORT_START
			while not netPortIsUnused("localhost", localPort):
				localPort += 1
				if localPort > self.SSH_LOCAL_PORT_END:
					raise AwlSimError("Failed to find an "
						"unused local port for the "
						"SSH tunnel.")
		actualLocalPort = localPort

		self.sshMessage("Establishing SSH tunnel to '%s@%s'...\n" %(
				self.sshUser, self.remoteHost),
				isDebug=False)

		self.__sshPid = None
		try:
			# Prepare SSH environment and arguments.
			env = AwlSimEnv.clearLang(AwlSimEnv.getEnv())
			if osIsWindows and "plink" in self.sshExecutable.lower():
				# Run plink.exe (PuTTY)
				pw = self.getPassphrase("%s's Password:" % self.remoteHost)
				argv = [ self.sshExecutable,
					"-ssh",
					"-pw", None,
					"-P", "%d" % self.sshPort,
					"-l", self.sshUser,
					"-L", "localhost:%d:localhost:%d" % (
						localPort, self.remotePort),
					"-N",
					"-x",
					"-v",
					self.remoteHost, ]
				pwArgIdx = 2
				if pw is None:
					del argv[pwArgIdx : pwArgIdx + 2]
					pwArgIdx = None
				else:
					argv[pwArgIdx + 1] = pw.decode("UTF-8")
			else:
				# Run OpenSSH
				argv = [ self.sshExecutable,
					"-p", "%d" % self.sshPort,
					"-l", self.sshUser,
					"-L", "localhost:%d:localhost:%d" % (
						localPort, self.remotePort),
					"-N",
					"-x",
					"-v",
					self.remoteHost, ]
				pwArgIdx = None

			printArgv = argv[:]
			if pwArgIdx is not None:
				printArgv[pwArgIdx + 1] = "*" * len(printArgv[pwArgIdx + 1])
			self.sshMessage("Running command:\n  %s\n" % " ".join(printArgv),
					isDebug=False)

			if osIsWindows:
				# Start SSH tunnel as subprocess.
				proc = PopenWrapper(argv, env=env, stdio=True)
				self.__sshProc = proc
				self.sshMessage("Starting %s..." % argv[0],
						isDebug=False)
				self.sleep(1.0)
				proc.stdin.write(b"n\n") # Do not cache host auth.
				proc.stdin.flush()
				for i in range(3):
					self.sshMessage(".", isDebug=False)
					self.sleep(1.0)
					if self.__sshProc.returncode is not None:
						raise AwlSimError("%s exited with "
							"error." % argv[0])
			else:
				# Create a PTY and fork.
				childPid, ptyMasterFd = pty.fork()
				if childPid == pty.CHILD:
					# Run SSH
					execargs = argv + [env]
					os.execlpe(argv[0], *execargs)
					assert(0) # unreachable
				self.__sshPid = childPid
				self.__handshake(ptyMasterFd, timeout)
		except (OSError, ValueError, IOError) as e:
			with suppressAllExc:
				self.shutdown()
			raise AwlSimError("Failed to execute SSH to "
					  "establish SSH tunnel:\n%s" %\
					  str(e))
		except KeyboardInterrupt as e:
			with suppressAllExc:
				self.shutdown()
			raise AwlSimError("Interrupted by user.")
		return "localhost", actualLocalPort

	def shutdown(self):
		if self.__sshProc:
			try:
				with suppressAllExc:
					self.__sshProc.terminate()
			finally:
				self.__sshProc = None
		if self.__sshPid is not None:
			try:
				with suppressAllExc:
					os.kill(self.__sshPid, signal.SIGTERM)
			finally:
				self.__sshPid = None

	@staticmethod
	def __read(fd):
		data = []
		while True:
			rfds, wfds, xfds = select.select([fd], [], [], 0)
			if fd not in rfds:
				break
			d = os.read(fd, 1024)
			if not d:
				break
			data.append(d)
		return b''.join(data)

	@staticmethod
	def __write(fd, data):
		while data:
			count = os.write(fd, data)
			data = data[count:]

	PROMPT_PW	= "'s Password:"
	PROMPT_AUTH	= "The authenticity of host "
	PROMPT_YESNO	= " (yes/no)?"
	AUTH_FINISH	= "Authenticated to "

	def __handshake(self, ptyMasterFd, timeout):
		timeoutEnd = monotonic_time() + (timeout or 0)
		sentPw, authReq, finished = False, [], False
		while not finished:
			self.sleep(0.1)
			if timeout and monotonic_time() >= timeoutEnd:
				raise AwlSimError("Timeout establishing SSH tunnel.")
			fromSsh = self.__read(ptyMasterFd)
			try:
				fromSsh = fromSsh.decode("UTF-8", "ignore")
			except UnicodeError:
				fromSsh = ""
			for line in fromSsh.splitlines():
				if not line:
					continue
				lineLow = line.lower()
				isDebug = lineLow.strip().startswith("debug")
				self.sshMessage(line, isDebug)
				if isDebug:
					continue
				if authReq:
					authReq.append(line)
				if self.PROMPT_PW.lower() in lineLow:
					if sentPw:
						# Second try.
						raise AwlSimError("SSH tunnel passphrase "
							"was not accepted.")
					passphrase = self.getPassphrase(line)
					if passphrase is None:
						raise AwlSimError("SSH tunnel connection "
							"requires a passphrase, but "
							"no passphrase was given.")
					self.__write(ptyMasterFd, passphrase)
					if not passphrase.endswith(b"\n"):
						self.__write(ptyMasterFd, b"\n")
					sentPw = True
					timeoutEnd = monotonic_time() + (timeout or 0)
					continue
				if self.PROMPT_AUTH.lower() in lineLow:
					authReq.append(line)
					continue
				if self.PROMPT_YESNO.lower() in lineLow and authReq:
					ok = self.hostAuth("\n".join(authReq))
					if not ok:
						raise AwlSimError("SSH tunnel host "
							"authentication failed.")
					self.__write(ptyMasterFd, b"yes\n")
					authReq = []
					timeoutEnd = monotonic_time() + (timeout or 0)
					continue
				if self.AUTH_FINISH.lower() in lineLow:
					# Successfully authenticated.
					finished = True
					continue

	def sleep(self, seconds):
		"""Sleep for a number of seconds.
		"""
		time.sleep(seconds)

	def sshMessage(self, message, isDebug):
		"""Print a SSH log message.
		"""
		if not isDebug:
			printInfo("[SSH]:  %s" % message)

	def getPassphrase(self, prompt):
		"""Get a password from the user.
		"""
		try:
			return input(prompt).encode("UTF-8", "ignore")
		except UnicodeError:
			return b""

	def hostAuth(self, prompt):
		"""Get the user answer to the host authentication question.
		This function returns a boolean.
		"""
		return str2bool(input(prompt))
bues.ch cgit interface