1 /*
2  * agent.c - ssh agent functions
3  *
4  * This file is part of the SSH Library
5  *
6  * Copyright (c) 2008-2013 by Andreas Schneider <asn@cryptomilk.org>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /* This file is based on authfd.c from OpenSSH */
24 
25 /*
26  * How does the ssh-agent work?
27  *
28  * a) client sends a request to get a list of all keys
29  *    the agent returns the count and all public keys
30  * b) iterate over them to check if the server likes one
31  * c) the client sends a sign request to the agent
32  *    type, pubkey as blob, data to sign, flags
33  *    the agent returns the signed data
34  */
35 
36 #ifndef _WIN32
37 
38 #include "config.h"
39 
40 #include <stdlib.h>
41 #include <errno.h>
42 #include <string.h>
43 #include <stdio.h>
44 
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 
52 #include "libssh/agent.h"
53 #include "libssh/priv.h"
54 #include "libssh/socket.h"
55 #include "libssh/buffer.h"
56 #include "libssh/session.h"
57 #include "libssh/poll.h"
58 #include "libssh/pki.h"
59 #include "libssh/bytearray.h"
60 
61 /* macro to check for "agent failure" message */
62 #define agent_failed(x) \
63   (((x) == SSH_AGENT_FAILURE) || ((x) == SSH_COM_AGENT2_FAILURE) || \
64    ((x) == SSH2_AGENT_FAILURE))
65 
atomicio(struct ssh_agent_struct * agent,void * buf,size_t n,int do_read)66 static size_t atomicio(struct ssh_agent_struct *agent, void *buf, size_t n, int do_read) {
67   char *b = buf;
68   size_t pos = 0;
69   ssize_t res;
70   ssh_pollfd_t pfd;
71   ssh_channel channel = agent->channel;
72   socket_t fd;
73 
74   /* Using a socket ? */
75   if (channel == NULL) {
76     fd = ssh_socket_get_fd(agent->sock);
77     pfd.fd = fd;
78     pfd.events = do_read ? POLLIN : POLLOUT;
79 
80     while (n > pos) {
81       if (do_read) {
82         res = read(fd, b + pos, n - pos);
83       } else {
84         res = write(fd, b + pos, n - pos);
85       }
86       switch (res) {
87       case -1:
88         if (errno == EINTR) {
89           continue;
90         }
91 #ifdef EWOULDBLOCK
92         if (errno == EAGAIN || errno == EWOULDBLOCK) {
93 #else
94           if (errno == EAGAIN) {
95 #endif
96             (void) ssh_poll(&pfd, 1, -1);
97             continue;
98           }
99           return 0;
100       case 0:
101         /* read returns 0 on end-of-file */
102         errno = do_read ? 0 : EPIPE;
103         return pos;
104       default:
105         pos += (size_t) res;
106         }
107       }
108       return pos;
109     } else {
110       /* using an SSH channel */
111       while (n > pos){
112         if (do_read)
113           res = ssh_channel_read(channel,b + pos, n-pos, 0);
114         else
115           res = ssh_channel_write(channel, b+pos, n-pos);
116         if (res == SSH_AGAIN)
117           continue;
118         if (res == SSH_ERROR)
119           return 0;
120         pos += (size_t)res;
121       }
122       return pos;
123     }
124 }
125 
126 ssh_agent ssh_agent_new(struct ssh_session_struct *session) {
127   ssh_agent agent = NULL;
128 
129   agent = malloc(sizeof(struct ssh_agent_struct));
130   if (agent == NULL) {
131     return NULL;
132   }
133   ZERO_STRUCTP(agent);
134 
135   agent->count = 0;
136   agent->sock = ssh_socket_new(session);
137   if (agent->sock == NULL) {
138     SAFE_FREE(agent);
139     return NULL;
140   }
141   agent->channel = NULL;
142   return agent;
143 }
144 
145 static void agent_set_channel(struct ssh_agent_struct *agent, ssh_channel channel){
146   agent->channel = channel;
147 }
148 
149 /** @brief sets the SSH agent channel.
150  * The SSH agent channel will be used to authenticate this client using
151  * an agent through a channel, from another session. The most likely use
152  * is to implement SSH Agent forwarding into a SSH proxy.
153  * @param[in] channel a SSH channel from another session.
154  * @returns SSH_OK in case of success
155  *          SSH_ERROR in case of an error
156  */
157 int ssh_set_agent_channel(ssh_session session, ssh_channel channel){
158   if (!session)
159     return SSH_ERROR;
160   if (!session->agent){
161     ssh_set_error(session, SSH_REQUEST_DENIED, "Session has no active agent");
162     return SSH_ERROR;
163   }
164   agent_set_channel(session->agent, channel);
165   return SSH_OK;
166 }
167 
168 /** @brief sets the SSH agent socket.
169  * The SSH agent will be used to authenticate this client using
170  * the given socket to communicate with the ssh-agent. The caller
171  * is responsible for connecting to the socket prior to calling
172  * this function.
173  * @returns SSH_OK in case of success
174  *          SSH_ERROR in case of an error
175  */
176 int ssh_set_agent_socket(ssh_session session, socket_t fd){
177   if (!session)
178     return SSH_ERROR;
179   if (!session->agent){
180     ssh_set_error(session, SSH_REQUEST_DENIED, "Session has no active agent");
181     return SSH_ERROR;
182   }
183 
184   ssh_socket_set_fd(session->agent->sock, fd);
185   return SSH_OK;
186 }
187 
188 void ssh_agent_close(struct ssh_agent_struct *agent) {
189   if (agent == NULL) {
190     return;
191   }
192 
193   ssh_socket_close(agent->sock);
194 }
195 
196 void ssh_agent_free(ssh_agent agent) {
197   if (agent) {
198     if (agent->ident) {
199       SSH_BUFFER_FREE(agent->ident);
200     }
201     if (agent->sock) {
202       ssh_agent_close(agent);
203       ssh_socket_free(agent->sock);
204     }
205     SAFE_FREE(agent);
206   }
207 }
208 
209 static int agent_connect(ssh_session session) {
210   const char *auth_sock = NULL;
211 
212   if (session == NULL || session->agent == NULL) {
213     return -1;
214   }
215 
216   if (session->agent->channel != NULL)
217     return 0;
218 
219   auth_sock = getenv("SSH_AUTH_SOCK");
220 
221   if (auth_sock && *auth_sock) {
222     if (ssh_socket_unix(session->agent->sock, auth_sock) < 0) {
223       return -1;
224     }
225     return 0;
226   }
227 
228   return -1;
229 }
230 
231 #if 0
232 static int agent_decode_reply(struct ssh_session_struct *session, int type) {
233   switch (type) {
234     case SSH_AGENT_FAILURE:
235     case SSH2_AGENT_FAILURE:
236     case SSH_COM_AGENT2_FAILURE:
237       ssh_log(session, SSH_LOG_RARE, "SSH_AGENT_FAILURE");
238       return 0;
239     case SSH_AGENT_SUCCESS:
240       return 1;
241     default:
242       ssh_set_error(session, SSH_FATAL,
243           "Bad response from authentication agent: %d", type);
244       break;
245   }
246 
247   return -1;
248 }
249 #endif
250 
251 static int agent_talk(struct ssh_session_struct *session,
252     struct ssh_buffer_struct *request, struct ssh_buffer_struct *reply) {
253   uint32_t len = 0;
254   uint8_t payload[1024] = {0};
255 
256   len = ssh_buffer_get_len(request);
257   SSH_LOG(SSH_LOG_TRACE, "Request length: %u", len);
258   PUSH_BE_U32(payload, 0, len);
259 
260   /* send length and then the request packet */
261   if (atomicio(session->agent, payload, 4, 0) == 4) {
262     if (atomicio(session->agent, ssh_buffer_get(request), len, 0)
263         != len) {
264       SSH_LOG(SSH_LOG_WARN, "atomicio sending request failed: %s",
265           strerror(errno));
266       return -1;
267     }
268   } else {
269     SSH_LOG(SSH_LOG_WARN,
270         "atomicio sending request length failed: %s",
271         strerror(errno));
272     return -1;
273   }
274 
275   /* wait for response, read the length of the response packet */
276   if (atomicio(session->agent, payload, 4, 1) != 4) {
277     SSH_LOG(SSH_LOG_WARN, "atomicio read response length failed: %s",
278         strerror(errno));
279     return -1;
280   }
281 
282   len = PULL_BE_U32(payload, 0);
283   if (len > 256 * 1024) {
284     ssh_set_error(session, SSH_FATAL,
285         "Authentication response too long: %u", len);
286     return -1;
287   }
288   SSH_LOG(SSH_LOG_TRACE, "Response length: %u", len);
289 
290   while (len > 0) {
291     size_t n = len;
292     if (n > sizeof(payload)) {
293       n = sizeof(payload);
294     }
295     if (atomicio(session->agent, payload, n, 1) != n) {
296       SSH_LOG(SSH_LOG_WARN,
297           "Error reading response from authentication socket.");
298       return -1;
299     }
300     if (ssh_buffer_add_data(reply, payload, n) < 0) {
301       SSH_LOG(SSH_LOG_WARN, "Not enough space");
302       return -1;
303     }
304     len -= n;
305   }
306 
307   return 0;
308 }
309 
310 uint32_t ssh_agent_get_ident_count(struct ssh_session_struct *session)
311 {
312     ssh_buffer request = NULL;
313     ssh_buffer reply = NULL;
314     unsigned int type = 0;
315     uint32_t count = 0;
316     int rc;
317 
318     /* send message to the agent requesting the list of identities */
319     request = ssh_buffer_new();
320     if (request == NULL) {
321         ssh_set_error_oom(session);
322         return 0;
323     }
324     if (ssh_buffer_add_u8(request, SSH2_AGENTC_REQUEST_IDENTITIES) < 0) {
325         ssh_set_error_oom(session);
326         SSH_BUFFER_FREE(request);
327         return 0;
328     }
329 
330     reply = ssh_buffer_new();
331     if (reply == NULL) {
332         SSH_BUFFER_FREE(request);
333         ssh_set_error(session, SSH_FATAL, "Not enough space");
334         return 0;
335     }
336 
337     if (agent_talk(session, request, reply) < 0) {
338         SSH_BUFFER_FREE(request);
339         SSH_BUFFER_FREE(reply);
340         return 0;
341     }
342     SSH_BUFFER_FREE(request);
343 
344     /* get message type and verify the answer */
345     rc = ssh_buffer_get_u8(reply, (uint8_t *) &type);
346     if (rc != sizeof(uint8_t)) {
347         ssh_set_error(session, SSH_FATAL,
348                 "Bad authentication reply size: %d", rc);
349         SSH_BUFFER_FREE(reply);
350         return 0;
351     }
352 #ifdef WORDS_BIGENDIAN
353     type = bswap_32(type);
354 #endif
355 
356     SSH_LOG(SSH_LOG_WARN,
357             "Answer type: %d, expected answer: %d",
358             type, SSH2_AGENT_IDENTITIES_ANSWER);
359 
360     if (agent_failed(type)) {
361         SSH_BUFFER_FREE(reply);
362         return 0;
363     } else if (type != SSH2_AGENT_IDENTITIES_ANSWER) {
364         ssh_set_error(session, SSH_FATAL,
365                 "Bad authentication reply message type: %u", type);
366         SSH_BUFFER_FREE(reply);
367         return 0;
368     }
369 
370     rc = ssh_buffer_get_u32(reply, &count);
371     if (rc != 4) {
372         ssh_set_error(session,
373                 SSH_FATAL,
374                 "Failed to read count");
375         SSH_BUFFER_FREE(reply);
376         return 0;
377     }
378     session->agent->count = ntohl(count);
379     SSH_LOG(SSH_LOG_DEBUG, "Agent count: %d",
380             session->agent->count);
381     if (session->agent->count > 1024) {
382         ssh_set_error(session, SSH_FATAL,
383                 "Too many identities in authentication reply: %d",
384                 session->agent->count);
385         SSH_BUFFER_FREE(reply);
386         return 0;
387     }
388 
389     if (session->agent->ident) {
390         ssh_buffer_reinit(session->agent->ident);
391     }
392     session->agent->ident = reply;
393 
394     return session->agent->count;
395 }
396 
397 /* caller has to free commment */
398 ssh_key ssh_agent_get_first_ident(struct ssh_session_struct *session,
399                               char **comment) {
400     if (ssh_agent_get_ident_count(session) > 0) {
401         return ssh_agent_get_next_ident(session, comment);
402     }
403 
404     return NULL;
405 }
406 
407 /* caller has to free commment */
408 ssh_key ssh_agent_get_next_ident(struct ssh_session_struct *session,
409     char **comment) {
410     struct ssh_key_struct *key;
411     struct ssh_string_struct *blob = NULL;
412     struct ssh_string_struct *tmp = NULL;
413     int rc;
414 
415     if (session->agent->count == 0) {
416         return NULL;
417     }
418 
419     /* get the blob */
420     blob = ssh_buffer_get_ssh_string(session->agent->ident);
421     if (blob == NULL) {
422         return NULL;
423     }
424 
425     /* get the comment */
426     tmp = ssh_buffer_get_ssh_string(session->agent->ident);
427     if (tmp == NULL) {
428         SSH_STRING_FREE(blob);
429 
430         return NULL;
431     }
432 
433     if (comment) {
434         *comment = ssh_string_to_char(tmp);
435     } else {
436         SSH_STRING_FREE(blob);
437         SSH_STRING_FREE(tmp);
438 
439         return NULL;
440     }
441     SSH_STRING_FREE(tmp);
442 
443     /* get key from blob */
444     rc = ssh_pki_import_pubkey_blob(blob, &key);
445     if (rc == SSH_ERROR) {
446         /* Try again as a cert. */
447         rc = ssh_pki_import_cert_blob(blob, &key);
448     }
449     SSH_STRING_FREE(blob);
450     if (rc == SSH_ERROR) {
451         return NULL;
452     }
453 
454     return key;
455 }
456 
457 int ssh_agent_is_running(ssh_session session) {
458   if (session == NULL || session->agent == NULL) {
459     return 0;
460   }
461 
462   if (ssh_socket_is_open(session->agent->sock)) {
463     return 1;
464   } else {
465     if (agent_connect(session) < 0) {
466       return 0;
467     } else {
468       return 1;
469     }
470   }
471 
472   return 0;
473 }
474 
475 ssh_string ssh_agent_sign_data(ssh_session session,
476                                const ssh_key pubkey,
477                                struct ssh_buffer_struct *data)
478 {
479     ssh_buffer request;
480     ssh_buffer reply;
481     ssh_string key_blob;
482     ssh_string sig_blob;
483     unsigned int type = 0;
484     unsigned int flags = 0;
485     uint32_t dlen;
486     int rc;
487 
488     request = ssh_buffer_new();
489     if (request == NULL) {
490         return NULL;
491     }
492 
493     /* create request */
494     if (ssh_buffer_add_u8(request, SSH2_AGENTC_SIGN_REQUEST) < 0) {
495         SSH_BUFFER_FREE(request);
496         return NULL;
497     }
498 
499     rc = ssh_pki_export_pubkey_blob(pubkey, &key_blob);
500     if (rc < 0) {
501         SSH_BUFFER_FREE(request);
502         return NULL;
503     }
504 
505     /*
506      * make sure it already can contain all the expected content:
507      * - 1 x uint8_t
508      * - 2 x uint32_t
509      * - 1 x ssh_string (uint8_t + data)
510      */
511     rc = ssh_buffer_allocate_size(request,
512                                   sizeof(uint8_t) * 2 +
513                                   sizeof(uint32_t) * 2 +
514                                   ssh_string_len(key_blob));
515     if (rc < 0) {
516         SSH_BUFFER_FREE(request);
517         return NULL;
518     }
519 
520     /* adds len + blob */
521     rc = ssh_buffer_add_ssh_string(request, key_blob);
522     SSH_STRING_FREE(key_blob);
523     if (rc < 0) {
524         SSH_BUFFER_FREE(request);
525         return NULL;
526     }
527 
528     /* Add data */
529     dlen = ssh_buffer_get_len(data);
530     if (ssh_buffer_add_u32(request, htonl(dlen)) < 0) {
531         SSH_BUFFER_FREE(request);
532         return NULL;
533     }
534     if (ssh_buffer_add_data(request, ssh_buffer_get(data), dlen) < 0) {
535         SSH_BUFFER_FREE(request);
536         return NULL;
537     }
538 
539     /* Add Flags: SHA2 extension (RFC 8332) if negotiated */
540     if (ssh_key_type_plain(pubkey->type) == SSH_KEYTYPE_RSA) {
541         if (session->extensions & SSH_EXT_SIG_RSA_SHA512) {
542             flags |= SSH_AGENT_RSA_SHA2_512;
543         } else if (session->extensions & SSH_EXT_SIG_RSA_SHA256) {
544             flags |= SSH_AGENT_RSA_SHA2_256;
545         }
546     }
547     if (ssh_buffer_add_u32(request, htonl(flags)) < 0) {
548         SSH_BUFFER_FREE(request);
549         return NULL;
550     }
551 
552     reply = ssh_buffer_new();
553     if (reply == NULL) {
554         SSH_BUFFER_FREE(request);
555         return NULL;
556     }
557 
558     /* send the request */
559     if (agent_talk(session, request, reply) < 0) {
560         SSH_BUFFER_FREE(request);
561         SSH_BUFFER_FREE(reply);
562         return NULL;
563     }
564     SSH_BUFFER_FREE(request);
565 
566     /* check if reply is valid */
567     if (ssh_buffer_get_u8(reply, (uint8_t *) &type) != sizeof(uint8_t)) {
568         SSH_BUFFER_FREE(reply);
569         return NULL;
570     }
571 #ifdef WORDS_BIGENDIAN
572     type = bswap_32(type);
573 #endif
574 
575     if (agent_failed(type)) {
576         SSH_LOG(SSH_LOG_WARN, "Agent reports failure in signing the key");
577         SSH_BUFFER_FREE(reply);
578         return NULL;
579     } else if (type != SSH2_AGENT_SIGN_RESPONSE) {
580         ssh_set_error(session,
581                       SSH_FATAL,
582                       "Bad authentication response: %u",
583                       type);
584         SSH_BUFFER_FREE(reply);
585         return NULL;
586     }
587 
588     sig_blob = ssh_buffer_get_ssh_string(reply);
589     SSH_BUFFER_FREE(reply);
590 
591     return sig_blob;
592 }
593 
594 #endif /* _WIN32 */
595