transport.py 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  3. #
  4. # This file is part of paramiko.
  5. #
  6. # Paramiko is free software; you can redistribute it and/or modify it under the
  7. # terms of the GNU Lesser General Public License as published by the Free
  8. # Software Foundation; either version 2.1 of the License, or (at your option)
  9. # any later version.
  10. #
  11. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  12. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  13. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License
  17. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  18. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  19. """
  20. Core protocol implementation
  21. """
  22. from __future__ import print_function
  23. import os
  24. import socket
  25. import sys
  26. import threading
  27. import time
  28. import weakref
  29. from hashlib import md5, sha1, sha256, sha512
  30. from cryptography.hazmat.backends import default_backend
  31. from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes
  32. import paramiko
  33. from paramiko import util
  34. from paramiko.auth_handler import AuthHandler
  35. from paramiko.ssh_gss import GSSAuth
  36. from paramiko.channel import Channel
  37. from paramiko.common import (
  38. xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, cMSG_GLOBAL_REQUEST, DEBUG,
  39. MSG_KEXINIT, MSG_IGNORE, MSG_DISCONNECT, MSG_DEBUG, ERROR, WARNING,
  40. cMSG_UNIMPLEMENTED, INFO, cMSG_KEXINIT, cMSG_NEWKEYS, MSG_NEWKEYS,
  41. cMSG_REQUEST_SUCCESS, cMSG_REQUEST_FAILURE, CONNECTION_FAILED_CODE,
  42. OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED, OPEN_SUCCEEDED,
  43. cMSG_CHANNEL_OPEN_FAILURE, cMSG_CHANNEL_OPEN_SUCCESS, MSG_GLOBAL_REQUEST,
  44. MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE, MSG_CHANNEL_OPEN_SUCCESS,
  45. MSG_CHANNEL_OPEN_FAILURE, MSG_CHANNEL_OPEN, MSG_CHANNEL_SUCCESS,
  46. MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA,
  47. MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF,
  48. MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE,
  49. DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE,
  50. )
  51. from paramiko.compress import ZlibCompressor, ZlibDecompressor
  52. from paramiko.dsskey import DSSKey
  53. from paramiko.ed25519key import Ed25519Key
  54. from paramiko.kex_gex import KexGex, KexGexSHA256
  55. from paramiko.kex_group1 import KexGroup1
  56. from paramiko.kex_group14 import KexGroup14
  57. from paramiko.kex_ecdh_nist import KexNistp256, KexNistp384, KexNistp521
  58. from paramiko.kex_gss import KexGSSGex, KexGSSGroup1, KexGSSGroup14
  59. from paramiko.message import Message
  60. from paramiko.packet import Packetizer, NeedRekeyException
  61. from paramiko.primes import ModulusPack
  62. from paramiko.py3compat import string_types, long, byte_ord, b, input, PY2
  63. from paramiko.rsakey import RSAKey
  64. from paramiko.ecdsakey import ECDSAKey
  65. from paramiko.server import ServerInterface
  66. from paramiko.sftp_client import SFTPClient
  67. from paramiko.ssh_exception import (
  68. SSHException, BadAuthenticationType, ChannelException, ProxyCommandFailure,
  69. )
  70. from paramiko.util import retry_on_signal, ClosingContextManager, clamp_value
  71. # for thread cleanup
  72. _active_threads = []
  73. def _join_lingering_threads():
  74. for thr in _active_threads:
  75. thr.stop_thread()
  76. import atexit
  77. atexit.register(_join_lingering_threads)
  78. class Transport(threading.Thread, ClosingContextManager):
  79. """
  80. An SSH Transport attaches to a stream (usually a socket), negotiates an
  81. encrypted session, authenticates, and then creates stream tunnels, called
  82. `channels <.Channel>`, across the session. Multiple channels can be
  83. multiplexed across a single session (and often are, in the case of port
  84. forwardings).
  85. Instances of this class may be used as context managers.
  86. """
  87. _ENCRYPT = object()
  88. _DECRYPT = object()
  89. _PROTO_ID = '2.0'
  90. _CLIENT_ID = 'paramiko_%s' % paramiko.__version__
  91. # These tuples of algorithm identifiers are in preference order; do not
  92. # reorder without reason!
  93. _preferred_ciphers = (
  94. 'aes128-ctr',
  95. 'aes192-ctr',
  96. 'aes256-ctr',
  97. 'aes128-cbc',
  98. 'aes192-cbc',
  99. 'aes256-cbc',
  100. 'blowfish-cbc',
  101. '3des-cbc',
  102. )
  103. _preferred_macs = (
  104. 'hmac-sha2-256',
  105. 'hmac-sha2-512',
  106. 'hmac-sha1',
  107. 'hmac-md5',
  108. 'hmac-sha1-96',
  109. 'hmac-md5-96',
  110. )
  111. _preferred_keys = (
  112. 'ssh-ed25519',
  113. 'ecdsa-sha2-nistp256',
  114. 'ecdsa-sha2-nistp384',
  115. 'ecdsa-sha2-nistp521',
  116. 'ssh-rsa',
  117. 'ssh-dss',
  118. )
  119. _preferred_kex = (
  120. 'ecdh-sha2-nistp256',
  121. 'ecdh-sha2-nistp384',
  122. 'ecdh-sha2-nistp521',
  123. 'diffie-hellman-group-exchange-sha256',
  124. 'diffie-hellman-group-exchange-sha1',
  125. 'diffie-hellman-group14-sha1',
  126. 'diffie-hellman-group1-sha1',
  127. )
  128. _preferred_compression = ('none',)
  129. _cipher_info = {
  130. 'aes128-ctr': {
  131. 'class': algorithms.AES,
  132. 'mode': modes.CTR,
  133. 'block-size': 16,
  134. 'key-size': 16
  135. },
  136. 'aes192-ctr': {
  137. 'class': algorithms.AES,
  138. 'mode': modes.CTR,
  139. 'block-size': 16,
  140. 'key-size': 24
  141. },
  142. 'aes256-ctr': {
  143. 'class': algorithms.AES,
  144. 'mode': modes.CTR,
  145. 'block-size': 16,
  146. 'key-size': 32
  147. },
  148. 'blowfish-cbc': {
  149. 'class': algorithms.Blowfish,
  150. 'mode': modes.CBC,
  151. 'block-size': 8,
  152. 'key-size': 16
  153. },
  154. 'aes128-cbc': {
  155. 'class': algorithms.AES,
  156. 'mode': modes.CBC,
  157. 'block-size': 16,
  158. 'key-size': 16
  159. },
  160. 'aes192-cbc': {
  161. 'class': algorithms.AES,
  162. 'mode': modes.CBC,
  163. 'block-size': 16,
  164. 'key-size': 24
  165. },
  166. 'aes256-cbc': {
  167. 'class': algorithms.AES,
  168. 'mode': modes.CBC,
  169. 'block-size': 16,
  170. 'key-size': 32
  171. },
  172. '3des-cbc': {
  173. 'class': algorithms.TripleDES,
  174. 'mode': modes.CBC,
  175. 'block-size': 8,
  176. 'key-size': 24
  177. },
  178. }
  179. _mac_info = {
  180. 'hmac-sha1': {'class': sha1, 'size': 20},
  181. 'hmac-sha1-96': {'class': sha1, 'size': 12},
  182. 'hmac-sha2-256': {'class': sha256, 'size': 32},
  183. 'hmac-sha2-512': {'class': sha512, 'size': 64},
  184. 'hmac-md5': {'class': md5, 'size': 16},
  185. 'hmac-md5-96': {'class': md5, 'size': 12},
  186. }
  187. _key_info = {
  188. 'ssh-rsa': RSAKey,
  189. 'ssh-dss': DSSKey,
  190. 'ecdsa-sha2-nistp256': ECDSAKey,
  191. 'ecdsa-sha2-nistp384': ECDSAKey,
  192. 'ecdsa-sha2-nistp521': ECDSAKey,
  193. 'ssh-ed25519': Ed25519Key,
  194. }
  195. _kex_info = {
  196. 'diffie-hellman-group1-sha1': KexGroup1,
  197. 'diffie-hellman-group14-sha1': KexGroup14,
  198. 'diffie-hellman-group-exchange-sha1': KexGex,
  199. 'diffie-hellman-group-exchange-sha256': KexGexSHA256,
  200. 'gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGroup1,
  201. 'gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGroup14,
  202. 'gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGex,
  203. 'ecdh-sha2-nistp256': KexNistp256,
  204. 'ecdh-sha2-nistp384': KexNistp384,
  205. 'ecdh-sha2-nistp521': KexNistp521,
  206. }
  207. _compression_info = {
  208. # zlib@openssh.com is just zlib, but only turned on after a successful
  209. # authentication. openssh servers may only offer this type because
  210. # they've had troubles with security holes in zlib in the past.
  211. 'zlib@openssh.com': (ZlibCompressor, ZlibDecompressor),
  212. 'zlib': (ZlibCompressor, ZlibDecompressor),
  213. 'none': (None, None),
  214. }
  215. _modulus_pack = None
  216. _active_check_timeout = 0.1
  217. def __init__(self,
  218. sock,
  219. default_window_size=DEFAULT_WINDOW_SIZE,
  220. default_max_packet_size=DEFAULT_MAX_PACKET_SIZE,
  221. gss_kex=False,
  222. gss_deleg_creds=True):
  223. """
  224. Create a new SSH session over an existing socket, or socket-like
  225. object. This only creates the `.Transport` object; it doesn't begin
  226. the SSH session yet. Use `connect` or `start_client` to begin a client
  227. session, or `start_server` to begin a server session.
  228. If the object is not actually a socket, it must have the following
  229. methods:
  230. - ``send(str)``: Writes from 1 to ``len(str)`` bytes, and returns an
  231. int representing the number of bytes written. Returns
  232. 0 or raises ``EOFError`` if the stream has been closed.
  233. - ``recv(int)``: Reads from 1 to ``int`` bytes and returns them as a
  234. string. Returns 0 or raises ``EOFError`` if the stream has been
  235. closed.
  236. - ``close()``: Closes the socket.
  237. - ``settimeout(n)``: Sets a (float) timeout on I/O operations.
  238. For ease of use, you may also pass in an address (as a tuple) or a host
  239. string as the ``sock`` argument. (A host string is a hostname with an
  240. optional port (separated by ``":"``) which will be converted into a
  241. tuple of ``(hostname, port)``.) A socket will be connected to this
  242. address and used for communication. Exceptions from the ``socket``
  243. call may be thrown in this case.
  244. .. note::
  245. Modifying the the window and packet sizes might have adverse
  246. effects on your channels created from this transport. The default
  247. values are the same as in the OpenSSH code base and have been
  248. battle tested.
  249. :param socket sock:
  250. a socket or socket-like object to create the session over.
  251. :param int default_window_size:
  252. sets the default window size on the transport. (defaults to
  253. 2097152)
  254. :param int default_max_packet_size:
  255. sets the default max packet size on the transport. (defaults to
  256. 32768)
  257. .. versionchanged:: 1.15
  258. Added the ``default_window_size`` and ``default_max_packet_size``
  259. arguments.
  260. """
  261. self.active = False
  262. if isinstance(sock, string_types):
  263. # convert "host:port" into (host, port)
  264. hl = sock.split(':', 1)
  265. if len(hl) == 1:
  266. sock = (hl[0], 22)
  267. else:
  268. sock = (hl[0], int(hl[1]))
  269. if type(sock) is tuple:
  270. # connect to the given (host, port)
  271. hostname, port = sock
  272. reason = 'No suitable address family'
  273. addrinfos = socket.getaddrinfo(
  274. hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
  275. )
  276. for family, socktype, proto, canonname, sockaddr in addrinfos:
  277. if socktype == socket.SOCK_STREAM:
  278. af = family
  279. # addr = sockaddr
  280. sock = socket.socket(af, socket.SOCK_STREAM)
  281. try:
  282. retry_on_signal(lambda: sock.connect((hostname, port)))
  283. except socket.error as e:
  284. reason = str(e)
  285. else:
  286. break
  287. else:
  288. raise SSHException(
  289. 'Unable to connect to %s: %s' % (hostname, reason))
  290. # okay, normal socket-ish flow here...
  291. threading.Thread.__init__(self)
  292. self.setDaemon(True)
  293. self.sock = sock
  294. # we set the timeout so we can check self.active periodically to
  295. # see if we should bail. socket.timeout exception is never propagated.
  296. self.sock.settimeout(self._active_check_timeout)
  297. # negotiated crypto parameters
  298. self.packetizer = Packetizer(sock)
  299. self.local_version = 'SSH-' + self._PROTO_ID + '-' + self._CLIENT_ID
  300. self.remote_version = ''
  301. self.local_cipher = self.remote_cipher = ''
  302. self.local_kex_init = self.remote_kex_init = None
  303. self.local_mac = self.remote_mac = None
  304. self.local_compression = self.remote_compression = None
  305. self.session_id = None
  306. self.host_key_type = None
  307. self.host_key = None
  308. # GSS-API / SSPI Key Exchange
  309. self.use_gss_kex = gss_kex
  310. # This will be set to True if GSS-API Key Exchange was performed
  311. self.gss_kex_used = False
  312. self.kexgss_ctxt = None
  313. self.gss_host = None
  314. if self.use_gss_kex:
  315. self.kexgss_ctxt = GSSAuth("gssapi-keyex", gss_deleg_creds)
  316. self._preferred_kex = ('gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  317. 'gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  318. 'gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  319. 'diffie-hellman-group-exchange-sha1',
  320. 'diffie-hellman-group14-sha1',
  321. 'diffie-hellman-group1-sha1')
  322. # state used during negotiation
  323. self.kex_engine = None
  324. self.H = None
  325. self.K = None
  326. self.initial_kex_done = False
  327. self.in_kex = False
  328. self.authenticated = False
  329. self._expected_packet = tuple()
  330. # synchronization (always higher level than write_lock)
  331. self.lock = threading.Lock()
  332. # tracking open channels
  333. self._channels = ChannelMap()
  334. self.channel_events = {} # (id -> Event)
  335. self.channels_seen = {} # (id -> True)
  336. self._channel_counter = 0
  337. self.default_max_packet_size = default_max_packet_size
  338. self.default_window_size = default_window_size
  339. self._forward_agent_handler = None
  340. self._x11_handler = None
  341. self._tcp_handler = None
  342. self.saved_exception = None
  343. self.clear_to_send = threading.Event()
  344. self.clear_to_send_lock = threading.Lock()
  345. self.clear_to_send_timeout = 30.0
  346. self.log_name = 'paramiko.transport'
  347. self.logger = util.get_logger(self.log_name)
  348. self.packetizer.set_log(self.logger)
  349. self.auth_handler = None
  350. # response Message from an arbitrary global request
  351. self.global_response = None
  352. # user-defined event callbacks
  353. self.completion_event = None
  354. # how long (seconds) to wait for the SSH banner
  355. self.banner_timeout = 15
  356. # how long (seconds) to wait for the handshake to finish after SSH
  357. # banner sent.
  358. self.handshake_timeout = 15
  359. # how long (seconds) to wait for the auth response.
  360. self.auth_timeout = 30
  361. # server mode:
  362. self.server_mode = False
  363. self.server_object = None
  364. self.server_key_dict = {}
  365. self.server_accepts = []
  366. self.server_accept_cv = threading.Condition(self.lock)
  367. self.subsystem_table = {}
  368. def __repr__(self):
  369. """
  370. Returns a string representation of this object, for debugging.
  371. """
  372. out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
  373. if not self.active:
  374. out += ' (unconnected)'
  375. else:
  376. if self.local_cipher != '':
  377. out += ' (cipher %s, %d bits)' % (
  378. self.local_cipher,
  379. self._cipher_info[self.local_cipher]['key-size'] * 8
  380. )
  381. if self.is_authenticated():
  382. out += ' (active; %d open channel(s))' % len(self._channels)
  383. elif self.initial_kex_done:
  384. out += ' (connected; awaiting auth)'
  385. else:
  386. out += ' (connecting)'
  387. out += '>'
  388. return out
  389. def atfork(self):
  390. """
  391. Terminate this Transport without closing the session. On posix
  392. systems, if a Transport is open during process forking, both parent
  393. and child will share the underlying socket, but only one process can
  394. use the connection (without corrupting the session). Use this method
  395. to clean up a Transport object without disrupting the other process.
  396. .. versionadded:: 1.5.3
  397. """
  398. self.sock.close()
  399. self.close()
  400. def get_security_options(self):
  401. """
  402. Return a `.SecurityOptions` object which can be used to tweak the
  403. encryption algorithms this transport will permit (for encryption,
  404. digest/hash operations, public keys, and key exchanges) and the order
  405. of preference for them.
  406. """
  407. return SecurityOptions(self)
  408. def set_gss_host(self, gss_host):
  409. """
  410. Setter for C{gss_host} if GSS-API Key Exchange is performed.
  411. :param str gss_host: The targets name in the kerberos database
  412. Default: The name of the host to connect to
  413. """
  414. # We need the FQDN to get this working with SSPI
  415. self.gss_host = socket.getfqdn(gss_host)
  416. def start_client(self, event=None, timeout=None):
  417. """
  418. Negotiate a new SSH2 session as a client. This is the first step after
  419. creating a new `.Transport`. A separate thread is created for protocol
  420. negotiation.
  421. If an event is passed in, this method returns immediately. When
  422. negotiation is done (successful or not), the given ``Event`` will
  423. be triggered. On failure, `is_active` will return ``False``.
  424. (Since 1.4) If ``event`` is ``None``, this method will not return until
  425. negotiation is done. On success, the method returns normally.
  426. Otherwise an SSHException is raised.
  427. After a successful negotiation, you will usually want to authenticate,
  428. calling `auth_password <Transport.auth_password>` or
  429. `auth_publickey <Transport.auth_publickey>`.
  430. .. note:: `connect` is a simpler method for connecting as a client.
  431. .. note::
  432. After calling this method (or `start_server` or `connect`), you
  433. should no longer directly read from or write to the original socket
  434. object.
  435. :param .threading.Event event:
  436. an event to trigger when negotiation is complete (optional)
  437. :param float timeout:
  438. a timeout, in seconds, for SSH2 session negotiation (optional)
  439. :raises:
  440. `.SSHException` -- if negotiation fails (and no ``event`` was
  441. passed in)
  442. """
  443. self.active = True
  444. if event is not None:
  445. # async, return immediately and let the app poll for completion
  446. self.completion_event = event
  447. self.start()
  448. return
  449. # synchronous, wait for a result
  450. self.completion_event = event = threading.Event()
  451. self.start()
  452. max_time = time.time() + timeout if timeout is not None else None
  453. while True:
  454. event.wait(0.1)
  455. if not self.active:
  456. e = self.get_exception()
  457. if e is not None:
  458. raise e
  459. raise SSHException('Negotiation failed.')
  460. if (
  461. event.is_set() or
  462. (timeout is not None and time.time() >= max_time)
  463. ):
  464. break
  465. def start_server(self, event=None, server=None):
  466. """
  467. Negotiate a new SSH2 session as a server. This is the first step after
  468. creating a new `.Transport` and setting up your server host key(s). A
  469. separate thread is created for protocol negotiation.
  470. If an event is passed in, this method returns immediately. When
  471. negotiation is done (successful or not), the given ``Event`` will
  472. be triggered. On failure, `is_active` will return ``False``.
  473. (Since 1.4) If ``event`` is ``None``, this method will not return until
  474. negotiation is done. On success, the method returns normally.
  475. Otherwise an SSHException is raised.
  476. After a successful negotiation, the client will need to authenticate.
  477. Override the methods `get_allowed_auths
  478. <.ServerInterface.get_allowed_auths>`, `check_auth_none
  479. <.ServerInterface.check_auth_none>`, `check_auth_password
  480. <.ServerInterface.check_auth_password>`, and `check_auth_publickey
  481. <.ServerInterface.check_auth_publickey>` in the given ``server`` object
  482. to control the authentication process.
  483. After a successful authentication, the client should request to open a
  484. channel. Override `check_channel_request
  485. <.ServerInterface.check_channel_request>` in the given ``server``
  486. object to allow channels to be opened.
  487. .. note::
  488. After calling this method (or `start_client` or `connect`), you
  489. should no longer directly read from or write to the original socket
  490. object.
  491. :param .threading.Event event:
  492. an event to trigger when negotiation is complete.
  493. :param .ServerInterface server:
  494. an object used to perform authentication and create `channels
  495. <.Channel>`
  496. :raises:
  497. `.SSHException` -- if negotiation fails (and no ``event`` was
  498. passed in)
  499. """
  500. if server is None:
  501. server = ServerInterface()
  502. self.server_mode = True
  503. self.server_object = server
  504. self.active = True
  505. if event is not None:
  506. # async, return immediately and let the app poll for completion
  507. self.completion_event = event
  508. self.start()
  509. return
  510. # synchronous, wait for a result
  511. self.completion_event = event = threading.Event()
  512. self.start()
  513. while True:
  514. event.wait(0.1)
  515. if not self.active:
  516. e = self.get_exception()
  517. if e is not None:
  518. raise e
  519. raise SSHException('Negotiation failed.')
  520. if event.is_set():
  521. break
  522. def add_server_key(self, key):
  523. """
  524. Add a host key to the list of keys used for server mode. When behaving
  525. as a server, the host key is used to sign certain packets during the
  526. SSH2 negotiation, so that the client can trust that we are who we say
  527. we are. Because this is used for signing, the key must contain private
  528. key info, not just the public half. Only one key of each type (RSA or
  529. DSS) is kept.
  530. :param .PKey key:
  531. the host key to add, usually an `.RSAKey` or `.DSSKey`.
  532. """
  533. self.server_key_dict[key.get_name()] = key
  534. def get_server_key(self):
  535. """
  536. Return the active host key, in server mode. After negotiating with the
  537. client, this method will return the negotiated host key. If only one
  538. type of host key was set with `add_server_key`, that's the only key
  539. that will ever be returned. But in cases where you have set more than
  540. one type of host key (for example, an RSA key and a DSS key), the key
  541. type will be negotiated by the client, and this method will return the
  542. key of the type agreed on. If the host key has not been negotiated
  543. yet, ``None`` is returned. In client mode, the behavior is undefined.
  544. :return:
  545. host key (`.PKey`) of the type negotiated by the client, or
  546. ``None``.
  547. """
  548. try:
  549. return self.server_key_dict[self.host_key_type]
  550. except KeyError:
  551. pass
  552. return None
  553. @staticmethod
  554. def load_server_moduli(filename=None):
  555. """
  556. (optional)
  557. Load a file of prime moduli for use in doing group-exchange key
  558. negotiation in server mode. It's a rather obscure option and can be
  559. safely ignored.
  560. In server mode, the remote client may request "group-exchange" key
  561. negotiation, which asks the server to send a random prime number that
  562. fits certain criteria. These primes are pretty difficult to compute,
  563. so they can't be generated on demand. But many systems contain a file
  564. of suitable primes (usually named something like ``/etc/ssh/moduli``).
  565. If you call `load_server_moduli` and it returns ``True``, then this
  566. file of primes has been loaded and we will support "group-exchange" in
  567. server mode. Otherwise server mode will just claim that it doesn't
  568. support that method of key negotiation.
  569. :param str filename:
  570. optional path to the moduli file, if you happen to know that it's
  571. not in a standard location.
  572. :return:
  573. True if a moduli file was successfully loaded; False otherwise.
  574. .. note:: This has no effect when used in client mode.
  575. """
  576. Transport._modulus_pack = ModulusPack()
  577. # places to look for the openssh "moduli" file
  578. file_list = ['/etc/ssh/moduli', '/usr/local/etc/moduli']
  579. if filename is not None:
  580. file_list.insert(0, filename)
  581. for fn in file_list:
  582. try:
  583. Transport._modulus_pack.read_file(fn)
  584. return True
  585. except IOError:
  586. pass
  587. # none succeeded
  588. Transport._modulus_pack = None
  589. return False
  590. def close(self):
  591. """
  592. Close this session, and any open channels that are tied to it.
  593. """
  594. if not self.active:
  595. return
  596. self.stop_thread()
  597. for chan in list(self._channels.values()):
  598. chan._unlink()
  599. self.sock.close()
  600. def get_remote_server_key(self):
  601. """
  602. Return the host key of the server (in client mode).
  603. .. note::
  604. Previously this call returned a tuple of ``(key type, key
  605. string)``. You can get the same effect by calling `.PKey.get_name`
  606. for the key type, and ``str(key)`` for the key string.
  607. :raises: `.SSHException` -- if no session is currently active.
  608. :return: public key (`.PKey`) of the remote server
  609. """
  610. if (not self.active) or (not self.initial_kex_done):
  611. raise SSHException('No existing session')
  612. return self.host_key
  613. def is_active(self):
  614. """
  615. Return true if this session is active (open).
  616. :return:
  617. True if the session is still active (open); False if the session is
  618. closed
  619. """
  620. return self.active
  621. def open_session(
  622. self,
  623. window_size=None,
  624. max_packet_size=None,
  625. timeout=None,
  626. ):
  627. """
  628. Request a new channel to the server, of type ``"session"``. This is
  629. just an alias for calling `open_channel` with an argument of
  630. ``"session"``.
  631. .. note:: Modifying the the window and packet sizes might have adverse
  632. effects on the session created. The default values are the same
  633. as in the OpenSSH code base and have been battle tested.
  634. :param int window_size:
  635. optional window size for this session.
  636. :param int max_packet_size:
  637. optional max packet size for this session.
  638. :return: a new `.Channel`
  639. :raises:
  640. `.SSHException` -- if the request is rejected or the session ends
  641. prematurely
  642. .. versionchanged:: 1.13.4/1.14.3/1.15.3
  643. Added the ``timeout`` argument.
  644. .. versionchanged:: 1.15
  645. Added the ``window_size`` and ``max_packet_size`` arguments.
  646. """
  647. return self.open_channel('session',
  648. window_size=window_size,
  649. max_packet_size=max_packet_size,
  650. timeout=timeout)
  651. def open_x11_channel(self, src_addr=None):
  652. """
  653. Request a new channel to the client, of type ``"x11"``. This
  654. is just an alias for ``open_channel('x11', src_addr=src_addr)``.
  655. :param tuple src_addr:
  656. the source address (``(str, int)``) of the x11 server (port is the
  657. x11 port, ie. 6010)
  658. :return: a new `.Channel`
  659. :raises:
  660. `.SSHException` -- if the request is rejected or the session ends
  661. prematurely
  662. """
  663. return self.open_channel('x11', src_addr=src_addr)
  664. def open_forward_agent_channel(self):
  665. """
  666. Request a new channel to the client, of type
  667. ``"auth-agent@openssh.com"``.
  668. This is just an alias for ``open_channel('auth-agent@openssh.com')``.
  669. :return: a new `.Channel`
  670. :raises: `.SSHException` --
  671. if the request is rejected or the session ends prematurely
  672. """
  673. return self.open_channel('auth-agent@openssh.com')
  674. def open_forwarded_tcpip_channel(self, src_addr, dest_addr):
  675. """
  676. Request a new channel back to the client, of type ``forwarded-tcpip``.
  677. This is used after a client has requested port forwarding, for sending
  678. incoming connections back to the client.
  679. :param src_addr: originator's address
  680. :param dest_addr: local (server) connected address
  681. """
  682. return self.open_channel('forwarded-tcpip', dest_addr, src_addr)
  683. def open_channel(self,
  684. kind,
  685. dest_addr=None,
  686. src_addr=None,
  687. window_size=None,
  688. max_packet_size=None,
  689. timeout=None):
  690. """
  691. Request a new channel to the server. `Channels <.Channel>` are
  692. socket-like objects used for the actual transfer of data across the
  693. session. You may only request a channel after negotiating encryption
  694. (using `connect` or `start_client`) and authenticating.
  695. .. note:: Modifying the the window and packet sizes might have adverse
  696. effects on the channel created. The default values are the same
  697. as in the OpenSSH code base and have been battle tested.
  698. :param str kind:
  699. the kind of channel requested (usually ``"session"``,
  700. ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``)
  701. :param tuple dest_addr:
  702. the destination address (address + port tuple) of this port
  703. forwarding, if ``kind`` is ``"forwarded-tcpip"`` or
  704. ``"direct-tcpip"`` (ignored for other channel types)
  705. :param src_addr: the source address of this port forwarding, if
  706. ``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``
  707. :param int window_size:
  708. optional window size for this session.
  709. :param int max_packet_size:
  710. optional max packet size for this session.
  711. :param float timeout:
  712. optional timeout opening a channel, default 3600s (1h)
  713. :return: a new `.Channel` on success
  714. :raises:
  715. `.SSHException` -- if the request is rejected, the session ends
  716. prematurely or there is a timeout openning a channel
  717. .. versionchanged:: 1.15
  718. Added the ``window_size`` and ``max_packet_size`` arguments.
  719. """
  720. if not self.active:
  721. raise SSHException('SSH session not active')
  722. timeout = 3600 if timeout is None else timeout
  723. self.lock.acquire()
  724. try:
  725. window_size = self._sanitize_window_size(window_size)
  726. max_packet_size = self._sanitize_packet_size(max_packet_size)
  727. chanid = self._next_channel()
  728. m = Message()
  729. m.add_byte(cMSG_CHANNEL_OPEN)
  730. m.add_string(kind)
  731. m.add_int(chanid)
  732. m.add_int(window_size)
  733. m.add_int(max_packet_size)
  734. if (kind == 'forwarded-tcpip') or (kind == 'direct-tcpip'):
  735. m.add_string(dest_addr[0])
  736. m.add_int(dest_addr[1])
  737. m.add_string(src_addr[0])
  738. m.add_int(src_addr[1])
  739. elif kind == 'x11':
  740. m.add_string(src_addr[0])
  741. m.add_int(src_addr[1])
  742. chan = Channel(chanid)
  743. self._channels.put(chanid, chan)
  744. self.channel_events[chanid] = event = threading.Event()
  745. self.channels_seen[chanid] = True
  746. chan._set_transport(self)
  747. chan._set_window(window_size, max_packet_size)
  748. finally:
  749. self.lock.release()
  750. self._send_user_message(m)
  751. start_ts = time.time()
  752. while True:
  753. event.wait(0.1)
  754. if not self.active:
  755. e = self.get_exception()
  756. if e is None:
  757. e = SSHException('Unable to open channel.')
  758. raise e
  759. if event.is_set():
  760. break
  761. elif start_ts + timeout < time.time():
  762. raise SSHException('Timeout openning channel.')
  763. chan = self._channels.get(chanid)
  764. if chan is not None:
  765. return chan
  766. e = self.get_exception()
  767. if e is None:
  768. e = SSHException('Unable to open channel.')
  769. raise e
  770. def request_port_forward(self, address, port, handler=None):
  771. """
  772. Ask the server to forward TCP connections from a listening port on
  773. the server, across this SSH session.
  774. If a handler is given, that handler is called from a different thread
  775. whenever a forwarded connection arrives. The handler parameters are::
  776. handler(
  777. channel,
  778. (origin_addr, origin_port),
  779. (server_addr, server_port),
  780. )
  781. where ``server_addr`` and ``server_port`` are the address and port that
  782. the server was listening on.
  783. If no handler is set, the default behavior is to send new incoming
  784. forwarded connections into the accept queue, to be picked up via
  785. `accept`.
  786. :param str address: the address to bind when forwarding
  787. :param int port:
  788. the port to forward, or 0 to ask the server to allocate any port
  789. :param callable handler:
  790. optional handler for incoming forwarded connections, of the form
  791. ``func(Channel, (str, int), (str, int))``.
  792. :return: the port number (`int`) allocated by the server
  793. :raises:
  794. `.SSHException` -- if the server refused the TCP forward request
  795. """
  796. if not self.active:
  797. raise SSHException('SSH session not active')
  798. port = int(port)
  799. response = self.global_request(
  800. 'tcpip-forward', (address, port), wait=True
  801. )
  802. if response is None:
  803. raise SSHException('TCP forwarding request denied')
  804. if port == 0:
  805. port = response.get_int()
  806. if handler is None:
  807. def default_handler(channel, src_addr, dest_addr_port):
  808. # src_addr, src_port = src_addr_port
  809. # dest_addr, dest_port = dest_addr_port
  810. self._queue_incoming_channel(channel)
  811. handler = default_handler
  812. self._tcp_handler = handler
  813. return port
  814. def cancel_port_forward(self, address, port):
  815. """
  816. Ask the server to cancel a previous port-forwarding request. No more
  817. connections to the given address & port will be forwarded across this
  818. ssh connection.
  819. :param str address: the address to stop forwarding
  820. :param int port: the port to stop forwarding
  821. """
  822. if not self.active:
  823. return
  824. self._tcp_handler = None
  825. self.global_request('cancel-tcpip-forward', (address, port), wait=True)
  826. def open_sftp_client(self):
  827. """
  828. Create an SFTP client channel from an open transport. On success, an
  829. SFTP session will be opened with the remote host, and a new
  830. `.SFTPClient` object will be returned.
  831. :return:
  832. a new `.SFTPClient` referring to an sftp session (channel) across
  833. this transport
  834. """
  835. return SFTPClient.from_transport(self)
  836. def send_ignore(self, byte_count=None):
  837. """
  838. Send a junk packet across the encrypted link. This is sometimes used
  839. to add "noise" to a connection to confuse would-be attackers. It can
  840. also be used as a keep-alive for long lived connections traversing
  841. firewalls.
  842. :param int byte_count:
  843. the number of random bytes to send in the payload of the ignored
  844. packet -- defaults to a random number from 10 to 41.
  845. """
  846. m = Message()
  847. m.add_byte(cMSG_IGNORE)
  848. if byte_count is None:
  849. byte_count = (byte_ord(os.urandom(1)) % 32) + 10
  850. m.add_bytes(os.urandom(byte_count))
  851. self._send_user_message(m)
  852. def renegotiate_keys(self):
  853. """
  854. Force this session to switch to new keys. Normally this is done
  855. automatically after the session hits a certain number of packets or
  856. bytes sent or received, but this method gives you the option of forcing
  857. new keys whenever you want. Negotiating new keys causes a pause in
  858. traffic both ways as the two sides swap keys and do computations. This
  859. method returns when the session has switched to new keys.
  860. :raises:
  861. `.SSHException` -- if the key renegotiation failed (which causes
  862. the session to end)
  863. """
  864. self.completion_event = threading.Event()
  865. self._send_kex_init()
  866. while True:
  867. self.completion_event.wait(0.1)
  868. if not self.active:
  869. e = self.get_exception()
  870. if e is not None:
  871. raise e
  872. raise SSHException('Negotiation failed.')
  873. if self.completion_event.is_set():
  874. break
  875. return
  876. def set_keepalive(self, interval):
  877. """
  878. Turn on/off keepalive packets (default is off). If this is set, after
  879. ``interval`` seconds without sending any data over the connection, a
  880. "keepalive" packet will be sent (and ignored by the remote host). This
  881. can be useful to keep connections alive over a NAT, for example.
  882. :param int interval:
  883. seconds to wait before sending a keepalive packet (or
  884. 0 to disable keepalives).
  885. """
  886. def _request(x=weakref.proxy(self)):
  887. return x.global_request('keepalive@lag.net', wait=False)
  888. self.packetizer.set_keepalive(interval, _request)
  889. def global_request(self, kind, data=None, wait=True):
  890. """
  891. Make a global request to the remote host. These are normally
  892. extensions to the SSH2 protocol.
  893. :param str kind: name of the request.
  894. :param tuple data:
  895. an optional tuple containing additional data to attach to the
  896. request.
  897. :param bool wait:
  898. ``True`` if this method should not return until a response is
  899. received; ``False`` otherwise.
  900. :return:
  901. a `.Message` containing possible additional data if the request was
  902. successful (or an empty `.Message` if ``wait`` was ``False``);
  903. ``None`` if the request was denied.
  904. """
  905. if wait:
  906. self.completion_event = threading.Event()
  907. m = Message()
  908. m.add_byte(cMSG_GLOBAL_REQUEST)
  909. m.add_string(kind)
  910. m.add_boolean(wait)
  911. if data is not None:
  912. m.add(*data)
  913. self._log(DEBUG, 'Sending global request "%s"' % kind)
  914. self._send_user_message(m)
  915. if not wait:
  916. return None
  917. while True:
  918. self.completion_event.wait(0.1)
  919. if not self.active:
  920. return None
  921. if self.completion_event.is_set():
  922. break
  923. return self.global_response
  924. def accept(self, timeout=None):
  925. """
  926. Return the next channel opened by the client over this transport, in
  927. server mode. If no channel is opened before the given timeout,
  928. ``None`` is returned.
  929. :param int timeout:
  930. seconds to wait for a channel, or ``None`` to wait forever
  931. :return: a new `.Channel` opened by the client
  932. """
  933. self.lock.acquire()
  934. try:
  935. if len(self.server_accepts) > 0:
  936. chan = self.server_accepts.pop(0)
  937. else:
  938. self.server_accept_cv.wait(timeout)
  939. if len(self.server_accepts) > 0:
  940. chan = self.server_accepts.pop(0)
  941. else:
  942. # timeout
  943. chan = None
  944. finally:
  945. self.lock.release()
  946. return chan
  947. def connect(
  948. self,
  949. hostkey=None,
  950. username='',
  951. password=None,
  952. pkey=None,
  953. gss_host=None,
  954. gss_auth=False,
  955. gss_kex=False,
  956. gss_deleg_creds=True,
  957. ):
  958. """
  959. Negotiate an SSH2 session, and optionally verify the server's host key
  960. and authenticate using a password or private key. This is a shortcut
  961. for `start_client`, `get_remote_server_key`, and
  962. `Transport.auth_password` or `Transport.auth_publickey`. Use those
  963. methods if you want more control.
  964. You can use this method immediately after creating a Transport to
  965. negotiate encryption with a server. If it fails, an exception will be
  966. thrown. On success, the method will return cleanly, and an encrypted
  967. session exists. You may immediately call `open_channel` or
  968. `open_session` to get a `.Channel` object, which is used for data
  969. transfer.
  970. .. note::
  971. If you fail to supply a password or private key, this method may
  972. succeed, but a subsequent `open_channel` or `open_session` call may
  973. fail because you haven't authenticated yet.
  974. :param .PKey hostkey:
  975. the host key expected from the server, or ``None`` if you don't
  976. want to do host key verification.
  977. :param str username: the username to authenticate as.
  978. :param str password:
  979. a password to use for authentication, if you want to use password
  980. authentication; otherwise ``None``.
  981. :param .PKey pkey:
  982. a private key to use for authentication, if you want to use private
  983. key authentication; otherwise ``None``.
  984. :param str gss_host:
  985. The target's name in the kerberos database. Default: hostname
  986. :param bool gss_auth:
  987. ``True`` if you want to use GSS-API authentication.
  988. :param bool gss_kex:
  989. Perform GSS-API Key Exchange and user authentication.
  990. :param bool gss_deleg_creds:
  991. Whether to delegate GSS-API client credentials.
  992. :raises: `.SSHException` -- if the SSH2 negotiation fails, the host key
  993. supplied by the server is incorrect, or authentication fails.
  994. """
  995. if hostkey is not None:
  996. self._preferred_keys = [hostkey.get_name()]
  997. self.start_client()
  998. # check host key if we were given one
  999. # If GSS-API Key Exchange was performed, we are not required to check
  1000. # the host key.
  1001. if (hostkey is not None) and not gss_kex:
  1002. key = self.get_remote_server_key()
  1003. if (
  1004. key.get_name() != hostkey.get_name() or
  1005. key.asbytes() != hostkey.asbytes()
  1006. ):
  1007. self._log(DEBUG, 'Bad host key from server')
  1008. self._log(DEBUG, 'Expected: %s: %s' % (
  1009. hostkey.get_name(), repr(hostkey.asbytes()))
  1010. )
  1011. self._log(DEBUG, 'Got : %s: %s' % (
  1012. key.get_name(), repr(key.asbytes()))
  1013. )
  1014. raise SSHException('Bad host key from server')
  1015. self._log(DEBUG, 'Host key verified (%s)' % hostkey.get_name())
  1016. if (pkey is not None) or (password is not None) or gss_auth or gss_kex:
  1017. if gss_auth:
  1018. self._log(DEBUG, 'Attempting GSS-API auth... (gssapi-with-mic)') # noqa
  1019. self.auth_gssapi_with_mic(username, gss_host, gss_deleg_creds)
  1020. elif gss_kex:
  1021. self._log(DEBUG, 'Attempting GSS-API auth... (gssapi-keyex)')
  1022. self.auth_gssapi_keyex(username)
  1023. elif pkey is not None:
  1024. self._log(DEBUG, 'Attempting public-key auth...')
  1025. self.auth_publickey(username, pkey)
  1026. else:
  1027. self._log(DEBUG, 'Attempting password auth...')
  1028. self.auth_password(username, password)
  1029. return
  1030. def get_exception(self):
  1031. """
  1032. Return any exception that happened during the last server request.
  1033. This can be used to fetch more specific error information after using
  1034. calls like `start_client`. The exception (if any) is cleared after
  1035. this call.
  1036. :return:
  1037. an exception, or ``None`` if there is no stored exception.
  1038. .. versionadded:: 1.1
  1039. """
  1040. self.lock.acquire()
  1041. try:
  1042. e = self.saved_exception
  1043. self.saved_exception = None
  1044. return e
  1045. finally:
  1046. self.lock.release()
  1047. def set_subsystem_handler(self, name, handler, *larg, **kwarg):
  1048. """
  1049. Set the handler class for a subsystem in server mode. If a request
  1050. for this subsystem is made on an open ssh channel later, this handler
  1051. will be constructed and called -- see `.SubsystemHandler` for more
  1052. detailed documentation.
  1053. Any extra parameters (including keyword arguments) are saved and
  1054. passed to the `.SubsystemHandler` constructor later.
  1055. :param str name: name of the subsystem.
  1056. :param handler:
  1057. subclass of `.SubsystemHandler` that handles this subsystem.
  1058. """
  1059. try:
  1060. self.lock.acquire()
  1061. self.subsystem_table[name] = (handler, larg, kwarg)
  1062. finally:
  1063. self.lock.release()
  1064. def is_authenticated(self):
  1065. """
  1066. Return true if this session is active and authenticated.
  1067. :return:
  1068. True if the session is still open and has been authenticated
  1069. successfully; False if authentication failed and/or the session is
  1070. closed.
  1071. """
  1072. return (
  1073. self.active and
  1074. self.auth_handler is not None and
  1075. self.auth_handler.is_authenticated()
  1076. )
  1077. def get_username(self):
  1078. """
  1079. Return the username this connection is authenticated for. If the
  1080. session is not authenticated (or authentication failed), this method
  1081. returns ``None``.
  1082. :return: username that was authenticated (a `str`), or ``None``.
  1083. """
  1084. if not self.active or (self.auth_handler is None):
  1085. return None
  1086. return self.auth_handler.get_username()
  1087. def get_banner(self):
  1088. """
  1089. Return the banner supplied by the server upon connect. If no banner is
  1090. supplied, this method returns ``None``.
  1091. :returns: server supplied banner (`str`), or ``None``.
  1092. .. versionadded:: 1.13
  1093. """
  1094. if not self.active or (self.auth_handler is None):
  1095. return None
  1096. return self.auth_handler.banner
  1097. def auth_none(self, username):
  1098. """
  1099. Try to authenticate to the server using no authentication at all.
  1100. This will almost always fail. It may be useful for determining the
  1101. list of authentication types supported by the server, by catching the
  1102. `.BadAuthenticationType` exception raised.
  1103. :param str username: the username to authenticate as
  1104. :return:
  1105. `list` of auth types permissible for the next stage of
  1106. authentication (normally empty)
  1107. :raises:
  1108. `.BadAuthenticationType` -- if "none" authentication isn't allowed
  1109. by the server for this user
  1110. :raises:
  1111. `.SSHException` -- if the authentication failed due to a network
  1112. error
  1113. .. versionadded:: 1.5
  1114. """
  1115. if (not self.active) or (not self.initial_kex_done):
  1116. raise SSHException('No existing session')
  1117. my_event = threading.Event()
  1118. self.auth_handler = AuthHandler(self)
  1119. self.auth_handler.auth_none(username, my_event)
  1120. return self.auth_handler.wait_for_response(my_event)
  1121. def auth_password(self, username, password, event=None, fallback=True):
  1122. """
  1123. Authenticate to the server using a password. The username and password
  1124. are sent over an encrypted link.
  1125. If an ``event`` is passed in, this method will return immediately, and
  1126. the event will be triggered once authentication succeeds or fails. On
  1127. success, `is_authenticated` will return ``True``. On failure, you may
  1128. use `get_exception` to get more detailed error information.
  1129. Since 1.1, if no event is passed, this method will block until the
  1130. authentication succeeds or fails. On failure, an exception is raised.
  1131. Otherwise, the method simply returns.
  1132. Since 1.5, if no event is passed and ``fallback`` is ``True`` (the
  1133. default), if the server doesn't support plain password authentication
  1134. but does support so-called "keyboard-interactive" mode, an attempt
  1135. will be made to authenticate using this interactive mode. If it fails,
  1136. the normal exception will be thrown as if the attempt had never been
  1137. made. This is useful for some recent Gentoo and Debian distributions,
  1138. which turn off plain password authentication in a misguided belief
  1139. that interactive authentication is "more secure". (It's not.)
  1140. If the server requires multi-step authentication (which is very rare),
  1141. this method will return a list of auth types permissible for the next
  1142. step. Otherwise, in the normal case, an empty list is returned.
  1143. :param str username: the username to authenticate as
  1144. :param basestring password: the password to authenticate with
  1145. :param .threading.Event event:
  1146. an event to trigger when the authentication attempt is complete
  1147. (whether it was successful or not)
  1148. :param bool fallback:
  1149. ``True`` if an attempt at an automated "interactive" password auth
  1150. should be made if the server doesn't support normal password auth
  1151. :return:
  1152. `list` of auth types permissible for the next stage of
  1153. authentication (normally empty)
  1154. :raises:
  1155. `.BadAuthenticationType` -- if password authentication isn't
  1156. allowed by the server for this user (and no event was passed in)
  1157. :raises:
  1158. `.AuthenticationException` -- if the authentication failed (and no
  1159. event was passed in)
  1160. :raises: `.SSHException` -- if there was a network error
  1161. """
  1162. if (not self.active) or (not self.initial_kex_done):
  1163. # we should never try to send the password unless we're on a secure
  1164. # link
  1165. raise SSHException('No existing session')
  1166. if event is None:
  1167. my_event = threading.Event()
  1168. else:
  1169. my_event = event
  1170. self.auth_handler = AuthHandler(self)
  1171. self.auth_handler.auth_password(username, password, my_event)
  1172. if event is not None:
  1173. # caller wants to wait for event themselves
  1174. return []
  1175. try:
  1176. return self.auth_handler.wait_for_response(my_event)
  1177. except BadAuthenticationType as e:
  1178. # if password auth isn't allowed, but keyboard-interactive *is*,
  1179. # try to fudge it
  1180. if not fallback or ('keyboard-interactive' not in e.allowed_types):
  1181. raise
  1182. try:
  1183. def handler(title, instructions, fields):
  1184. if len(fields) > 1:
  1185. raise SSHException('Fallback authentication failed.')
  1186. if len(fields) == 0:
  1187. # for some reason, at least on os x, a 2nd request will
  1188. # be made with zero fields requested. maybe it's just
  1189. # to try to fake out automated scripting of the exact
  1190. # type we're doing here. *shrug* :)
  1191. return []
  1192. return [password]
  1193. return self.auth_interactive(username, handler)
  1194. except SSHException:
  1195. # attempt failed; just raise the original exception
  1196. raise e
  1197. def auth_publickey(self, username, key, event=None):
  1198. """
  1199. Authenticate to the server using a private key. The key is used to
  1200. sign data from the server, so it must include the private part.
  1201. If an ``event`` is passed in, this method will return immediately, and
  1202. the event will be triggered once authentication succeeds or fails. On
  1203. success, `is_authenticated` will return ``True``. On failure, you may
  1204. use `get_exception` to get more detailed error information.
  1205. Since 1.1, if no event is passed, this method will block until the
  1206. authentication succeeds or fails. On failure, an exception is raised.
  1207. Otherwise, the method simply returns.
  1208. If the server requires multi-step authentication (which is very rare),
  1209. this method will return a list of auth types permissible for the next
  1210. step. Otherwise, in the normal case, an empty list is returned.
  1211. :param str username: the username to authenticate as
  1212. :param .PKey key: the private key to authenticate with
  1213. :param .threading.Event event:
  1214. an event to trigger when the authentication attempt is complete
  1215. (whether it was successful or not)
  1216. :return:
  1217. `list` of auth types permissible for the next stage of
  1218. authentication (normally empty)
  1219. :raises:
  1220. `.BadAuthenticationType` -- if public-key authentication isn't
  1221. allowed by the server for this user (and no event was passed in)
  1222. :raises:
  1223. `.AuthenticationException` -- if the authentication failed (and no
  1224. event was passed in)
  1225. :raises: `.SSHException` -- if there was a network error
  1226. """
  1227. if (not self.active) or (not self.initial_kex_done):
  1228. # we should never try to authenticate unless we're on a secure link
  1229. raise SSHException('No existing session')
  1230. if event is None:
  1231. my_event = threading.Event()
  1232. else:
  1233. my_event = event
  1234. self.auth_handler = AuthHandler(self)
  1235. self.auth_handler.auth_publickey(username, key, my_event)
  1236. if event is not None:
  1237. # caller wants to wait for event themselves
  1238. return []
  1239. return self.auth_handler.wait_for_response(my_event)
  1240. def auth_interactive(self, username, handler, submethods=''):
  1241. """
  1242. Authenticate to the server interactively. A handler is used to answer
  1243. arbitrary questions from the server. On many servers, this is just a
  1244. dumb wrapper around PAM.
  1245. This method will block until the authentication succeeds or fails,
  1246. peroidically calling the handler asynchronously to get answers to
  1247. authentication questions. The handler may be called more than once
  1248. if the server continues to ask questions.
  1249. The handler is expected to be a callable that will handle calls of the
  1250. form: ``handler(title, instructions, prompt_list)``. The ``title`` is
  1251. meant to be a dialog-window title, and the ``instructions`` are user
  1252. instructions (both are strings). ``prompt_list`` will be a list of
  1253. prompts, each prompt being a tuple of ``(str, bool)``. The string is
  1254. the prompt and the boolean indicates whether the user text should be
  1255. echoed.
  1256. A sample call would thus be:
  1257. ``handler('title', 'instructions', [('Password:', False)])``.
  1258. The handler should return a list or tuple of answers to the server's
  1259. questions.
  1260. If the server requires multi-step authentication (which is very rare),
  1261. this method will return a list of auth types permissible for the next
  1262. step. Otherwise, in the normal case, an empty list is returned.
  1263. :param str username: the username to authenticate as
  1264. :param callable handler: a handler for responding to server questions
  1265. :param str submethods: a string list of desired submethods (optional)
  1266. :return:
  1267. `list` of auth types permissible for the next stage of
  1268. authentication (normally empty).
  1269. :raises: `.BadAuthenticationType` -- if public-key authentication isn't
  1270. allowed by the server for this user
  1271. :raises: `.AuthenticationException` -- if the authentication failed
  1272. :raises: `.SSHException` -- if there was a network error
  1273. .. versionadded:: 1.5
  1274. """
  1275. if (not self.active) or (not self.initial_kex_done):
  1276. # we should never try to authenticate unless we're on a secure link
  1277. raise SSHException('No existing session')
  1278. my_event = threading.Event()
  1279. self.auth_handler = AuthHandler(self)
  1280. self.auth_handler.auth_interactive(
  1281. username, handler, my_event, submethods
  1282. )
  1283. return self.auth_handler.wait_for_response(my_event)
  1284. def auth_interactive_dumb(self, username, handler=None, submethods=''):
  1285. """
  1286. Autenticate to the server interactively but dumber.
  1287. Just print the prompt and / or instructions to stdout and send back
  1288. the response. This is good for situations where partial auth is
  1289. achieved by key and then the user has to enter a 2fac token.
  1290. """
  1291. if not handler:
  1292. def handler(title, instructions, prompt_list):
  1293. answers = []
  1294. if title:
  1295. print(title.strip())
  1296. if instructions:
  1297. print(instructions.strip())
  1298. for prompt, show_input in prompt_list:
  1299. print(prompt.strip(), end=' ')
  1300. answers.append(input())
  1301. return answers
  1302. return self.auth_interactive(username, handler, submethods)
  1303. def auth_gssapi_with_mic(self, username, gss_host, gss_deleg_creds):
  1304. """
  1305. Authenticate to the Server using GSS-API / SSPI.
  1306. :param str username: The username to authenticate as
  1307. :param str gss_host: The target host
  1308. :param bool gss_deleg_creds: Delegate credentials or not
  1309. :return: list of auth types permissible for the next stage of
  1310. authentication (normally empty)
  1311. :rtype: list
  1312. :raises: `.BadAuthenticationType` -- if gssapi-with-mic isn't
  1313. allowed by the server (and no event was passed in)
  1314. :raises:
  1315. `.AuthenticationException` -- if the authentication failed (and no
  1316. event was passed in)
  1317. :raises: `.SSHException` -- if there was a network error
  1318. """
  1319. if (not self.active) or (not self.initial_kex_done):
  1320. # we should never try to authenticate unless we're on a secure link
  1321. raise SSHException('No existing session')
  1322. my_event = threading.Event()
  1323. self.auth_handler = AuthHandler(self)
  1324. self.auth_handler.auth_gssapi_with_mic(
  1325. username, gss_host, gss_deleg_creds, my_event
  1326. )
  1327. return self.auth_handler.wait_for_response(my_event)
  1328. def auth_gssapi_keyex(self, username):
  1329. """
  1330. Authenticate to the server with GSS-API/SSPI if GSS-API kex is in use.
  1331. :param str username: The username to authenticate as.
  1332. :returns:
  1333. a `list` of auth types permissible for the next stage of
  1334. authentication (normally empty)
  1335. :raises: `.BadAuthenticationType` --
  1336. if GSS-API Key Exchange was not performed (and no event was passed
  1337. in)
  1338. :raises: `.AuthenticationException` --
  1339. if the authentication failed (and no event was passed in)
  1340. :raises: `.SSHException` -- if there was a network error
  1341. """
  1342. if (not self.active) or (not self.initial_kex_done):
  1343. # we should never try to authenticate unless we're on a secure link
  1344. raise SSHException('No existing session')
  1345. my_event = threading.Event()
  1346. self.auth_handler = AuthHandler(self)
  1347. self.auth_handler.auth_gssapi_keyex(username, my_event)
  1348. return self.auth_handler.wait_for_response(my_event)
  1349. def set_log_channel(self, name):
  1350. """
  1351. Set the channel for this transport's logging. The default is
  1352. ``"paramiko.transport"`` but it can be set to anything you want. (See
  1353. the `.logging` module for more info.) SSH Channels will log to a
  1354. sub-channel of the one specified.
  1355. :param str name: new channel name for logging
  1356. .. versionadded:: 1.1
  1357. """
  1358. self.log_name = name
  1359. self.logger = util.get_logger(name)
  1360. self.packetizer.set_log(self.logger)
  1361. def get_log_channel(self):
  1362. """
  1363. Return the channel name used for this transport's logging.
  1364. :return: channel name as a `str`
  1365. .. versionadded:: 1.2
  1366. """
  1367. return self.log_name
  1368. def set_hexdump(self, hexdump):
  1369. """
  1370. Turn on/off logging a hex dump of protocol traffic at DEBUG level in
  1371. the logs. Normally you would want this off (which is the default),
  1372. but if you are debugging something, it may be useful.
  1373. :param bool hexdump:
  1374. ``True`` to log protocol traffix (in hex) to the log; ``False``
  1375. otherwise.
  1376. """
  1377. self.packetizer.set_hexdump(hexdump)
  1378. def get_hexdump(self):
  1379. """
  1380. Return ``True`` if the transport is currently logging hex dumps of
  1381. protocol traffic.
  1382. :return: ``True`` if hex dumps are being logged, else ``False``.
  1383. .. versionadded:: 1.4
  1384. """
  1385. return self.packetizer.get_hexdump()
  1386. def use_compression(self, compress=True):
  1387. """
  1388. Turn on/off compression. This will only have an affect before starting
  1389. the transport (ie before calling `connect`, etc). By default,
  1390. compression is off since it negatively affects interactive sessions.
  1391. :param bool compress:
  1392. ``True`` to ask the remote client/server to compress traffic;
  1393. ``False`` to refuse compression
  1394. .. versionadded:: 1.5.2
  1395. """
  1396. if compress:
  1397. self._preferred_compression = ('zlib@openssh.com', 'zlib', 'none')
  1398. else:
  1399. self._preferred_compression = ('none',)
  1400. def getpeername(self):
  1401. """
  1402. Return the address of the remote side of this Transport, if possible.
  1403. This is effectively a wrapper around ``getpeername`` on the underlying
  1404. socket. If the socket-like object has no ``getpeername`` method, then
  1405. ``("unknown", 0)`` is returned.
  1406. :return:
  1407. the address of the remote host, if known, as a ``(str, int)``
  1408. tuple.
  1409. """
  1410. gp = getattr(self.sock, 'getpeername', None)
  1411. if gp is None:
  1412. return 'unknown', 0
  1413. return gp()
  1414. def stop_thread(self):
  1415. self.active = False
  1416. self.packetizer.close()
  1417. if PY2:
  1418. # Original join logic; #520 doesn't appear commonly present under
  1419. # Python 2.
  1420. while self.is_alive() and self is not threading.current_thread():
  1421. self.join(10)
  1422. else:
  1423. # Keep trying to join() our main thread, quickly, until:
  1424. # * We join()ed successfully (self.is_alive() == False)
  1425. # * Or it looks like we've hit issue #520 (socket.recv hitting some
  1426. # race condition preventing it from timing out correctly), wherein
  1427. # our socket and packetizer are both closed (but where we'd
  1428. # otherwise be sitting forever on that recv()).
  1429. while (
  1430. self.is_alive() and
  1431. self is not threading.current_thread() and
  1432. not self.sock._closed and
  1433. not self.packetizer.closed
  1434. ):
  1435. self.join(0.1)
  1436. # internals...
  1437. def _log(self, level, msg, *args):
  1438. if issubclass(type(msg), list):
  1439. for m in msg:
  1440. self.logger.log(level, m)
  1441. else:
  1442. self.logger.log(level, msg, *args)
  1443. def _get_modulus_pack(self):
  1444. """used by KexGex to find primes for group exchange"""
  1445. return self._modulus_pack
  1446. def _next_channel(self):
  1447. """you are holding the lock"""
  1448. chanid = self._channel_counter
  1449. while self._channels.get(chanid) is not None:
  1450. self._channel_counter = (self._channel_counter + 1) & 0xffffff
  1451. chanid = self._channel_counter
  1452. self._channel_counter = (self._channel_counter + 1) & 0xffffff
  1453. return chanid
  1454. def _unlink_channel(self, chanid):
  1455. """used by a Channel to remove itself from the active channel list"""
  1456. self._channels.delete(chanid)
  1457. def _send_message(self, data):
  1458. self.packetizer.send_message(data)
  1459. def _send_user_message(self, data):
  1460. """
  1461. send a message, but block if we're in key negotiation. this is used
  1462. for user-initiated requests.
  1463. """
  1464. start = time.time()
  1465. while True:
  1466. self.clear_to_send.wait(0.1)
  1467. if not self.active:
  1468. self._log(DEBUG, 'Dropping user packet because connection is dead.') # noqa
  1469. return
  1470. self.clear_to_send_lock.acquire()
  1471. if self.clear_to_send.is_set():
  1472. break
  1473. self.clear_to_send_lock.release()
  1474. if time.time() > start + self.clear_to_send_timeout:
  1475. raise SSHException('Key-exchange timed out waiting for key negotiation') # noqa
  1476. try:
  1477. self._send_message(data)
  1478. finally:
  1479. self.clear_to_send_lock.release()
  1480. def _set_K_H(self, k, h):
  1481. """
  1482. Used by a kex obj to set the K (root key) and H (exchange hash).
  1483. """
  1484. self.K = k
  1485. self.H = h
  1486. if self.session_id is None:
  1487. self.session_id = h
  1488. def _expect_packet(self, *ptypes):
  1489. """
  1490. Used by a kex obj to register the next packet type it expects to see.
  1491. """
  1492. self._expected_packet = tuple(ptypes)
  1493. def _verify_key(self, host_key, sig):
  1494. key = self._key_info[self.host_key_type](Message(host_key))
  1495. if key is None:
  1496. raise SSHException('Unknown host key type')
  1497. if not key.verify_ssh_sig(self.H, Message(sig)):
  1498. raise SSHException('Signature verification (%s) failed.' % self.host_key_type) # noqa
  1499. self.host_key = key
  1500. def _compute_key(self, id, nbytes):
  1501. """id is 'A' - 'F' for the various keys used by ssh"""
  1502. m = Message()
  1503. m.add_mpint(self.K)
  1504. m.add_bytes(self.H)
  1505. m.add_byte(b(id))
  1506. m.add_bytes(self.session_id)
  1507. # Fallback to SHA1 for kex engines that fail to specify a hex
  1508. # algorithm, or for e.g. transport tests that don't run kexinit.
  1509. hash_algo = getattr(self.kex_engine, 'hash_algo', None)
  1510. hash_select_msg = "kex engine %s specified hash_algo %r" % (
  1511. self.kex_engine.__class__.__name__, hash_algo
  1512. )
  1513. if hash_algo is None:
  1514. hash_algo = sha1
  1515. hash_select_msg += ", falling back to sha1"
  1516. if not hasattr(self, '_logged_hash_selection'):
  1517. self._log(DEBUG, hash_select_msg)
  1518. setattr(self, '_logged_hash_selection', True)
  1519. out = sofar = hash_algo(m.asbytes()).digest()
  1520. while len(out) < nbytes:
  1521. m = Message()
  1522. m.add_mpint(self.K)
  1523. m.add_bytes(self.H)
  1524. m.add_bytes(sofar)
  1525. digest = hash_algo(m.asbytes()).digest()
  1526. out += digest
  1527. sofar += digest
  1528. return out[:nbytes]
  1529. def _get_cipher(self, name, key, iv, operation):
  1530. if name not in self._cipher_info:
  1531. raise SSHException('Unknown client cipher ' + name)
  1532. else:
  1533. cipher = Cipher(
  1534. self._cipher_info[name]['class'](key),
  1535. self._cipher_info[name]['mode'](iv),
  1536. backend=default_backend(),
  1537. )
  1538. if operation is self._ENCRYPT:
  1539. return cipher.encryptor()
  1540. else:
  1541. return cipher.decryptor()
  1542. def _set_forward_agent_handler(self, handler):
  1543. if handler is None:
  1544. def default_handler(channel):
  1545. self._queue_incoming_channel(channel)
  1546. self._forward_agent_handler = default_handler
  1547. else:
  1548. self._forward_agent_handler = handler
  1549. def _set_x11_handler(self, handler):
  1550. # only called if a channel has turned on x11 forwarding
  1551. if handler is None:
  1552. # by default, use the same mechanism as accept()
  1553. def default_handler(channel, src_addr_port):
  1554. self._queue_incoming_channel(channel)
  1555. self._x11_handler = default_handler
  1556. else:
  1557. self._x11_handler = handler
  1558. def _queue_incoming_channel(self, channel):
  1559. self.lock.acquire()
  1560. try:
  1561. self.server_accepts.append(channel)
  1562. self.server_accept_cv.notify()
  1563. finally:
  1564. self.lock.release()
  1565. def _sanitize_window_size(self, window_size):
  1566. if window_size is None:
  1567. window_size = self.default_window_size
  1568. return clamp_value(MIN_WINDOW_SIZE, window_size, MAX_WINDOW_SIZE)
  1569. def _sanitize_packet_size(self, max_packet_size):
  1570. if max_packet_size is None:
  1571. max_packet_size = self.default_max_packet_size
  1572. return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE)
  1573. def run(self):
  1574. # (use the exposed "run" method, because if we specify a thread target
  1575. # of a private method, threading.Thread will keep a reference to it
  1576. # indefinitely, creating a GC cycle and not letting Transport ever be
  1577. # GC'd. it's a bug in Thread.)
  1578. # Hold reference to 'sys' so we can test sys.modules to detect
  1579. # interpreter shutdown.
  1580. self.sys = sys
  1581. # active=True occurs before the thread is launched, to avoid a race
  1582. _active_threads.append(self)
  1583. tid = hex(long(id(self)) & xffffffff)
  1584. if self.server_mode:
  1585. self._log(DEBUG, 'starting thread (server mode): %s' % tid)
  1586. else:
  1587. self._log(DEBUG, 'starting thread (client mode): %s' % tid)
  1588. try:
  1589. try:
  1590. self.packetizer.write_all(b(self.local_version + '\r\n'))
  1591. self._log(DEBUG, 'Local version/idstring: %s' % self.local_version) # noqa
  1592. self._check_banner()
  1593. # The above is actually very much part of the handshake, but
  1594. # sometimes the banner can be read but the machine is not
  1595. # responding, for example when the remote ssh daemon is loaded
  1596. # in to memory but we can not read from the disk/spawn a new
  1597. # shell.
  1598. # Make sure we can specify a timeout for the initial handshake.
  1599. # Re-use the banner timeout for now.
  1600. self.packetizer.start_handshake(self.handshake_timeout)
  1601. self._send_kex_init()
  1602. self._expect_packet(MSG_KEXINIT)
  1603. while self.active:
  1604. if self.packetizer.need_rekey() and not self.in_kex:
  1605. self._send_kex_init()
  1606. try:
  1607. ptype, m = self.packetizer.read_message()
  1608. except NeedRekeyException:
  1609. continue
  1610. if ptype == MSG_IGNORE:
  1611. continue
  1612. elif ptype == MSG_DISCONNECT:
  1613. self._parse_disconnect(m)
  1614. self.active = False
  1615. self.packetizer.close()
  1616. break
  1617. elif ptype == MSG_DEBUG:
  1618. self._parse_debug(m)
  1619. continue
  1620. if len(self._expected_packet) > 0:
  1621. if ptype not in self._expected_packet:
  1622. raise SSHException('Expecting packet from %r, got %d' % (self._expected_packet, ptype)) # noqa
  1623. self._expected_packet = tuple()
  1624. if (ptype >= 30) and (ptype <= 41):
  1625. self.kex_engine.parse_next(ptype, m)
  1626. continue
  1627. if ptype in self._handler_table:
  1628. self._handler_table[ptype](self, m)
  1629. elif ptype in self._channel_handler_table:
  1630. chanid = m.get_int()
  1631. chan = self._channels.get(chanid)
  1632. if chan is not None:
  1633. self._channel_handler_table[ptype](chan, m)
  1634. elif chanid in self.channels_seen:
  1635. self._log(DEBUG, 'Ignoring message for dead channel %d' % chanid) # noqa
  1636. else:
  1637. self._log(ERROR, 'Channel request for unknown channel %d' % chanid) # noqa
  1638. self.active = False
  1639. self.packetizer.close()
  1640. elif (
  1641. self.auth_handler is not None and
  1642. ptype in self.auth_handler._handler_table
  1643. ):
  1644. handler = self.auth_handler._handler_table[ptype]
  1645. handler(self.auth_handler, m)
  1646. else:
  1647. self._log(WARNING, 'Oops, unhandled type %d' % ptype)
  1648. msg = Message()
  1649. msg.add_byte(cMSG_UNIMPLEMENTED)
  1650. msg.add_int(m.seqno)
  1651. self._send_message(msg)
  1652. self.packetizer.complete_handshake()
  1653. except SSHException as e:
  1654. self._log(ERROR, 'Exception: ' + str(e))
  1655. self._log(ERROR, util.tb_strings())
  1656. self.saved_exception = e
  1657. except EOFError as e:
  1658. self._log(DEBUG, 'EOF in transport thread')
  1659. self.saved_exception = e
  1660. except socket.error as e:
  1661. if type(e.args) is tuple:
  1662. if e.args:
  1663. emsg = '%s (%d)' % (e.args[1], e.args[0])
  1664. else: # empty tuple, e.g. socket.timeout
  1665. emsg = str(e) or repr(e)
  1666. else:
  1667. emsg = e.args
  1668. self._log(ERROR, 'Socket exception: ' + emsg)
  1669. self.saved_exception = e
  1670. except Exception as e:
  1671. self._log(ERROR, 'Unknown exception: ' + str(e))
  1672. self._log(ERROR, util.tb_strings())
  1673. self.saved_exception = e
  1674. _active_threads.remove(self)
  1675. for chan in list(self._channels.values()):
  1676. chan._unlink()
  1677. if self.active:
  1678. self.active = False
  1679. self.packetizer.close()
  1680. if self.completion_event is not None:
  1681. self.completion_event.set()
  1682. if self.auth_handler is not None:
  1683. self.auth_handler.abort()
  1684. for event in self.channel_events.values():
  1685. event.set()
  1686. try:
  1687. self.lock.acquire()
  1688. self.server_accept_cv.notify()
  1689. finally:
  1690. self.lock.release()
  1691. self.sock.close()
  1692. except:
  1693. # Don't raise spurious 'NoneType has no attribute X' errors when we
  1694. # wake up during interpreter shutdown. Or rather -- raise
  1695. # everything *if* sys.modules (used as a convenient sentinel)
  1696. # appears to still exist.
  1697. if self.sys.modules is not None:
  1698. raise
  1699. def _log_agreement(self, which, local, remote):
  1700. # Log useful, non-duplicative line re: an agreed-upon algorithm.
  1701. # Old code implied algorithms could be asymmetrical (different for
  1702. # inbound vs outbound) so we preserve that possibility.
  1703. msg = "{0} agreed: ".format(which)
  1704. if local == remote:
  1705. msg += local
  1706. else:
  1707. msg += "local={0}, remote={1}".format(local, remote)
  1708. self._log(DEBUG, msg)
  1709. # protocol stages
  1710. def _negotiate_keys(self, m):
  1711. # throws SSHException on anything unusual
  1712. self.clear_to_send_lock.acquire()
  1713. try:
  1714. self.clear_to_send.clear()
  1715. finally:
  1716. self.clear_to_send_lock.release()
  1717. if self.local_kex_init is None:
  1718. # remote side wants to renegotiate
  1719. self._send_kex_init()
  1720. self._parse_kex_init(m)
  1721. self.kex_engine.start_kex()
  1722. def _check_banner(self):
  1723. # this is slow, but we only have to do it once
  1724. for i in range(100):
  1725. # give them 15 seconds for the first line, then just 2 seconds
  1726. # each additional line. (some sites have very high latency.)
  1727. if i == 0:
  1728. timeout = self.banner_timeout
  1729. else:
  1730. timeout = 2
  1731. try:
  1732. buf = self.packetizer.readline(timeout)
  1733. except ProxyCommandFailure:
  1734. raise
  1735. except Exception as e:
  1736. raise SSHException(
  1737. 'Error reading SSH protocol banner' + str(e)
  1738. )
  1739. if buf[:4] == 'SSH-':
  1740. break
  1741. self._log(DEBUG, 'Banner: ' + buf)
  1742. if buf[:4] != 'SSH-':
  1743. raise SSHException('Indecipherable protocol version "' + buf + '"')
  1744. # save this server version string for later
  1745. self.remote_version = buf
  1746. self._log(DEBUG, 'Remote version/idstring: %s' % buf)
  1747. # pull off any attached comment
  1748. # NOTE: comment used to be stored in a variable and then...never used.
  1749. # since 2003. ca 877cd974b8182d26fa76d566072917ea67b64e67
  1750. i = buf.find(' ')
  1751. if i >= 0:
  1752. buf = buf[:i]
  1753. # parse out version string and make sure it matches
  1754. segs = buf.split('-', 2)
  1755. if len(segs) < 3:
  1756. raise SSHException('Invalid SSH banner')
  1757. version = segs[1]
  1758. client = segs[2]
  1759. if version != '1.99' and version != '2.0':
  1760. msg = 'Incompatible version ({0} instead of 2.0)'
  1761. raise SSHException(msg.format(version))
  1762. msg = 'Connected (version {0}, client {1})'.format(version, client)
  1763. self._log(INFO, msg)
  1764. def _send_kex_init(self):
  1765. """
  1766. announce to the other side that we'd like to negotiate keys, and what
  1767. kind of key negotiation we support.
  1768. """
  1769. self.clear_to_send_lock.acquire()
  1770. try:
  1771. self.clear_to_send.clear()
  1772. finally:
  1773. self.clear_to_send_lock.release()
  1774. self.in_kex = True
  1775. if self.server_mode:
  1776. mp_required_prefix = 'diffie-hellman-group-exchange-sha'
  1777. kex_mp = [
  1778. k for k
  1779. in self._preferred_kex
  1780. if k.startswith(mp_required_prefix)
  1781. ]
  1782. if (self._modulus_pack is None) and (len(kex_mp) > 0):
  1783. # can't do group-exchange if we don't have a pack of potential
  1784. # primes
  1785. pkex = [
  1786. k for k
  1787. in self.get_security_options().kex
  1788. if not k.startswith(mp_required_prefix)
  1789. ]
  1790. self.get_security_options().kex = pkex
  1791. available_server_keys = list(filter(
  1792. list(self.server_key_dict.keys()).__contains__,
  1793. self._preferred_keys
  1794. ))
  1795. else:
  1796. available_server_keys = self._preferred_keys
  1797. m = Message()
  1798. m.add_byte(cMSG_KEXINIT)
  1799. m.add_bytes(os.urandom(16))
  1800. m.add_list(self._preferred_kex)
  1801. m.add_list(available_server_keys)
  1802. m.add_list(self._preferred_ciphers)
  1803. m.add_list(self._preferred_ciphers)
  1804. m.add_list(self._preferred_macs)
  1805. m.add_list(self._preferred_macs)
  1806. m.add_list(self._preferred_compression)
  1807. m.add_list(self._preferred_compression)
  1808. m.add_string(bytes())
  1809. m.add_string(bytes())
  1810. m.add_boolean(False)
  1811. m.add_int(0)
  1812. # save a copy for later (needed to compute a hash)
  1813. self.local_kex_init = m.asbytes()
  1814. self._send_message(m)
  1815. def _parse_kex_init(self, m):
  1816. m.get_bytes(16) # cookie, discarded
  1817. kex_algo_list = m.get_list()
  1818. server_key_algo_list = m.get_list()
  1819. client_encrypt_algo_list = m.get_list()
  1820. server_encrypt_algo_list = m.get_list()
  1821. client_mac_algo_list = m.get_list()
  1822. server_mac_algo_list = m.get_list()
  1823. client_compress_algo_list = m.get_list()
  1824. server_compress_algo_list = m.get_list()
  1825. client_lang_list = m.get_list()
  1826. server_lang_list = m.get_list()
  1827. kex_follows = m.get_boolean()
  1828. m.get_int() # unused
  1829. self._log(DEBUG,
  1830. 'kex algos:' + str(kex_algo_list) +
  1831. ' server key:' + str(server_key_algo_list) +
  1832. ' client encrypt:' + str(client_encrypt_algo_list) +
  1833. ' server encrypt:' + str(server_encrypt_algo_list) +
  1834. ' client mac:' + str(client_mac_algo_list) +
  1835. ' server mac:' + str(server_mac_algo_list) +
  1836. ' client compress:' + str(client_compress_algo_list) +
  1837. ' server compress:' + str(server_compress_algo_list) +
  1838. ' client lang:' + str(client_lang_list) +
  1839. ' server lang:' + str(server_lang_list) +
  1840. ' kex follows?' + str(kex_follows)
  1841. )
  1842. # as a server, we pick the first item in the client's list that we
  1843. # support.
  1844. # as a client, we pick the first item in our list that the server
  1845. # supports.
  1846. if self.server_mode:
  1847. agreed_kex = list(filter(
  1848. self._preferred_kex.__contains__,
  1849. kex_algo_list
  1850. ))
  1851. else:
  1852. agreed_kex = list(filter(
  1853. kex_algo_list.__contains__,
  1854. self._preferred_kex
  1855. ))
  1856. if len(agreed_kex) == 0:
  1857. raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)') # noqa
  1858. self.kex_engine = self._kex_info[agreed_kex[0]](self)
  1859. self._log(DEBUG, "Kex agreed: %s" % agreed_kex[0])
  1860. if self.server_mode:
  1861. available_server_keys = list(filter(
  1862. list(self.server_key_dict.keys()).__contains__,
  1863. self._preferred_keys
  1864. ))
  1865. agreed_keys = list(filter(
  1866. available_server_keys.__contains__, server_key_algo_list
  1867. ))
  1868. else:
  1869. agreed_keys = list(filter(
  1870. server_key_algo_list.__contains__, self._preferred_keys
  1871. ))
  1872. if len(agreed_keys) == 0:
  1873. raise SSHException('Incompatible ssh peer (no acceptable host key)') # noqa
  1874. self.host_key_type = agreed_keys[0]
  1875. if self.server_mode and (self.get_server_key() is None):
  1876. raise SSHException('Incompatible ssh peer (can\'t match requested host key type)') # noqa
  1877. self._log_agreement(
  1878. 'HostKey', agreed_keys[0], agreed_keys[0]
  1879. )
  1880. if self.server_mode:
  1881. agreed_local_ciphers = list(filter(
  1882. self._preferred_ciphers.__contains__,
  1883. server_encrypt_algo_list
  1884. ))
  1885. agreed_remote_ciphers = list(filter(
  1886. self._preferred_ciphers.__contains__,
  1887. client_encrypt_algo_list
  1888. ))
  1889. else:
  1890. agreed_local_ciphers = list(filter(
  1891. client_encrypt_algo_list.__contains__,
  1892. self._preferred_ciphers
  1893. ))
  1894. agreed_remote_ciphers = list(filter(
  1895. server_encrypt_algo_list.__contains__,
  1896. self._preferred_ciphers
  1897. ))
  1898. if len(agreed_local_ciphers) == 0 or len(agreed_remote_ciphers) == 0:
  1899. raise SSHException('Incompatible ssh server (no acceptable ciphers)') # noqa
  1900. self.local_cipher = agreed_local_ciphers[0]
  1901. self.remote_cipher = agreed_remote_ciphers[0]
  1902. self._log_agreement(
  1903. 'Cipher', local=self.local_cipher, remote=self.remote_cipher
  1904. )
  1905. if self.server_mode:
  1906. agreed_remote_macs = list(filter(
  1907. self._preferred_macs.__contains__, client_mac_algo_list
  1908. ))
  1909. agreed_local_macs = list(filter(
  1910. self._preferred_macs.__contains__, server_mac_algo_list
  1911. ))
  1912. else:
  1913. agreed_local_macs = list(filter(
  1914. client_mac_algo_list.__contains__, self._preferred_macs
  1915. ))
  1916. agreed_remote_macs = list(filter(
  1917. server_mac_algo_list.__contains__, self._preferred_macs
  1918. ))
  1919. if (len(agreed_local_macs) == 0) or (len(agreed_remote_macs) == 0):
  1920. raise SSHException('Incompatible ssh server (no acceptable macs)')
  1921. self.local_mac = agreed_local_macs[0]
  1922. self.remote_mac = agreed_remote_macs[0]
  1923. self._log_agreement(
  1924. 'MAC', local=self.local_mac, remote=self.remote_mac
  1925. )
  1926. if self.server_mode:
  1927. agreed_remote_compression = list(filter(
  1928. self._preferred_compression.__contains__,
  1929. client_compress_algo_list
  1930. ))
  1931. agreed_local_compression = list(filter(
  1932. self._preferred_compression.__contains__,
  1933. server_compress_algo_list
  1934. ))
  1935. else:
  1936. agreed_local_compression = list(filter(
  1937. client_compress_algo_list.__contains__,
  1938. self._preferred_compression
  1939. ))
  1940. agreed_remote_compression = list(filter(
  1941. server_compress_algo_list.__contains__,
  1942. self._preferred_compression
  1943. ))
  1944. if (
  1945. len(agreed_local_compression) == 0 or
  1946. len(agreed_remote_compression) == 0
  1947. ):
  1948. msg = 'Incompatible ssh server (no acceptable compression) {0!r} {1!r} {2!r}' # noqa
  1949. raise SSHException(msg.format(
  1950. agreed_local_compression, agreed_remote_compression,
  1951. self._preferred_compression,
  1952. ))
  1953. self.local_compression = agreed_local_compression[0]
  1954. self.remote_compression = agreed_remote_compression[0]
  1955. self._log_agreement(
  1956. 'Compression',
  1957. local=self.local_compression,
  1958. remote=self.remote_compression
  1959. )
  1960. # save for computing hash later...
  1961. # now wait! openssh has a bug (and others might too) where there are
  1962. # actually some extra bytes (one NUL byte in openssh's case) added to
  1963. # the end of the packet but not parsed. turns out we need to throw
  1964. # away those bytes because they aren't part of the hash.
  1965. self.remote_kex_init = cMSG_KEXINIT + m.get_so_far()
  1966. def _activate_inbound(self):
  1967. """switch on newly negotiated encryption parameters for
  1968. inbound traffic"""
  1969. block_size = self._cipher_info[self.remote_cipher]['block-size']
  1970. if self.server_mode:
  1971. IV_in = self._compute_key('A', block_size)
  1972. key_in = self._compute_key(
  1973. 'C', self._cipher_info[self.remote_cipher]['key-size']
  1974. )
  1975. else:
  1976. IV_in = self._compute_key('B', block_size)
  1977. key_in = self._compute_key(
  1978. 'D', self._cipher_info[self.remote_cipher]['key-size']
  1979. )
  1980. engine = self._get_cipher(
  1981. self.remote_cipher, key_in, IV_in, self._DECRYPT
  1982. )
  1983. mac_size = self._mac_info[self.remote_mac]['size']
  1984. mac_engine = self._mac_info[self.remote_mac]['class']
  1985. # initial mac keys are done in the hash's natural size (not the
  1986. # potentially truncated transmission size)
  1987. if self.server_mode:
  1988. mac_key = self._compute_key('E', mac_engine().digest_size)
  1989. else:
  1990. mac_key = self._compute_key('F', mac_engine().digest_size)
  1991. self.packetizer.set_inbound_cipher(
  1992. engine, block_size, mac_engine, mac_size, mac_key
  1993. )
  1994. compress_in = self._compression_info[self.remote_compression][1]
  1995. if (
  1996. compress_in is not None and
  1997. (
  1998. self.remote_compression != 'zlib@openssh.com' or
  1999. self.authenticated
  2000. )
  2001. ):
  2002. self._log(DEBUG, 'Switching on inbound compression ...')
  2003. self.packetizer.set_inbound_compressor(compress_in())
  2004. def _activate_outbound(self):
  2005. """switch on newly negotiated encryption parameters for
  2006. outbound traffic"""
  2007. m = Message()
  2008. m.add_byte(cMSG_NEWKEYS)
  2009. self._send_message(m)
  2010. block_size = self._cipher_info[self.local_cipher]['block-size']
  2011. if self.server_mode:
  2012. IV_out = self._compute_key('B', block_size)
  2013. key_out = self._compute_key(
  2014. 'D', self._cipher_info[self.local_cipher]['key-size'])
  2015. else:
  2016. IV_out = self._compute_key('A', block_size)
  2017. key_out = self._compute_key(
  2018. 'C', self._cipher_info[self.local_cipher]['key-size'])
  2019. engine = self._get_cipher(
  2020. self.local_cipher, key_out, IV_out, self._ENCRYPT)
  2021. mac_size = self._mac_info[self.local_mac]['size']
  2022. mac_engine = self._mac_info[self.local_mac]['class']
  2023. # initial mac keys are done in the hash's natural size (not the
  2024. # potentially truncated transmission size)
  2025. if self.server_mode:
  2026. mac_key = self._compute_key('F', mac_engine().digest_size)
  2027. else:
  2028. mac_key = self._compute_key('E', mac_engine().digest_size)
  2029. sdctr = self.local_cipher.endswith('-ctr')
  2030. self.packetizer.set_outbound_cipher(
  2031. engine, block_size, mac_engine, mac_size, mac_key, sdctr)
  2032. compress_out = self._compression_info[self.local_compression][0]
  2033. if (
  2034. compress_out is not None and
  2035. (
  2036. self.local_compression != 'zlib@openssh.com' or
  2037. self.authenticated
  2038. )
  2039. ):
  2040. self._log(DEBUG, 'Switching on outbound compression ...')
  2041. self.packetizer.set_outbound_compressor(compress_out())
  2042. if not self.packetizer.need_rekey():
  2043. self.in_kex = False
  2044. # we always expect to receive NEWKEYS now
  2045. self._expect_packet(MSG_NEWKEYS)
  2046. def _auth_trigger(self):
  2047. self.authenticated = True
  2048. # delayed initiation of compression
  2049. if self.local_compression == 'zlib@openssh.com':
  2050. compress_out = self._compression_info[self.local_compression][0]
  2051. self._log(DEBUG, 'Switching on outbound compression ...')
  2052. self.packetizer.set_outbound_compressor(compress_out())
  2053. if self.remote_compression == 'zlib@openssh.com':
  2054. compress_in = self._compression_info[self.remote_compression][1]
  2055. self._log(DEBUG, 'Switching on inbound compression ...')
  2056. self.packetizer.set_inbound_compressor(compress_in())
  2057. def _parse_newkeys(self, m):
  2058. self._log(DEBUG, 'Switch to new keys ...')
  2059. self._activate_inbound()
  2060. # can also free a bunch of stuff here
  2061. self.local_kex_init = self.remote_kex_init = None
  2062. self.K = None
  2063. self.kex_engine = None
  2064. if self.server_mode and (self.auth_handler is None):
  2065. # create auth handler for server mode
  2066. self.auth_handler = AuthHandler(self)
  2067. if not self.initial_kex_done:
  2068. # this was the first key exchange
  2069. self.initial_kex_done = True
  2070. # send an event?
  2071. if self.completion_event is not None:
  2072. self.completion_event.set()
  2073. # it's now okay to send data again (if this was a re-key)
  2074. if not self.packetizer.need_rekey():
  2075. self.in_kex = False
  2076. self.clear_to_send_lock.acquire()
  2077. try:
  2078. self.clear_to_send.set()
  2079. finally:
  2080. self.clear_to_send_lock.release()
  2081. return
  2082. def _parse_disconnect(self, m):
  2083. code = m.get_int()
  2084. desc = m.get_text()
  2085. self._log(INFO, 'Disconnect (code %d): %s' % (code, desc))
  2086. def _parse_global_request(self, m):
  2087. kind = m.get_text()
  2088. self._log(DEBUG, 'Received global request "%s"' % kind)
  2089. want_reply = m.get_boolean()
  2090. if not self.server_mode:
  2091. self._log(
  2092. DEBUG,
  2093. 'Rejecting "%s" global request from server.' % kind
  2094. )
  2095. ok = False
  2096. elif kind == 'tcpip-forward':
  2097. address = m.get_text()
  2098. port = m.get_int()
  2099. ok = self.server_object.check_port_forward_request(address, port)
  2100. if ok:
  2101. ok = (ok,)
  2102. elif kind == 'cancel-tcpip-forward':
  2103. address = m.get_text()
  2104. port = m.get_int()
  2105. self.server_object.cancel_port_forward_request(address, port)
  2106. ok = True
  2107. else:
  2108. ok = self.server_object.check_global_request(kind, m)
  2109. extra = ()
  2110. if type(ok) is tuple:
  2111. extra = ok
  2112. ok = True
  2113. if want_reply:
  2114. msg = Message()
  2115. if ok:
  2116. msg.add_byte(cMSG_REQUEST_SUCCESS)
  2117. msg.add(*extra)
  2118. else:
  2119. msg.add_byte(cMSG_REQUEST_FAILURE)
  2120. self._send_message(msg)
  2121. def _parse_request_success(self, m):
  2122. self._log(DEBUG, 'Global request successful.')
  2123. self.global_response = m
  2124. if self.completion_event is not None:
  2125. self.completion_event.set()
  2126. def _parse_request_failure(self, m):
  2127. self._log(DEBUG, 'Global request denied.')
  2128. self.global_response = None
  2129. if self.completion_event is not None:
  2130. self.completion_event.set()
  2131. def _parse_channel_open_success(self, m):
  2132. chanid = m.get_int()
  2133. server_chanid = m.get_int()
  2134. server_window_size = m.get_int()
  2135. server_max_packet_size = m.get_int()
  2136. chan = self._channels.get(chanid)
  2137. if chan is None:
  2138. self._log(WARNING, 'Success for unrequested channel! [??]')
  2139. return
  2140. self.lock.acquire()
  2141. try:
  2142. chan._set_remote_channel(
  2143. server_chanid, server_window_size, server_max_packet_size)
  2144. self._log(DEBUG, 'Secsh channel %d opened.' % chanid)
  2145. if chanid in self.channel_events:
  2146. self.channel_events[chanid].set()
  2147. del self.channel_events[chanid]
  2148. finally:
  2149. self.lock.release()
  2150. return
  2151. def _parse_channel_open_failure(self, m):
  2152. chanid = m.get_int()
  2153. reason = m.get_int()
  2154. reason_str = m.get_text()
  2155. m.get_text() # ignored language
  2156. reason_text = CONNECTION_FAILED_CODE.get(reason, '(unknown code)')
  2157. self._log(
  2158. ERROR,
  2159. 'Secsh channel %d open FAILED: %s: %s' % (
  2160. chanid, reason_str, reason_text)
  2161. )
  2162. self.lock.acquire()
  2163. try:
  2164. self.saved_exception = ChannelException(reason, reason_text)
  2165. if chanid in self.channel_events:
  2166. self._channels.delete(chanid)
  2167. if chanid in self.channel_events:
  2168. self.channel_events[chanid].set()
  2169. del self.channel_events[chanid]
  2170. finally:
  2171. self.lock.release()
  2172. return
  2173. def _parse_channel_open(self, m):
  2174. kind = m.get_text()
  2175. chanid = m.get_int()
  2176. initial_window_size = m.get_int()
  2177. max_packet_size = m.get_int()
  2178. reject = False
  2179. if (
  2180. kind == 'auth-agent@openssh.com' and
  2181. self._forward_agent_handler is not None
  2182. ):
  2183. self._log(DEBUG, 'Incoming forward agent connection')
  2184. self.lock.acquire()
  2185. try:
  2186. my_chanid = self._next_channel()
  2187. finally:
  2188. self.lock.release()
  2189. elif (kind == 'x11') and (self._x11_handler is not None):
  2190. origin_addr = m.get_text()
  2191. origin_port = m.get_int()
  2192. self._log(
  2193. DEBUG,
  2194. 'Incoming x11 connection from %s:%d' % (
  2195. origin_addr, origin_port)
  2196. )
  2197. self.lock.acquire()
  2198. try:
  2199. my_chanid = self._next_channel()
  2200. finally:
  2201. self.lock.release()
  2202. elif (kind == 'forwarded-tcpip') and (self._tcp_handler is not None):
  2203. server_addr = m.get_text()
  2204. server_port = m.get_int()
  2205. origin_addr = m.get_text()
  2206. origin_port = m.get_int()
  2207. self._log(
  2208. DEBUG,
  2209. 'Incoming tcp forwarded connection from %s:%d' % (
  2210. origin_addr, origin_port)
  2211. )
  2212. self.lock.acquire()
  2213. try:
  2214. my_chanid = self._next_channel()
  2215. finally:
  2216. self.lock.release()
  2217. elif not self.server_mode:
  2218. self._log(
  2219. DEBUG,
  2220. 'Rejecting "%s" channel request from server.' % kind)
  2221. reject = True
  2222. reason = OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
  2223. else:
  2224. self.lock.acquire()
  2225. try:
  2226. my_chanid = self._next_channel()
  2227. finally:
  2228. self.lock.release()
  2229. if kind == 'direct-tcpip':
  2230. # handle direct-tcpip requests coming from the client
  2231. dest_addr = m.get_text()
  2232. dest_port = m.get_int()
  2233. origin_addr = m.get_text()
  2234. origin_port = m.get_int()
  2235. reason = self.server_object.check_channel_direct_tcpip_request(
  2236. my_chanid,
  2237. (origin_addr, origin_port),
  2238. (dest_addr, dest_port)
  2239. )
  2240. else:
  2241. reason = self.server_object.check_channel_request(
  2242. kind, my_chanid)
  2243. if reason != OPEN_SUCCEEDED:
  2244. self._log(
  2245. DEBUG,
  2246. 'Rejecting "%s" channel request from client.' % kind)
  2247. reject = True
  2248. if reject:
  2249. msg = Message()
  2250. msg.add_byte(cMSG_CHANNEL_OPEN_FAILURE)
  2251. msg.add_int(chanid)
  2252. msg.add_int(reason)
  2253. msg.add_string('')
  2254. msg.add_string('en')
  2255. self._send_message(msg)
  2256. return
  2257. chan = Channel(my_chanid)
  2258. self.lock.acquire()
  2259. try:
  2260. self._channels.put(my_chanid, chan)
  2261. self.channels_seen[my_chanid] = True
  2262. chan._set_transport(self)
  2263. chan._set_window(
  2264. self.default_window_size, self.default_max_packet_size)
  2265. chan._set_remote_channel(
  2266. chanid, initial_window_size, max_packet_size)
  2267. finally:
  2268. self.lock.release()
  2269. m = Message()
  2270. m.add_byte(cMSG_CHANNEL_OPEN_SUCCESS)
  2271. m.add_int(chanid)
  2272. m.add_int(my_chanid)
  2273. m.add_int(self.default_window_size)
  2274. m.add_int(self.default_max_packet_size)
  2275. self._send_message(m)
  2276. self._log(DEBUG, 'Secsh channel %d (%s) opened.', my_chanid, kind)
  2277. if kind == 'auth-agent@openssh.com':
  2278. self._forward_agent_handler(chan)
  2279. elif kind == 'x11':
  2280. self._x11_handler(chan, (origin_addr, origin_port))
  2281. elif kind == 'forwarded-tcpip':
  2282. chan.origin_addr = (origin_addr, origin_port)
  2283. self._tcp_handler(
  2284. chan,
  2285. (origin_addr, origin_port),
  2286. (server_addr, server_port)
  2287. )
  2288. else:
  2289. self._queue_incoming_channel(chan)
  2290. def _parse_debug(self, m):
  2291. m.get_boolean() # always_display
  2292. msg = m.get_string()
  2293. m.get_string() # language
  2294. self._log(DEBUG, 'Debug msg: {0}'.format(util.safe_string(msg)))
  2295. def _get_subsystem_handler(self, name):
  2296. try:
  2297. self.lock.acquire()
  2298. if name not in self.subsystem_table:
  2299. return None, [], {}
  2300. return self.subsystem_table[name]
  2301. finally:
  2302. self.lock.release()
  2303. _handler_table = {
  2304. MSG_NEWKEYS: _parse_newkeys,
  2305. MSG_GLOBAL_REQUEST: _parse_global_request,
  2306. MSG_REQUEST_SUCCESS: _parse_request_success,
  2307. MSG_REQUEST_FAILURE: _parse_request_failure,
  2308. MSG_CHANNEL_OPEN_SUCCESS: _parse_channel_open_success,
  2309. MSG_CHANNEL_OPEN_FAILURE: _parse_channel_open_failure,
  2310. MSG_CHANNEL_OPEN: _parse_channel_open,
  2311. MSG_KEXINIT: _negotiate_keys,
  2312. }
  2313. _channel_handler_table = {
  2314. MSG_CHANNEL_SUCCESS: Channel._request_success,
  2315. MSG_CHANNEL_FAILURE: Channel._request_failed,
  2316. MSG_CHANNEL_DATA: Channel._feed,
  2317. MSG_CHANNEL_EXTENDED_DATA: Channel._feed_extended,
  2318. MSG_CHANNEL_WINDOW_ADJUST: Channel._window_adjust,
  2319. MSG_CHANNEL_REQUEST: Channel._handle_request,
  2320. MSG_CHANNEL_EOF: Channel._handle_eof,
  2321. MSG_CHANNEL_CLOSE: Channel._handle_close,
  2322. }
  2323. class SecurityOptions (object):
  2324. """
  2325. Simple object containing the security preferences of an ssh transport.
  2326. These are tuples of acceptable ciphers, digests, key types, and key
  2327. exchange algorithms, listed in order of preference.
  2328. Changing the contents and/or order of these fields affects the underlying
  2329. `.Transport` (but only if you change them before starting the session).
  2330. If you try to add an algorithm that paramiko doesn't recognize,
  2331. ``ValueError`` will be raised. If you try to assign something besides a
  2332. tuple to one of the fields, ``TypeError`` will be raised.
  2333. """
  2334. __slots__ = '_transport'
  2335. def __init__(self, transport):
  2336. self._transport = transport
  2337. def __repr__(self):
  2338. """
  2339. Returns a string representation of this object, for debugging.
  2340. """
  2341. return '<paramiko.SecurityOptions for %s>' % repr(self._transport)
  2342. def _set(self, name, orig, x):
  2343. if type(x) is list:
  2344. x = tuple(x)
  2345. if type(x) is not tuple:
  2346. raise TypeError('expected tuple or list')
  2347. possible = list(getattr(self._transport, orig).keys())
  2348. forbidden = [n for n in x if n not in possible]
  2349. if len(forbidden) > 0:
  2350. raise ValueError('unknown cipher')
  2351. setattr(self._transport, name, x)
  2352. @property
  2353. def ciphers(self):
  2354. """Symmetric encryption ciphers"""
  2355. return self._transport._preferred_ciphers
  2356. @ciphers.setter
  2357. def ciphers(self, x):
  2358. self._set('_preferred_ciphers', '_cipher_info', x)
  2359. @property
  2360. def digests(self):
  2361. """Digest (one-way hash) algorithms"""
  2362. return self._transport._preferred_macs
  2363. @digests.setter
  2364. def digests(self, x):
  2365. self._set('_preferred_macs', '_mac_info', x)
  2366. @property
  2367. def key_types(self):
  2368. """Public-key algorithms"""
  2369. return self._transport._preferred_keys
  2370. @key_types.setter
  2371. def key_types(self, x):
  2372. self._set('_preferred_keys', '_key_info', x)
  2373. @property
  2374. def kex(self):
  2375. """Key exchange algorithms"""
  2376. return self._transport._preferred_kex
  2377. @kex.setter
  2378. def kex(self, x):
  2379. self._set('_preferred_kex', '_kex_info', x)
  2380. @property
  2381. def compression(self):
  2382. """Compression algorithms"""
  2383. return self._transport._preferred_compression
  2384. @compression.setter
  2385. def compression(self, x):
  2386. self._set('_preferred_compression', '_compression_info', x)
  2387. class ChannelMap (object):
  2388. def __init__(self):
  2389. # (id -> Channel)
  2390. self._map = weakref.WeakValueDictionary()
  2391. self._lock = threading.Lock()
  2392. def put(self, chanid, chan):
  2393. self._lock.acquire()
  2394. try:
  2395. self._map[chanid] = chan
  2396. finally:
  2397. self._lock.release()
  2398. def get(self, chanid):
  2399. self._lock.acquire()
  2400. try:
  2401. return self._map.get(chanid, None)
  2402. finally:
  2403. self._lock.release()
  2404. def delete(self, chanid):
  2405. self._lock.acquire()
  2406. try:
  2407. try:
  2408. del self._map[chanid]
  2409. except KeyError:
  2410. pass
  2411. finally:
  2412. self._lock.release()
  2413. def values(self):
  2414. self._lock.acquire()
  2415. try:
  2416. return list(self._map.values())
  2417. finally:
  2418. self._lock.release()
  2419. def __len__(self):
  2420. self._lock.acquire()
  2421. try:
  2422. return len(self._map)
  2423. finally:
  2424. self._lock.release()