Imported Upstream version 3.3.2
[debian/amanda] / common-src / ssh-security.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1999 University of Maryland
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26
27 /*
28  * $Id: ssh-security.c,v 1.23 2006/08/21 20:17:10 martinea Exp $
29  *
30  * ssh-security.c - security and transport over ssh or a ssh-like command.
31  *
32  * XXX still need to check for initial keyword on connect so we can skip
33  * over shell garbage and other stuff that ssh might want to spew out.
34  */
35
36 #include "amanda.h"
37 #include "util.h"
38 #include "event.h"
39 #include "packet.h"
40 #include "security.h"
41 #include "security-util.h"
42 #include "sockaddr-util.h"
43 #include "stream.h"
44
45 /*
46  * Number of seconds ssh has to start up
47  */
48 #define CONNECT_TIMEOUT 20
49
50 /*
51  * Magic values for ssh_conn->handle
52  */
53 #define H_TAKEN -1              /* ssh_conn->tok was already read */
54 #define H_EOF   -2              /* this connection has been shut down */
55
56 /*
57  * Interface functions
58  */
59 static void     ssh_connect(const char *, char *(*)(char *, void *),
60                         void (*)(void *, security_handle_t *, security_status_t),
61                         void *, void *);
62 static void ssh_accept(const security_driver_t *driver, char *(*conf_fn)(char *, void *),
63                         int in, int out,
64                         void (*fn)(security_handle_t *, pkt_t *),
65                         void *datap);
66
67 /*
68  * This is our interface to the outside world.
69  */
70 const security_driver_t ssh_security_driver = {
71     "SSH",
72     ssh_connect,
73     ssh_accept,
74     sec_get_authenticated_peer_name_hostname,
75     sec_close,
76     stream_sendpkt,
77     stream_recvpkt,
78     stream_recvpkt_cancel,
79     tcpma_stream_server,
80     tcpma_stream_accept,
81     tcpma_stream_client,
82     tcpma_stream_close,
83     sec_stream_auth,
84     sec_stream_id,
85     tcpm_stream_write,
86     tcpm_stream_read,
87     tcpm_stream_read_sync,
88     tcpm_stream_read_cancel,
89     tcpm_close_connection,
90     NULL,
91     NULL
92 };
93
94 static int newhandle = 1;
95
96 /*
97  * Local functions
98  */
99 static int runssh(struct tcp_conn *, const char *, const char *, const char *,
100                   const char *);
101
102 /*
103  * ssh version of a security handle allocator.  Logically sets
104  * up a network "connection".
105  */
106 static void
107 ssh_connect(
108     const char *        hostname,
109     char *              (*conf_fn)(char *, void *),
110     void                (*fn)(void *, security_handle_t *, security_status_t),
111     void *              arg,
112     void *              datap)
113 {
114     int result;
115     struct sec_handle *rh;
116     char *amandad_path=NULL, *client_username=NULL, *ssh_keys=NULL;
117     char *client_port = NULL;
118
119     assert(fn != NULL);
120     assert(hostname != NULL);
121
122     auth_debug(1, "ssh_connect: %s\n", hostname);
123
124     rh = g_new0(struct sec_handle, 1);
125     security_handleinit(&rh->sech, &ssh_security_driver);
126     rh->hostname = NULL;
127     rh->rs = NULL;
128     rh->ev_timeout = NULL;
129     rh->rc = NULL;
130
131     /* get the canonical hostname */
132     rh->hostname = NULL;
133     if ((result = resolve_hostname(hostname, 0, NULL, &rh->hostname)) != 0
134          || rh->hostname == NULL) {
135         security_seterror(&rh->sech,
136             _("ssh_security could not find canonical name for '%s': %s"),
137             hostname, gai_strerror(result));
138         (*fn)(arg, &rh->sech, S_ERROR);
139         return;
140     }
141     rh->rs = tcpma_stream_client(rh, newhandle++);
142     rh->rc->conf_fn = conf_fn;
143     rh->rc->datap = datap;
144
145     if (rh->rs == NULL)
146         goto error;
147
148     amfree(rh->hostname);
149     rh->hostname = stralloc(rh->rs->rc->hostname);
150
151     /*
152      * We need to open a new connection.
153      *
154      * XXX need to eventually limit number of outgoing connections here.
155      */
156     if(conf_fn) {
157         char *port_str;
158         amandad_path    = conf_fn("amandad_path", datap);
159         client_username = conf_fn("client_username", datap);
160         ssh_keys        = conf_fn("ssh_keys", datap);
161         port_str        = conf_fn("client_port", datap);
162         if (port_str && strlen(port_str) >= 1) {
163             client_port = port_str;
164         }
165     }
166     if(rh->rc->read == -1) {
167         if (runssh(rh->rs->rc, amandad_path, client_username, ssh_keys,
168                    client_port) < 0) {
169             security_seterror(&rh->sech, _("can't connect to %s: %s"),
170                               hostname, rh->rs->rc->errmsg);
171             goto error;
172         }
173         rh->rc->refcnt++;
174     }
175
176     /*
177      * The socket will be opened async so hosts that are down won't
178      * block everything.  We need to register a write event
179      * so we will know when the socket comes alive.
180      *
181      * Overload rh->rs->ev_read to provide a write event handle.
182      * We also register a timeout.
183      */
184     rh->fn.connect = fn;
185     rh->arg = arg;
186     rh->rs->ev_read = event_register((event_id_t)rh->rs->rc->write, EV_WRITEFD,
187         sec_connect_callback, rh);
188     rh->ev_timeout = event_register((event_id_t)CONNECT_TIMEOUT, EV_TIME,
189         sec_connect_timeout, rh);
190
191     return;
192
193 error:
194     (*fn)(arg, &rh->sech, S_ERROR);
195 }
196
197 /* like sec_accept, but first it gets the remote system's hostname */
198 static void
199 ssh_accept(
200     const security_driver_t *driver,
201     char       *(*conf_fn)(char *, void *),
202     int         in,
203     int         out,
204     void        (*fn)(security_handle_t *, pkt_t *),
205     void       *datap)
206 {
207     struct sec_handle *rh;
208     struct tcp_conn *rc = sec_tcp_conn_get("", 0);
209     char *ssh_connection, *p;
210     char *errmsg = NULL;
211     sockaddr_union addr;
212     int result;
213
214     /* "Accepting" an SSH connection means that amandad was invoked via sshd, so
215      * we should have anSSH_CONNECTION env var.  If not, then this probably isn't
216      * a real SSH connection and we should bail out. */
217     ssh_connection = getenv("SSH_CONNECTION");
218     if (!ssh_connection) {
219         errmsg = g_strdup("$SSH_CONNECTION not set - was amandad started by sshd?");
220         goto error;
221     }
222
223     /* make a local copy, to munge */
224     ssh_connection = g_strdup(ssh_connection);
225
226     /* strip off the first component - the ASCII IP address */
227     if ((p = strchr(ssh_connection, ' ')) == NULL) {
228         errmsg = g_strdup("$SSH_CONNECTION malformed");
229         goto error;
230     }
231     *p = '\0';
232
233     /* ---- everything from here on is just a warning, leaving hostname at "" */
234
235     SU_INIT(&addr, AF_INET);
236
237     /* turn the string address into a sockaddr */
238     if ((result = str_to_sockaddr(ssh_connection, &addr)) != 1) {
239         if (result == 0) {
240             g_warning("Could not parse peer address %s", ssh_connection);
241         } else {
242             g_warning("Parsing peer address %s: %s", ssh_connection, gai_strerror(result));
243         }
244         goto done;
245     }
246
247     /* find the hostname */
248     result = getnameinfo((struct sockaddr *)&addr, SS_LEN(&addr),
249                  rc->hostname, sizeof(rc->hostname), NULL, 0, 0);
250     if (result != 0) {
251         g_warning("Could not get hostname for SSH client %s: %s", ssh_connection,
252                 gai_strerror(result));
253         goto done;
254     }
255
256     /* and verify it */
257     if (check_name_give_sockaddr(rc->hostname,
258                                  (struct sockaddr *)&addr, &errmsg) < 0) {
259         rc->hostname[0] = '\0'; /* null out the bad hostname */
260         g_warning("Checking SSH client DNS: %s", errmsg);
261         amfree(errmsg);
262         goto done;
263     }
264
265 done:
266     if (ssh_connection)
267         g_free(ssh_connection);
268
269     rc->read = in;
270     rc->write = out;
271     rc->accept_fn = fn;
272     rc->driver = driver;
273     rc->conf_fn = conf_fn;
274     rc->datap = datap;
275     sec_tcp_conn_read(rc);
276     return;
277
278 error:
279     if (ssh_connection)
280         g_free(ssh_connection);
281
282     /* make up a fake handle for the error */
283     rh = g_new0(struct sec_handle, 1);
284     security_handleinit(&rh->sech, driver);
285     security_seterror((security_handle_t*)rh, "ssh_accept: %s", errmsg);
286     amfree(errmsg);
287     (*fn)(&rh->sech, NULL);
288 }
289
290 /*
291  * Forks a ssh to the host listed in rc->hostname
292  * Returns negative on error, with an errmsg in rc->errmsg.
293  */
294 static int
295 runssh(
296     struct tcp_conn *   rc,
297     const char *        amandad_path,
298     const char *        client_username,
299     const char *        ssh_keys,
300     const char *        client_port)
301 {
302     int rpipe[2], wpipe[2];
303     char *xamandad_path = (char *)amandad_path;
304     char *xclient_username = (char *)client_username;
305     char *xssh_keys = (char *)ssh_keys;
306     char *xclient_port = (char *)client_port;
307     GPtrArray *myargs;
308     gchar *ssh_options[100] = {SSH_OPTIONS, NULL};
309     gchar **ssh_option;
310     gchar *cmd;
311
312     memset(rpipe, -1, SIZEOF(rpipe));
313     memset(wpipe, -1, SIZEOF(wpipe));
314     if (pipe(rpipe) < 0 || pipe(wpipe) < 0) {
315         rc->errmsg = newvstrallocf(rc->errmsg, _("pipe: %s"), strerror(errno));
316         return (-1);
317     }
318
319     if(!xamandad_path || strlen(xamandad_path) <= 1) 
320         xamandad_path = vstralloc(amlibexecdir, "/", "amandad", NULL);
321     if(!xclient_username || strlen(xclient_username) <= 1)
322         xclient_username = CLIENT_LOGIN;
323     if(!xclient_port || strlen(xclient_port) <= 1)
324         xclient_port = NULL;
325
326     myargs = g_ptr_array_sized_new(20);
327     g_ptr_array_add(myargs, SSH);
328     for (ssh_option = ssh_options; *ssh_option != NULL; ssh_option++) {
329         g_ptr_array_add(myargs, *ssh_option);
330     }
331     g_ptr_array_add(myargs, "-l");
332     g_ptr_array_add(myargs, xclient_username);
333     if (xclient_port) {
334         g_ptr_array_add(myargs, "-p");
335         g_ptr_array_add(myargs, xclient_port);
336     }
337     if (ssh_keys && strlen(ssh_keys) > 1) {
338         g_ptr_array_add(myargs, "-i");
339         g_ptr_array_add(myargs, xssh_keys);
340     }
341     g_ptr_array_add(myargs, rc->hostname);
342     g_ptr_array_add(myargs, xamandad_path);
343     g_ptr_array_add(myargs, "-auth=ssh");
344     g_ptr_array_add(myargs, NULL);
345
346     cmd = g_strjoinv(" ", (gchar **)myargs->pdata);
347     g_debug("exec: %s", cmd);
348     g_free(cmd);
349
350     switch (rc->pid = fork()) {
351     case -1:
352         rc->errmsg = newvstrallocf(rc->errmsg, _("fork: %s"), strerror(errno));
353         aclose(rpipe[0]);
354         aclose(rpipe[1]);
355         aclose(wpipe[0]);
356         aclose(wpipe[1]);
357         return (-1);
358     case 0:
359         dup2(wpipe[0], 0);
360         dup2(rpipe[1], 1);
361         break;
362     default:
363         rc->read = rpipe[0];
364         aclose(rpipe[1]);
365         rc->write = wpipe[1];
366         aclose(wpipe[0]);
367         return (0);
368     }
369
370     /* drop root privs for good */
371     set_root_privs(-1);
372
373     safe_fd(-1, 0);
374
375     execvp(SSH, (gchar **)myargs->pdata);
376
377     error("error: couldn't exec %s: %s", SSH, strerror(errno));
378
379     /* should never go here, shut up compiler warning */
380     return(-1);
381 }