Agent.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. /**
  3. * Pure-PHP ssh-agent client.
  4. *
  5. * PHP version 5
  6. *
  7. * Here are some examples of how to use this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * $agent = new \phpseclib\System\SSH\Agent();
  13. *
  14. * $ssh = new \phpseclib\Net\SSH2('www.domain.tld');
  15. * if (!$ssh->login('username', $agent)) {
  16. * exit('Login Failed');
  17. * }
  18. *
  19. * echo $ssh->exec('pwd');
  20. * echo $ssh->exec('ls -la');
  21. * ?>
  22. * </code>
  23. *
  24. * @category System
  25. * @package SSH\Agent
  26. * @author Jim Wigginton <terrafrost@php.net>
  27. * @copyright 2014 Jim Wigginton
  28. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  29. * @link http://phpseclib.sourceforge.net
  30. * @internal See http://api.libssh.org/rfc/PROTOCOL.agent
  31. */
  32. namespace phpseclib\System\SSH;
  33. use ParagonIE\ConstantTime\Base64;
  34. use phpseclib\Crypt\RSA;
  35. use phpseclib\Exception\BadConfigurationException;
  36. use phpseclib\System\SSH\Agent\Identity;
  37. use phpseclib\Common\Functions\Objects;
  38. /**
  39. * Pure-PHP ssh-agent client identity factory
  40. *
  41. * requestIdentities() method pumps out \phpseclib\System\SSH\Agent\Identity objects
  42. *
  43. * @package SSH\Agent
  44. * @author Jim Wigginton <terrafrost@php.net>
  45. * @access internal
  46. */
  47. class Agent
  48. {
  49. /**#@+
  50. * Message numbers
  51. *
  52. * @access private
  53. */
  54. // to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1)
  55. const SSH_AGENTC_REQUEST_IDENTITIES = 11;
  56. // this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2).
  57. const SSH_AGENT_IDENTITIES_ANSWER = 12;
  58. // the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3)
  59. const SSH_AGENTC_SIGN_REQUEST = 13;
  60. // the SSH1 response is SSH_AGENT_RSA_RESPONSE (4)
  61. const SSH_AGENT_SIGN_RESPONSE = 14;
  62. /**#@-*/
  63. /**@+
  64. * Agent forwarding status
  65. *
  66. * @access private
  67. */
  68. // no forwarding requested and not active
  69. const FORWARD_NONE = 0;
  70. // request agent forwarding when opportune
  71. const FORWARD_REQUEST = 1;
  72. // forwarding has been request and is active
  73. const FORWARD_ACTIVE = 2;
  74. /**#@-*/
  75. /**
  76. * Unused
  77. */
  78. const SSH_AGENT_FAILURE = 5;
  79. /**
  80. * Socket Resource
  81. *
  82. * @var resource
  83. * @access private
  84. */
  85. private $fsock;
  86. /**
  87. * Agent forwarding status
  88. *
  89. * @var int
  90. * @access private
  91. */
  92. private $forward_status = self::FORWARD_NONE;
  93. /**
  94. * Buffer for accumulating forwarded authentication
  95. * agent data arriving on SSH data channel destined
  96. * for agent unix socket
  97. *
  98. * @var string
  99. * @access private
  100. */
  101. private $socket_buffer = '';
  102. /**
  103. * Tracking the number of bytes we are expecting
  104. * to arrive for the agent socket on the SSH data
  105. * channel
  106. *
  107. * @var int
  108. * @access private
  109. */
  110. private $expected_bytes = 0;
  111. /**
  112. * The current request channel
  113. *
  114. * @var int
  115. * @access private
  116. */
  117. private $request_channel;
  118. /**
  119. * Default Constructor
  120. *
  121. * @return \phpseclib\System\SSH\Agent
  122. * @throws \phpseclib\Exception\BadConfigurationException if SSH_AUTH_SOCK cannot be found
  123. * @throws \RuntimeException on connection errors
  124. * @access public
  125. */
  126. public function __construct()
  127. {
  128. switch (true) {
  129. case isset($_SERVER['SSH_AUTH_SOCK']):
  130. $address = $_SERVER['SSH_AUTH_SOCK'];
  131. break;
  132. case isset($_ENV['SSH_AUTH_SOCK']):
  133. $address = $_ENV['SSH_AUTH_SOCK'];
  134. break;
  135. default:
  136. throw new BadConfigurationException('SSH_AUTH_SOCK not found');
  137. }
  138. $this->fsock = fsockopen('unix://' . $address, 0, $errno, $errstr);
  139. if (!$this->fsock) {
  140. throw new \RuntimeException("Unable to connect to ssh-agent (Error $errno: $errstr)");
  141. }
  142. }
  143. /**
  144. * Request Identities
  145. *
  146. * See "2.5.2 Requesting a list of protocol 2 keys"
  147. * Returns an array containing zero or more \phpseclib\System\SSH\Agent\Identity objects
  148. *
  149. * @return array
  150. * @throws \RuntimeException on receipt of unexpected packets
  151. * @access public
  152. */
  153. public function requestIdentities()
  154. {
  155. if (!$this->fsock) {
  156. return [];
  157. }
  158. $packet = pack('NC', 1, self::SSH_AGENTC_REQUEST_IDENTITIES);
  159. if (strlen($packet) != fputs($this->fsock, $packet)) {
  160. throw new \RuntimeException('Connection closed while requesting identities');
  161. }
  162. $length = current(unpack('N', fread($this->fsock, 4)));
  163. $type = ord(fread($this->fsock, 1));
  164. if ($type != self::SSH_AGENT_IDENTITIES_ANSWER) {
  165. throw new \RuntimeException('Unable to request identities');
  166. }
  167. $identities = [];
  168. $keyCount = current(unpack('N', fread($this->fsock, 4)));
  169. for ($i = 0; $i < $keyCount; $i++) {
  170. $length = current(unpack('N', fread($this->fsock, 4)));
  171. $key_blob = fread($this->fsock, $length);
  172. $key_str = 'ssh-rsa ' . Base64::encode($key_blob);
  173. $length = current(unpack('N', fread($this->fsock, 4)));
  174. if ($length) {
  175. $key_str.= ' ' . fread($this->fsock, $length);
  176. }
  177. $length = current(unpack('N', substr($key_blob, 0, 4)));
  178. $key_type = substr($key_blob, 4, $length);
  179. switch ($key_type) {
  180. case 'ssh-rsa':
  181. $key = new RSA();
  182. $key->load($key_str);
  183. break;
  184. case 'ssh-dss':
  185. // not currently supported
  186. break;
  187. }
  188. // resources are passed by reference by default
  189. if (isset($key)) {
  190. $identity = new Identity($this->fsock);
  191. $identity->setPublicKey($key);
  192. $identity->setPublicKeyBlob($key_blob);
  193. $identities[] = $identity;
  194. unset($key);
  195. }
  196. }
  197. return $identities;
  198. }
  199. /**
  200. * Signal that agent forwarding should
  201. * be requested when a channel is opened
  202. *
  203. * @param Net_SSH2 $ssh
  204. * @return bool
  205. * @access public
  206. */
  207. public function startSSHForwarding($ssh)
  208. {
  209. if ($this->forward_status == self::FORWARD_NONE) {
  210. $this->forward_status = self::FORWARD_REQUEST;
  211. }
  212. }
  213. /**
  214. * Request agent forwarding of remote server
  215. *
  216. * @param Net_SSH2 $ssh
  217. * @return bool
  218. * @access private
  219. */
  220. private function request_forwarding($ssh)
  221. {
  222. $this->request_channel = Objects::callFunc($ssh, 'get_open_channel');
  223. if ($this->request_channel === false) {
  224. return false;
  225. }
  226. $packet = pack(
  227. 'CNNa*C',
  228. NET_SSH2_MSG_CHANNEL_REQUEST,
  229. Objects::getVar($ssh, 'server_channels')[$this->request_channel],
  230. strlen('auth-agent-req@openssh.com'),
  231. 'auth-agent-req@openssh.com',
  232. 1
  233. );
  234. $this->update_channel_status($ssh, NET_SSH2_MSG_CHANNEL_REQUEST);
  235. if (!Objects::callFunc($ssh, 'send_binary_packet', [$packet])) {
  236. return false;
  237. }
  238. $response = Objects::callFunc($ssh, 'get_channel_packet', [$this->request_channel]);
  239. if ($response === false) {
  240. return false;
  241. }
  242. $this->update_channel_status($ssh, NET_SSH2_MSG_CHANNEL_OPEN);
  243. $this->forward_status = self::FORWARD_ACTIVE;
  244. return true;
  245. }
  246. /**
  247. * On successful channel open
  248. *
  249. * This method is called upon successful channel
  250. * open to give the SSH Agent an opportunity
  251. * to take further action. i.e. request agent forwarding
  252. *
  253. * @param Net_SSH2 $ssh
  254. * @access private
  255. */
  256. private function on_channel_open($ssh)
  257. {
  258. if ($this->forward_status == self::FORWARD_REQUEST) {
  259. $this->request_forwarding($ssh);
  260. }
  261. }
  262. /**
  263. * Forward data to SSH Agent and return data reply
  264. *
  265. * @param string $data
  266. * @return data from SSH Agent
  267. * @throws \RuntimeException on connection errors
  268. * @access private
  269. */
  270. private function forward_data($data)
  271. {
  272. if ($this->expected_bytes > 0) {
  273. $this->socket_buffer.= $data;
  274. $this->expected_bytes -= strlen($data);
  275. } else {
  276. $agent_data_bytes = current(unpack('N', $data));
  277. $current_data_bytes = strlen($data);
  278. $this->socket_buffer = $data;
  279. if ($current_data_bytes != $agent_data_bytes + 4) {
  280. $this->expected_bytes = ($agent_data_bytes + 4) - $current_data_bytes;
  281. return false;
  282. }
  283. }
  284. if (strlen($this->socket_buffer) != fwrite($this->fsock, $this->socket_buffer)) {
  285. throw new \RuntimeException('Connection closed attempting to forward data to SSH agent');
  286. }
  287. $this->socket_buffer = '';
  288. $this->expected_bytes = 0;
  289. $agent_reply_bytes = current(unpack('N', fread($this->fsock, 4)));
  290. $agent_reply_data = fread($this->fsock, $agent_reply_bytes);
  291. $agent_reply_data = current(unpack('a*', $agent_reply_data));
  292. return pack('Na*', $agent_reply_bytes, $agent_reply_data);
  293. }
  294. /**
  295. * Forward data to SSH Agent and return data reply
  296. *
  297. * @param \phpseclib\Net\SSH2 $ssh
  298. * @param integer $status
  299. * @access private
  300. */
  301. private function update_channel_status($ssh, $status)
  302. {
  303. $temp = Objects::getVar($ssh, 'channel_status');
  304. $temp[$this->request_channel] = $status;
  305. Objects::setVar($ssh, 'channel_status', $temp);
  306. }
  307. }