bed501be996151a31ca54560b8b1513b7de975e9
[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
101 /*
102  * ssh version of a security handle allocator.  Logically sets
103  * up a network "connection".
104  */
105 static void
106 ssh_connect(
107     const char *        hostname,
108     char *              (*conf_fn)(char *, void *),
109     void                (*fn)(void *, security_handle_t *, security_status_t),
110     void *              arg,
111     void *              datap)
112 {
113     int result;
114     struct sec_handle *rh;
115     char *amandad_path=NULL, *client_username=NULL, *ssh_keys=NULL;
116
117     assert(fn != NULL);
118     assert(hostname != NULL);
119
120     auth_debug(1, "ssh_connect: %s\n", hostname);
121
122     rh = g_new0(struct sec_handle, 1);
123     security_handleinit(&rh->sech, &ssh_security_driver);
124     rh->hostname = NULL;
125     rh->rs = NULL;
126     rh->ev_timeout = NULL;
127     rh->rc = NULL;
128
129     /* get the canonical hostname */
130     rh->hostname = NULL;
131     if ((result = resolve_hostname(hostname, 0, NULL, &rh->hostname)) != 0
132          || rh->hostname == NULL) {
133         security_seterror(&rh->sech,
134             _("ssh_security could not find canonical name for '%s': %s"),
135             hostname, gai_strerror(result));
136         (*fn)(arg, &rh->sech, S_ERROR);
137         return;
138     }
139     rh->rs = tcpma_stream_client(rh, newhandle++);
140     rh->rc->conf_fn = conf_fn;
141     rh->rc->datap = datap;
142
143     if (rh->rs == NULL)
144         goto error;
145
146     amfree(rh->hostname);
147     rh->hostname = stralloc(rh->rs->rc->hostname);
148
149     /*
150      * We need to open a new connection.
151      *
152      * XXX need to eventually limit number of outgoing connections here.
153      */
154     if(conf_fn) {
155         amandad_path    = conf_fn("amandad_path", datap);
156         client_username = conf_fn("client_username", datap);
157         ssh_keys        = conf_fn("ssh_keys", datap);
158     }
159     if(rh->rc->read == -1) {
160         if (runssh(rh->rs->rc, amandad_path, client_username, ssh_keys) < 0) {
161             security_seterror(&rh->sech, _("can't connect to %s: %s"),
162                               hostname, rh->rs->rc->errmsg);
163             goto error;
164         }
165         rh->rc->refcnt++;
166     }
167
168     /*
169      * The socket will be opened async so hosts that are down won't
170      * block everything.  We need to register a write event
171      * so we will know when the socket comes alive.
172      *
173      * Overload rh->rs->ev_read to provide a write event handle.
174      * We also register a timeout.
175      */
176     rh->fn.connect = fn;
177     rh->arg = arg;
178     rh->rs->ev_read = event_register((event_id_t)rh->rs->rc->write, EV_WRITEFD,
179         sec_connect_callback, rh);
180     rh->ev_timeout = event_register((event_id_t)CONNECT_TIMEOUT, EV_TIME,
181         sec_connect_timeout, rh);
182
183     return;
184
185 error:
186     (*fn)(arg, &rh->sech, S_ERROR);
187 }
188
189 /* like sec_accept, but first it gets the remote system's hostname */
190 static void
191 ssh_accept(
192     const security_driver_t *driver,
193     char       *(*conf_fn)(char *, void *),
194     int         in,
195     int         out,
196     void        (*fn)(security_handle_t *, pkt_t *),
197     void       *datap)
198 {
199     struct sec_handle *rh;
200     struct tcp_conn *rc = sec_tcp_conn_get("", 0);
201     char *ssh_connection, *p;
202     char *errmsg = NULL;
203     sockaddr_union addr;
204     int result;
205
206     /* "Accepting" an SSH connection means that amandad was invoked via sshd, so
207      * we should have anSSH_CONNECTION env var.  If not, then this probably isn't
208      * a real SSH connection and we should bail out. */
209     ssh_connection = getenv("SSH_CONNECTION");
210     if (!ssh_connection) {
211         errmsg = g_strdup("$SSH_CONNECTION not set - was amandad started by sshd?");
212         goto error;
213     }
214
215     /* make a local copy, to munge */
216     ssh_connection = g_strdup(ssh_connection);
217
218     /* strip off the first component - the ASCII IP address */
219     if ((p = strchr(ssh_connection, ' ')) == NULL) {
220         errmsg = g_strdup("$SSH_CONNECTION malformed");
221         goto error;
222     }
223     *p = '\0';
224
225     /* ---- everything from here on is just a warning, leaving hostname at "" */
226
227     SU_INIT(&addr, AF_INET);
228
229     /* turn the string address into a sockaddr */
230     if ((result = str_to_sockaddr(ssh_connection, &addr)) != 1) {
231         if (result == 0) {
232             g_warning("Could not parse peer address %s", ssh_connection);
233         } else {
234             g_warning("Parsing peer address %s: %s", ssh_connection, gai_strerror(result));
235         }
236         goto done;
237     }
238
239     /* find the hostname */
240     result = getnameinfo((struct sockaddr *)&addr, SS_LEN(&addr),
241                  rc->hostname, sizeof(rc->hostname), NULL, 0, 0);
242     if (result != 0) {
243         g_warning("Could not get hostname for SSH client %s: %s", ssh_connection,
244                 gai_strerror(result));
245         goto done;
246     }
247
248     /* and verify it */
249     if (check_name_give_sockaddr(rc->hostname,
250                                  (struct sockaddr *)&addr, &errmsg) < 0) {
251         rc->hostname[0] = '\0'; /* null out the bad hostname */
252         g_warning("Checking SSH client DNS: %s", errmsg);
253         amfree(errmsg);
254         goto done;
255     }
256
257 done:
258     if (ssh_connection)
259         g_free(ssh_connection);
260
261     rc->read = in;
262     rc->write = out;
263     rc->accept_fn = fn;
264     rc->driver = driver;
265     rc->conf_fn = conf_fn;
266     rc->datap = datap;
267     sec_tcp_conn_read(rc);
268     return;
269
270 error:
271     if (ssh_connection)
272         g_free(ssh_connection);
273
274     /* make up a fake handle for the error */
275     rh = g_new0(struct sec_handle, 1);
276     security_handleinit(&rh->sech, driver);
277     security_seterror((security_handle_t*)rh, "ssh_accept: %s", errmsg);
278     amfree(errmsg);
279     (*fn)(&rh->sech, NULL);
280 }
281
282 /*
283  * Forks a ssh to the host listed in rc->hostname
284  * Returns negative on error, with an errmsg in rc->errmsg.
285  */
286 static int
287 runssh(
288     struct tcp_conn *   rc,
289     const char *        amandad_path,
290     const char *        client_username,
291     const char *        ssh_keys)
292 {
293     int rpipe[2], wpipe[2];
294     char *xamandad_path = (char *)amandad_path;
295     char *xclient_username = (char *)client_username;
296     char *xssh_keys = (char *)ssh_keys;
297
298     memset(rpipe, -1, SIZEOF(rpipe));
299     memset(wpipe, -1, SIZEOF(wpipe));
300     if (pipe(rpipe) < 0 || pipe(wpipe) < 0) {
301         rc->errmsg = newvstrallocf(rc->errmsg, _("pipe: %s"), strerror(errno));
302         return (-1);
303     }
304
305     switch (rc->pid = fork()) {
306     case -1:
307         rc->errmsg = newvstrallocf(rc->errmsg, _("fork: %s"), strerror(errno));
308         aclose(rpipe[0]);
309         aclose(rpipe[1]);
310         aclose(wpipe[0]);
311         aclose(wpipe[1]);
312         return (-1);
313     case 0:
314         dup2(wpipe[0], 0);
315         dup2(rpipe[1], 1);
316         break;
317     default:
318         rc->read = rpipe[0];
319         aclose(rpipe[1]);
320         rc->write = wpipe[1];
321         aclose(wpipe[0]);
322         return (0);
323     }
324
325     /* drop root privs for good */
326     set_root_privs(-1);
327
328     safe_fd(-1, 0);
329
330     if(!xamandad_path || strlen(xamandad_path) <= 1) 
331         xamandad_path = vstralloc(amlibexecdir, "/", "amandad", NULL);
332     if(!xclient_username || strlen(xclient_username) <= 1)
333         xclient_username = CLIENT_LOGIN;
334     if(!ssh_keys || strlen(ssh_keys) <= 1) {
335         execlp(SSH, SSH, SSH_OPTIONS, "-l", xclient_username,
336                rc->hostname, xamandad_path, "-auth=ssh", "amdump", "amindexd",
337                "amidxtaped", (char *)NULL);
338     }
339     else {
340         execlp(SSH, SSH, SSH_OPTIONS, "-l", xclient_username,
341                "-i", xssh_keys, rc->hostname, xamandad_path, "-auth=ssh",
342                "amdump", "amindexd", "amidxtaped", (char *)NULL);
343     }
344     error("error: couldn't exec %s: %s", SSH, strerror(errno));
345
346     /* should never go here, shut up compiler warning */
347     return(-1);
348 }