Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

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