]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/subversion/subversion/libsvn_subr/gpg_agent.c
Update ELF Tool Chain to upstream rev 3400
[FreeBSD/FreeBSD.git] / contrib / subversion / subversion / libsvn_subr / gpg_agent.c
1 /*
2  * gpg_agent.c: GPG Agent provider for SVN_AUTH_CRED_*
3  *
4  * ====================================================================
5  *    Licensed to the Apache Software Foundation (ASF) under one
6  *    or more contributor license agreements.  See the NOTICE file
7  *    distributed with this work for additional information
8  *    regarding copyright ownership.  The ASF licenses this file
9  *    to you under the Apache License, Version 2.0 (the
10  *    "License"); you may not use this file except in compliance
11  *    with the License.  You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *    Unless required by applicable law or agreed to in writing,
16  *    software distributed under the License is distributed on an
17  *    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18  *    KIND, either express or implied.  See the License for the
19  *    specific language governing permissions and limitations
20  *    under the License.
21  * ====================================================================
22  */
23
24 /* ==================================================================== */
25
26 /* This auth provider stores a plaintext password in memory managed by
27  * a running gpg-agent. In contrast to other password store providers
28  * it does not save the password to disk.
29  *
30  * Prompting is performed by the gpg-agent using a "pinentry" program
31  * which needs to be installed separately. There are several pinentry
32  * implementations with different front-ends (e.g. qt, gtk, ncurses).
33  *
34  * The gpg-agent will let the password time out after a while,
35  * or immediately when it receives the SIGHUP signal.
36  * When the password has timed out it will automatically prompt the
37  * user for the password again. This is transparent to Subversion.
38  *
39  * SECURITY CONSIDERATIONS:
40  *
41  * Communication to the agent happens over a UNIX socket, which is located
42  * in a directory which only the user running Subversion can access.
43  * However, any program the user runs could access this socket and get
44  * the Subversion password if the program knows the "cache ID" Subversion
45  * uses for the password.
46  * The cache ID is very easy to obtain for programs running as the same user.
47  * Subversion uses the MD5 of the realmstring as cache ID, and these checksums
48  * are also used as filenames within ~/.subversion/auth/svn.simple.
49  * Unlike GNOME Keyring or KDE Wallet, the user is not prompted for
50  * permission if another program attempts to access the password.
51  *
52  * Therefore, while the gpg-agent is running and has the password cached,
53  * this provider is no more secure than a file storing the password in
54  * plaintext.
55  */
56
57 \f
58 /*** Includes. ***/
59
60 #ifndef WIN32
61
62 #include <unistd.h>
63
64 #include <sys/socket.h>
65 #include <sys/un.h>
66
67 #include <apr_pools.h>
68 #include "svn_auth.h"
69 #include "svn_config.h"
70 #include "svn_error.h"
71 #include "svn_pools.h"
72 #include "svn_cmdline.h"
73 #include "svn_checksum.h"
74 #include "svn_string.h"
75 #include "svn_hash.h"
76 #include "svn_user.h"
77 #include "svn_dirent_uri.h"
78
79 #include "auth.h"
80 #include "private/svn_auth_private.h"
81
82 #include "svn_private_config.h"
83
84 #ifdef SVN_HAVE_GPG_AGENT
85
86 #define BUFFER_SIZE 1024
87 #define ATTEMPT_PARAMETER "svn.simple.gpg_agent.attempt"
88
89 /* Modify STR in-place such that blanks are escaped as required by the
90  * gpg-agent protocol. Return a pointer to STR. */
91 static char *
92 escape_blanks(char *str)
93 {
94   char *s = str;
95
96   while (*s)
97     {
98       if (*s == ' ')
99         *s = '+';
100       s++;
101     }
102
103   return str;
104 }
105
106 /* Generate the string CACHE_ID_P based on the REALMSTRING allocated in
107  * RESULT_POOL using SCRATCH_POOL for temporary allocations.  This is similar
108  * to other password caching mechanisms. */
109 static svn_error_t *
110 get_cache_id(const char **cache_id_p, const char *realmstring,
111              apr_pool_t *result_pool, apr_pool_t *scratch_pool)
112 {
113   const char *cache_id = NULL;
114   svn_checksum_t *digest = NULL;
115
116   SVN_ERR(svn_checksum(&digest, svn_checksum_md5, realmstring,
117                        strlen(realmstring), scratch_pool));
118   cache_id = svn_checksum_to_cstring(digest, result_pool);
119   *cache_id_p = cache_id;
120
121   return SVN_NO_ERROR;
122 }
123
124 /* Attempt to read a gpg-agent response message from the socket SD into
125  * buffer BUF. Buf is assumed to be N bytes large. Return TRUE if a response
126  * message could be read that fits into the buffer. Else return FALSE.
127  * If a message could be read it will always be NUL-terminated and the
128  * trailing newline is retained. */
129 static svn_boolean_t
130 receive_from_gpg_agent(int sd, char *buf, size_t n)
131 {
132   int i = 0;
133   size_t recvd;
134   char c;
135
136   /* Clear existing buffer content before reading response. */
137   if (n > 0)
138     *buf = '\0';
139
140   /* Require the message to fit into the buffer and be terminated
141    * with a newline. */
142   while (i < n)
143     {
144       recvd = read(sd, &c, 1);
145       if (recvd == -1)
146         return FALSE;
147       buf[i] = c;
148       i++;
149       if (i < n && c == '\n')
150         {
151           buf[i] = '\0';
152           return TRUE;
153         }
154     }
155
156     return FALSE;
157 }
158
159 /* Using socket SD, send the option OPTION with the specified VALUE
160  * to the gpg agent. Store the response in BUF, assumed to be N bytes
161  * in size, and evaluate the response. Return TRUE if the agent liked
162  * the smell of the option, if there is such a thing, and doesn't feel
163  * saturated by it. Else return FALSE.
164  * Do temporary allocations in scratch_pool. */
165 static svn_boolean_t
166 send_option(int sd, char *buf, size_t n, const char *option, const char *value,
167             apr_pool_t *scratch_pool)
168 {
169   const char *request;
170
171   request = apr_psprintf(scratch_pool, "OPTION %s=%s\n", option, value);
172
173   if (write(sd, request, strlen(request)) == -1)
174     return FALSE;
175
176   if (!receive_from_gpg_agent(sd, buf, n))
177     return FALSE;
178
179   return (strncmp(buf, "OK", 2) == 0);
180 }
181
182 /* Send the BYE command and disconnect from the gpg-agent.  Doing this avoids
183  * gpg-agent emitting a "Connection reset by peer" log message with some
184  * versions of gpg-agent. */
185 static void
186 bye_gpg_agent(int sd)
187 {
188   /* don't bother to check the result of the write, it either worked or it
189    * didn't, but either way we're closing. */
190   write(sd, "BYE\n", 4);
191   close(sd);
192 }
193
194 /* Locate a running GPG Agent, and return an open file descriptor
195  * for communication with the agent in *NEW_SD. If no running agent
196  * can be found, set *NEW_SD to -1. */
197 static svn_error_t *
198 find_running_gpg_agent(int *new_sd, apr_pool_t *pool)
199 {
200   char *buffer;
201   char *gpg_agent_info = NULL;
202   const char *socket_name = NULL;
203   const char *request = NULL;
204   const char *p = NULL;
205   char *ep = NULL;
206   int sd;
207
208   *new_sd = -1;
209
210   /* This implements the method of finding the socket as described in
211    * the gpg-agent man page under the --use-standard-socket option.
212    * The manage page misleadingly says the standard socket is
213    * "named 'S.gpg-agent' located in the home directory."  The standard
214    * socket path is actually in the .gnupg directory in the home directory,
215    * i.e. ~/.gnupg/S.gpg-agent */
216   gpg_agent_info = getenv("GPG_AGENT_INFO");
217   if (gpg_agent_info != NULL)
218     {
219       apr_array_header_t *socket_details;
220
221       /* For reference GPG_AGENT_INFO consists of 3 : separated fields.
222        * The path to the socket, the pid of the gpg-agent process and
223        * finally the version of the protocol the agent talks. */
224       socket_details = svn_cstring_split(gpg_agent_info, ":", TRUE,
225                                          pool);
226       socket_name = APR_ARRAY_IDX(socket_details, 0, const char *);
227     }
228   else
229     {
230       const char *homedir = svn_user_get_homedir(pool);
231
232       if (!homedir)
233         return SVN_NO_ERROR;
234
235       homedir = svn_dirent_canonicalize(homedir, pool);
236       socket_name = svn_dirent_join_many(pool, homedir, ".gnupg",
237                                          "S.gpg-agent", SVN_VA_NULL);
238     }
239
240   if (socket_name != NULL)
241     {
242       struct sockaddr_un addr;
243
244       addr.sun_family = AF_UNIX;
245       strncpy(addr.sun_path, socket_name, sizeof(addr.sun_path) - 1);
246       addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
247
248       sd = socket(AF_UNIX, SOCK_STREAM, 0);
249       if (sd == -1)
250         return SVN_NO_ERROR;
251
252       if (connect(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
253         {
254           close(sd);
255           return SVN_NO_ERROR;
256         }
257     }
258   else
259     return SVN_NO_ERROR;
260
261   /* Receive the connection status from the gpg-agent daemon. */
262   buffer = apr_palloc(pool, BUFFER_SIZE);
263   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
264     {
265       bye_gpg_agent(sd);
266       return SVN_NO_ERROR;
267     }
268
269   if (strncmp(buffer, "OK", 2) != 0)
270     {
271       bye_gpg_agent(sd);
272       return SVN_NO_ERROR;
273     }
274
275   /* The GPG-Agent documentation says:
276    *  "Clients should deny to access an agent with a socket name which does
277    *   not match its own configuration". */
278   request = "GETINFO socket_name\n";
279   if (write(sd, request, strlen(request)) == -1)
280     {
281       bye_gpg_agent(sd);
282       return SVN_NO_ERROR;
283     }
284   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
285     {
286       bye_gpg_agent(sd);
287       return SVN_NO_ERROR;
288     }
289   if (strncmp(buffer, "D", 1) == 0)
290     p = &buffer[2];
291   if (!p)
292     {
293       bye_gpg_agent(sd);
294       return SVN_NO_ERROR;
295     }
296   ep = strchr(p, '\n');
297   if (ep != NULL)
298     *ep = '\0';
299   if (strcmp(socket_name, p) != 0)
300     {
301       bye_gpg_agent(sd);
302       return SVN_NO_ERROR;
303     }
304   /* The agent will terminate its response with "OK". */
305   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
306     {
307       bye_gpg_agent(sd);
308       return SVN_NO_ERROR;
309     }
310   if (strncmp(buffer, "OK", 2) != 0)
311     {
312       bye_gpg_agent(sd);
313       return SVN_NO_ERROR;
314     }
315
316   *new_sd = sd;
317   return SVN_NO_ERROR;
318 }
319
320 static svn_boolean_t
321 send_options(int sd, char *buf, size_t n, apr_pool_t *scratch_pool)
322 {
323   const char *tty_name;
324   const char *tty_type;
325   const char *lc_ctype;
326   const char *display;
327
328   /* Send TTY_NAME to the gpg-agent daemon. */
329   tty_name = getenv("GPG_TTY");
330   if (tty_name != NULL)
331     {
332       if (!send_option(sd, buf, n, "ttyname", tty_name, scratch_pool))
333         return FALSE;
334     }
335
336   /* Send TTY_TYPE to the gpg-agent daemon. */
337   tty_type = getenv("TERM");
338   if (tty_type != NULL)
339     {
340       if (!send_option(sd, buf, n, "ttytype", tty_type, scratch_pool))
341         return FALSE;
342     }
343
344   /* Compute LC_CTYPE. */
345   lc_ctype = getenv("LC_ALL");
346   if (lc_ctype == NULL)
347     lc_ctype = getenv("LC_CTYPE");
348   if (lc_ctype == NULL)
349     lc_ctype = getenv("LANG");
350
351   /* Send LC_CTYPE to the gpg-agent daemon. */
352   if (lc_ctype != NULL)
353     {
354       if (!send_option(sd, buf, n, "lc-ctype", lc_ctype, scratch_pool))
355         return FALSE;
356     }
357
358   /* Send DISPLAY to the gpg-agent daemon. */
359   display = getenv("DISPLAY");
360   if (display != NULL)
361     {
362       if (!send_option(sd, buf, n, "display", display, scratch_pool))
363         return FALSE;
364     }
365
366   return TRUE;
367 }
368
369 /* Implementation of svn_auth__password_get_t that retrieves the password
370    from gpg-agent */
371 static svn_error_t *
372 password_get_gpg_agent(svn_boolean_t *done,
373                        const char **password,
374                        apr_hash_t *creds,
375                        const char *realmstring,
376                        const char *username,
377                        apr_hash_t *parameters,
378                        svn_boolean_t non_interactive,
379                        apr_pool_t *pool)
380 {
381   int sd;
382   const char *p = NULL;
383   char *ep = NULL;
384   char *buffer;
385   const char *request = NULL;
386   const char *cache_id = NULL;
387   char *password_prompt;
388   char *realm_prompt;
389   char *error_prompt;
390   int *attempt;
391
392   *done = FALSE;
393
394   attempt = svn_hash_gets(parameters, ATTEMPT_PARAMETER);
395
396   SVN_ERR(find_running_gpg_agent(&sd, pool));
397   if (sd == -1)
398     return SVN_NO_ERROR;
399
400   buffer = apr_palloc(pool, BUFFER_SIZE);
401
402   if (!send_options(sd, buffer, BUFFER_SIZE, pool))
403     {
404       bye_gpg_agent(sd);
405       return SVN_NO_ERROR;
406     }
407
408   SVN_ERR(get_cache_id(&cache_id, realmstring, pool, pool));
409
410   password_prompt = apr_psprintf(pool, _("Password for '%s': "), username);
411   realm_prompt = apr_psprintf(pool, _("Enter your Subversion password for %s"),
412                               realmstring);
413   if (*attempt == 1)
414     /* X means no error to the gpg-agent protocol */
415     error_prompt = apr_pstrdup(pool, "X");
416   else
417     error_prompt = apr_pstrdup(pool, _("Authentication failed"));
418
419   request = apr_psprintf(pool,
420                          "GET_PASSPHRASE --data %s"
421                          "%s %s %s %s\n",
422                          non_interactive ? "--no-ask " : "",
423                          cache_id,
424                          escape_blanks(error_prompt),
425                          escape_blanks(password_prompt),
426                          escape_blanks(realm_prompt));
427
428   if (write(sd, request, strlen(request)) == -1)
429     {
430       bye_gpg_agent(sd);
431       return SVN_NO_ERROR;
432     }
433   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
434     {
435       bye_gpg_agent(sd);
436       return SVN_NO_ERROR;
437     }
438
439   bye_gpg_agent(sd);
440
441   if (strncmp(buffer, "ERR", 3) == 0)
442     return SVN_NO_ERROR;
443
444   p = NULL;
445   if (strncmp(buffer, "D", 1) == 0)
446     p = &buffer[2];
447
448   if (!p)
449     return SVN_NO_ERROR;
450
451   ep = strchr(p, '\n');
452   if (ep != NULL)
453     *ep = '\0';
454
455   *password = p;
456
457   *done = TRUE;
458   return SVN_NO_ERROR;
459 }
460
461
462 /* Implementation of svn_auth__password_set_t that would store the
463    password in GPG Agent if that's how this particular integration
464    worked.  But it isn't.  GPG Agent stores the password provided by
465    the user via the pinentry program immediately upon its provision
466    (and regardless of its accuracy as passwords go), so we just need
467    to check if a running GPG Agent exists. */
468 static svn_error_t *
469 password_set_gpg_agent(svn_boolean_t *done,
470                        apr_hash_t *creds,
471                        const char *realmstring,
472                        const char *username,
473                        const char *password,
474                        apr_hash_t *parameters,
475                        svn_boolean_t non_interactive,
476                        apr_pool_t *pool)
477 {
478   int sd;
479
480   *done = FALSE;
481
482   SVN_ERR(find_running_gpg_agent(&sd, pool));
483   if (sd == -1)
484     return SVN_NO_ERROR;
485
486   bye_gpg_agent(sd);
487   *done = TRUE;
488
489   return SVN_NO_ERROR;
490 }
491
492
493 /* An implementation of svn_auth_provider_t::first_credentials() */
494 static svn_error_t *
495 simple_gpg_agent_first_creds(void **credentials,
496                              void **iter_baton,
497                              void *provider_baton,
498                              apr_hash_t *parameters,
499                              const char *realmstring,
500                              apr_pool_t *pool)
501 {
502   svn_error_t *err;
503   int *attempt = apr_palloc(pool, sizeof(*attempt));
504
505   *attempt = 1;
506   svn_hash_sets(parameters, ATTEMPT_PARAMETER, attempt);
507   err = svn_auth__simple_creds_cache_get(credentials, iter_baton,
508                                          provider_baton, parameters,
509                                          realmstring, password_get_gpg_agent,
510                                          SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
511                                          pool);
512   *iter_baton = attempt;
513
514   return err;
515 }
516
517 /* An implementation of svn_auth_provider_t::next_credentials() */
518 static svn_error_t *
519 simple_gpg_agent_next_creds(void **credentials,
520                             void *iter_baton,
521                             void *provider_baton,
522                             apr_hash_t *parameters,
523                             const char *realmstring,
524                             apr_pool_t *pool)
525 {
526   int *attempt = (int *)iter_baton;
527   int sd;
528   char *buffer;
529   const char *cache_id = NULL;
530   const char *request = NULL;
531
532   *credentials = NULL;
533
534   /* The users previous credentials failed so first remove the cached entry,
535    * before trying to retrieve them again.  Because gpg-agent stores cached
536    * credentials immediately upon retrieving them, this gives us the
537    * opportunity to remove the invalid credentials and prompt the
538    * user again.  While it's possible that server side issues could trigger
539    * this, this cache is ephemeral so at worst we're just speeding up
540    * when the user would need to re-enter their password. */
541
542   if (svn_hash_gets(parameters, SVN_AUTH_PARAM_NON_INTERACTIVE))
543     {
544       /* In this case since we're running non-interactively we do not
545        * want to clear the cache since the user was never prompted by
546        * gpg-agent to set a password. */
547       return SVN_NO_ERROR;
548     }
549
550   *attempt = *attempt + 1;
551
552   SVN_ERR(find_running_gpg_agent(&sd, pool));
553   if (sd == -1)
554     return SVN_NO_ERROR;
555
556   buffer = apr_palloc(pool, BUFFER_SIZE);
557
558   if (!send_options(sd, buffer, BUFFER_SIZE, pool))
559     {
560       bye_gpg_agent(sd);
561       return SVN_NO_ERROR;
562     }
563
564   SVN_ERR(get_cache_id(&cache_id, realmstring, pool, pool));
565
566   request = apr_psprintf(pool, "CLEAR_PASSPHRASE %s\n", cache_id);
567
568   if (write(sd, request, strlen(request)) == -1)
569     {
570       bye_gpg_agent(sd);
571       return SVN_NO_ERROR;
572     }
573
574   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
575     {
576       bye_gpg_agent(sd);
577       return SVN_NO_ERROR;
578     }
579
580   if (strncmp(buffer, "OK\n", 3) != 0)
581     {
582       bye_gpg_agent(sd);
583       return SVN_NO_ERROR;
584     }
585
586   /* TODO: This attempt limit hard codes it at 3 attempts (or 2 retries)
587    * which matches svn command line client's retry_limit as set in
588    * svn_cmdline_create_auth_baton().  It would be nice to have that
589    * limit reflected here but that violates the boundry between the
590    * prompt provider and the cache provider.  gpg-agent is acting as
591    * both here due to the peculiarties of their design so we'll have to
592    * live with this for now.  Note that when these failures get exceeded
593    * it'll eventually fall back on the retry limits of whatever prompt
594    * provider is in effect, so this effectively doubles the limit. */
595   if (*attempt < 4)
596     return svn_auth__simple_creds_cache_get(credentials, &iter_baton,
597                                             provider_baton, parameters,
598                                             realmstring,
599                                             password_get_gpg_agent,
600                                             SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
601                                             pool);
602
603   return SVN_NO_ERROR;
604 }
605
606
607 /* An implementation of svn_auth_provider_t::save_credentials() */
608 static svn_error_t *
609 simple_gpg_agent_save_creds(svn_boolean_t *saved,
610                             void *credentials,
611                             void *provider_baton,
612                             apr_hash_t *parameters,
613                             const char *realmstring,
614                             apr_pool_t *pool)
615 {
616   return svn_auth__simple_creds_cache_set(saved, credentials,
617                                           provider_baton, parameters,
618                                           realmstring, password_set_gpg_agent,
619                                           SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
620                                           pool);
621 }
622
623
624 static const svn_auth_provider_t gpg_agent_simple_provider = {
625   SVN_AUTH_CRED_SIMPLE,
626   simple_gpg_agent_first_creds,
627   simple_gpg_agent_next_creds,
628   simple_gpg_agent_save_creds
629 };
630
631
632 /* Public API */
633 void
634 svn_auth__get_gpg_agent_simple_provider(svn_auth_provider_object_t **provider,
635                                        apr_pool_t *pool)
636 {
637   svn_auth_provider_object_t *po = apr_pcalloc(pool, sizeof(*po));
638
639   po->vtable = &gpg_agent_simple_provider;
640   *provider = po;
641 }
642
643 #endif /* SVN_HAVE_GPG_AGENT */
644 #endif /* !WIN32 */