Agent.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. /**
  38. * Pure-PHP ssh-agent client identity factory
  39. *
  40. * requestIdentities() method pumps out \phpseclib\System\SSH\Agent\Identity objects
  41. *
  42. * @package SSH\Agent
  43. * @author Jim Wigginton <terrafrost@php.net>
  44. * @access internal
  45. */
  46. class Agent
  47. {
  48. /**#@+
  49. * Message numbers
  50. *
  51. * @access private
  52. */
  53. // to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1)
  54. const SSH_AGENTC_REQUEST_IDENTITIES = 11;
  55. // this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2).
  56. const SSH_AGENT_IDENTITIES_ANSWER = 12;
  57. // the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3)
  58. const SSH_AGENTC_SIGN_REQUEST = 13;
  59. // the SSH1 response is SSH_AGENT_RSA_RESPONSE (4)
  60. const SSH_AGENT_SIGN_RESPONSE = 14;
  61. /**#@-*/
  62. /**@+
  63. * Agent forwarding status
  64. *
  65. * @access private
  66. */
  67. // no forwarding requested and not active
  68. const FORWARD_NONE = 0;
  69. // request agent forwarding when opportune
  70. const FORWARD_REQUEST = 1;
  71. // forwarding has been request and is active
  72. const FORWARD_ACTIVE = 2;
  73. /**#@-*/
  74. /**
  75. * Unused
  76. */
  77. const SSH_AGENT_FAILURE = 5;
  78. /**
  79. * Socket Resource
  80. *
  81. * @var resource
  82. * @access private
  83. */
  84. var $fsock;
  85. /**
  86. * Agent forwarding status
  87. *
  88. * @access private
  89. */
  90. var $forward_status = self::FORWARD_NONE;
  91. /**
  92. * Buffer for accumulating forwarded authentication
  93. * agent data arriving on SSH data channel destined
  94. * for agent unix socket
  95. *
  96. * @access private
  97. */
  98. var $socket_buffer = '';
  99. /**
  100. * Tracking the number of bytes we are expecting
  101. * to arrive for the agent socket on the SSH data
  102. * channel
  103. */
  104. var $expected_bytes = 0;
  105. /**
  106. * Default Constructor
  107. *
  108. * @return \phpseclib\System\SSH\Agent
  109. * @throws \phpseclib\Exception\BadConfigurationException if SSH_AUTH_SOCK cannot be found
  110. * @throws \RuntimeException on connection errors
  111. * @access public
  112. */
  113. function __construct()
  114. {
  115. switch (true) {
  116. case isset($_SERVER['SSH_AUTH_SOCK']):
  117. $address = $_SERVER['SSH_AUTH_SOCK'];
  118. break;
  119. case isset($_ENV['SSH_AUTH_SOCK']):
  120. $address = $_ENV['SSH_AUTH_SOCK'];
  121. break;
  122. default:
  123. throw new BadConfigurationException('SSH_AUTH_SOCK not found');
  124. }
  125. $this->fsock = fsockopen('unix://' . $address, 0, $errno, $errstr);
  126. if (!$this->fsock) {
  127. throw new \RuntimeException("Unable to connect to ssh-agent (Error $errno: $errstr)");
  128. }
  129. }
  130. /**
  131. * Request Identities
  132. *
  133. * See "2.5.2 Requesting a list of protocol 2 keys"
  134. * Returns an array containing zero or more \phpseclib\System\SSH\Agent\Identity objects
  135. *
  136. * @return array
  137. * @throws \RuntimeException on receipt of unexpected packets
  138. * @access public
  139. */
  140. function requestIdentities()
  141. {
  142. if (!$this->fsock) {
  143. return array();
  144. }
  145. $packet = pack('NC', 1, self::SSH_AGENTC_REQUEST_IDENTITIES);
  146. if (strlen($packet) != fputs($this->fsock, $packet)) {
  147. throw new \RuntimeException('Connection closed while requesting identities');
  148. }
  149. $length = current(unpack('N', fread($this->fsock, 4)));
  150. $type = ord(fread($this->fsock, 1));
  151. if ($type != self::SSH_AGENT_IDENTITIES_ANSWER) {
  152. throw new \RuntimeException('Unable to request identities');
  153. }
  154. $identities = array();
  155. $keyCount = current(unpack('N', fread($this->fsock, 4)));
  156. for ($i = 0; $i < $keyCount; $i++) {
  157. $length = current(unpack('N', fread($this->fsock, 4)));
  158. $key_blob = fread($this->fsock, $length);
  159. $key_str = 'ssh-rsa ' . Base64::encode($key_blob);
  160. $length = current(unpack('N', fread($this->fsock, 4)));
  161. if ($length) {
  162. $key_str.= ' ' . fread($this->fsock, $length);
  163. }
  164. $length = current(unpack('N', substr($key_blob, 0, 4)));
  165. $key_type = substr($key_blob, 4, $length);
  166. switch ($key_type) {
  167. case 'ssh-rsa':
  168. $key = new RSA();
  169. $key->load($key_str);
  170. break;
  171. case 'ssh-dss':
  172. // not currently supported
  173. break;
  174. }
  175. // resources are passed by reference by default
  176. if (isset($key)) {
  177. $identity = new Identity($this->fsock);
  178. $identity->setPublicKey($key);
  179. $identity->setPublicKeyBlob($key_blob);
  180. $identities[] = $identity;
  181. unset($key);
  182. }
  183. }
  184. return $identities;
  185. }
  186. /**
  187. * Signal that agent forwarding should
  188. * be requested when a channel is opened
  189. *
  190. * @param Net_SSH2 $ssh
  191. * @return bool
  192. * @access public
  193. */
  194. function startSSHForwarding($ssh)
  195. {
  196. if ($this->forward_status == self::FORWARD_NONE) {
  197. $this->forward_status = self::FORWARD_REQUEST;
  198. }
  199. }
  200. /**
  201. * Request agent forwarding of remote server
  202. *
  203. * @param Net_SSH2 $ssh
  204. * @return bool
  205. * @access private
  206. */
  207. function _request_forwarding($ssh)
  208. {
  209. $request_channel = $ssh->_get_open_channel();
  210. if ($request_channel === false) {
  211. return false;
  212. }
  213. $packet = pack(
  214. 'CNNa*C',
  215. NET_SSH2_MSG_CHANNEL_REQUEST,
  216. $ssh->server_channels[$request_channel],
  217. strlen('auth-agent-req@openssh.com'),
  218. 'auth-agent-req@openssh.com',
  219. 1
  220. );
  221. $ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_REQUEST;
  222. if (!$ssh->_send_binary_packet($packet)) {
  223. return false;
  224. }
  225. $response = $ssh->_get_channel_packet($request_channel);
  226. if ($response === false) {
  227. return false;
  228. }
  229. $ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_OPEN;
  230. $this->forward_status = self::FORWARD_ACTIVE;
  231. return true;
  232. }
  233. /**
  234. * On successful channel open
  235. *
  236. * This method is called upon successful channel
  237. * open to give the SSH Agent an opportunity
  238. * to take further action. i.e. request agent forwarding
  239. *
  240. * @param Net_SSH2 $ssh
  241. * @access private
  242. */
  243. function _on_channel_open($ssh)
  244. {
  245. if ($this->forward_status == self::FORWARD_REQUEST) {
  246. $this->_request_forwarding($ssh);
  247. }
  248. }
  249. /**
  250. * Forward data to SSH Agent and return data reply
  251. *
  252. * @param string $data
  253. * @return data from SSH Agent
  254. * @throws \RuntimeException on connection errors
  255. * @access private
  256. */
  257. function _forward_data($data)
  258. {
  259. if ($this->expected_bytes > 0) {
  260. $this->socket_buffer.= $data;
  261. $this->expected_bytes -= strlen($data);
  262. } else {
  263. $agent_data_bytes = current(unpack('N', $data));
  264. $current_data_bytes = strlen($data);
  265. $this->socket_buffer = $data;
  266. if ($current_data_bytes != $agent_data_bytes + 4) {
  267. $this->expected_bytes = ($agent_data_bytes + 4) - $current_data_bytes;
  268. return false;
  269. }
  270. }
  271. if (strlen($this->socket_buffer) != fwrite($this->fsock, $this->socket_buffer)) {
  272. throw new \RuntimeException('Connection closed attempting to forward data to SSH agent');
  273. }
  274. $this->socket_buffer = '';
  275. $this->expected_bytes = 0;
  276. $agent_reply_bytes = current(unpack('N', fread($this->fsock, 4)));
  277. $agent_reply_data = fread($this->fsock, $agent_reply_bytes);
  278. $agent_reply_data = current(unpack('a*', $agent_reply_data));
  279. return pack('Na*', $agent_reply_bytes, $agent_reply_data);
  280. }
  281. }