]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/subversion/subversion/libsvn_subr/gpg_agent.c
MFC r275385 (by bapt):
[FreeBSD/stable/10.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 #define is_hex(c) (((c) >= '0' && (c) <= '9') || ((c) >= 'A' && (c) <= 'F'))
107 #define hex_to_int(c) ((c) < '9' ? (c) - '0' : (c) - 'A' + 10)
108  
109 /* Modify STR in-place.  '%', CR and LF are always percent escaped,
110    other characters may be percent escaped, always using uppercase
111    hex, see https://www.gnupg.org/documentation/manuals/assuan.pdf */
112 static char *
113 unescape_assuan(char *str)
114 {
115   char *s = str;
116
117   while (s[0])
118     {
119       if (s[0] == '%' && is_hex(s[1]) && is_hex(s[2]))
120         {
121           char *s2 = s;
122           char val = hex_to_int(s[1]) * 16 + hex_to_int(s[2]);
123
124           s2[0] = val;
125           ++s2;
126
127           while (s2[2])
128             {
129               s2[0] = s2[2];
130               ++s2;
131             }
132           s2[0] = '\0';
133         }
134       ++s;
135     }
136
137   return str;
138 }
139
140 /* Generate the string CACHE_ID_P based on the REALMSTRING allocated in
141  * RESULT_POOL using SCRATCH_POOL for temporary allocations.  This is similar
142  * to other password caching mechanisms. */
143 static svn_error_t *
144 get_cache_id(const char **cache_id_p, const char *realmstring,
145              apr_pool_t *result_pool, apr_pool_t *scratch_pool)
146 {
147   const char *cache_id = NULL;
148   svn_checksum_t *digest = NULL;
149
150   SVN_ERR(svn_checksum(&digest, svn_checksum_md5, realmstring,
151                        strlen(realmstring), scratch_pool));
152   cache_id = svn_checksum_to_cstring(digest, result_pool);
153   *cache_id_p = cache_id;
154
155   return SVN_NO_ERROR;
156 }
157
158 /* Attempt to read a gpg-agent response message from the socket SD into
159  * buffer BUF. Buf is assumed to be N bytes large. Return TRUE if a response
160  * message could be read that fits into the buffer. Else return FALSE.
161  * If a message could be read it will always be NUL-terminated and the
162  * trailing newline is retained. */
163 static svn_boolean_t
164 receive_from_gpg_agent(int sd, char *buf, size_t n)
165 {
166   int i = 0;
167   size_t recvd;
168   char c;
169
170   /* Clear existing buffer content before reading response. */
171   if (n > 0)
172     *buf = '\0';
173
174   /* Require the message to fit into the buffer and be terminated
175    * with a newline. */
176   while (i < n)
177     {
178       recvd = read(sd, &c, 1);
179       if (recvd == -1)
180         return FALSE;
181       buf[i] = c;
182       i++;
183       if (i < n && c == '\n')
184         {
185           buf[i] = '\0';
186           return TRUE;
187         }
188     }
189
190     return FALSE;
191 }
192
193 /* Using socket SD, send the option OPTION with the specified VALUE
194  * to the gpg agent. Store the response in BUF, assumed to be N bytes
195  * in size, and evaluate the response. Return TRUE if the agent liked
196  * the smell of the option, if there is such a thing, and doesn't feel
197  * saturated by it. Else return FALSE.
198  * Do temporary allocations in scratch_pool. */
199 static svn_boolean_t
200 send_option(int sd, char *buf, size_t n, const char *option, const char *value,
201             apr_pool_t *scratch_pool)
202 {
203   const char *request;
204
205   request = apr_psprintf(scratch_pool, "OPTION %s=%s\n", option, value);
206
207   if (write(sd, request, strlen(request)) == -1)
208     return FALSE;
209
210   if (!receive_from_gpg_agent(sd, buf, n))
211     return FALSE;
212
213   return (strncmp(buf, "OK", 2) == 0);
214 }
215
216 /* Send the BYE command and disconnect from the gpg-agent.  Doing this avoids
217  * gpg-agent emitting a "Connection reset by peer" log message with some
218  * versions of gpg-agent. */
219 static void
220 bye_gpg_agent(int sd)
221 {
222   /* don't bother to check the result of the write, it either worked or it
223    * didn't, but either way we're closing. */
224   write(sd, "BYE\n", 4);
225   close(sd);
226 }
227
228 /* Locate a running GPG Agent, and return an open file descriptor
229  * for communication with the agent in *NEW_SD. If no running agent
230  * can be found, set *NEW_SD to -1. */
231 static svn_error_t *
232 find_running_gpg_agent(int *new_sd, apr_pool_t *pool)
233 {
234   char *buffer;
235   char *gpg_agent_info = NULL;
236   const char *socket_name = NULL;
237   const char *request = NULL;
238   const char *p = NULL;
239   char *ep = NULL;
240   int sd;
241
242   *new_sd = -1;
243
244   /* This implements the method of finding the socket as described in
245    * the gpg-agent man page under the --use-standard-socket option.
246    * The manage page misleadingly says the standard socket is
247    * "named 'S.gpg-agent' located in the home directory."  The standard
248    * socket path is actually in the .gnupg directory in the home directory,
249    * i.e. ~/.gnupg/S.gpg-agent */
250   gpg_agent_info = getenv("GPG_AGENT_INFO");
251   if (gpg_agent_info != NULL)
252     {
253       apr_array_header_t *socket_details;
254
255       /* For reference GPG_AGENT_INFO consists of 3 : separated fields.
256        * The path to the socket, the pid of the gpg-agent process and
257        * finally the version of the protocol the agent talks. */
258       socket_details = svn_cstring_split(gpg_agent_info, ":", TRUE,
259                                          pool);
260       socket_name = APR_ARRAY_IDX(socket_details, 0, const char *);
261     }
262   else
263     {
264       const char *homedir = svn_user_get_homedir(pool);
265
266       if (!homedir)
267         return SVN_NO_ERROR;
268
269       homedir = svn_dirent_canonicalize(homedir, pool);
270       socket_name = svn_dirent_join_many(pool, homedir, ".gnupg",
271                                          "S.gpg-agent", SVN_VA_NULL);
272     }
273
274   if (socket_name != NULL)
275     {
276       struct sockaddr_un addr;
277
278       addr.sun_family = AF_UNIX;
279       strncpy(addr.sun_path, socket_name, sizeof(addr.sun_path) - 1);
280       addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
281
282       sd = socket(AF_UNIX, SOCK_STREAM, 0);
283       if (sd == -1)
284         return SVN_NO_ERROR;
285
286       if (connect(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
287         {
288           close(sd);
289           return SVN_NO_ERROR;
290         }
291     }
292   else
293     return SVN_NO_ERROR;
294
295   /* Receive the connection status from the gpg-agent daemon. */
296   buffer = apr_palloc(pool, BUFFER_SIZE);
297   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
298     {
299       bye_gpg_agent(sd);
300       return SVN_NO_ERROR;
301     }
302
303   if (strncmp(buffer, "OK", 2) != 0)
304     {
305       bye_gpg_agent(sd);
306       return SVN_NO_ERROR;
307     }
308
309   /* The GPG-Agent documentation says:
310    *  "Clients should deny to access an agent with a socket name which does
311    *   not match its own configuration". */
312   request = "GETINFO socket_name\n";
313   if (write(sd, request, strlen(request)) == -1)
314     {
315       bye_gpg_agent(sd);
316       return SVN_NO_ERROR;
317     }
318   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
319     {
320       bye_gpg_agent(sd);
321       return SVN_NO_ERROR;
322     }
323   if (strncmp(buffer, "D", 1) == 0)
324     p = &buffer[2];
325   if (!p)
326     {
327       bye_gpg_agent(sd);
328       return SVN_NO_ERROR;
329     }
330   ep = strchr(p, '\n');
331   if (ep != NULL)
332     *ep = '\0';
333   if (strcmp(socket_name, p) != 0)
334     {
335       bye_gpg_agent(sd);
336       return SVN_NO_ERROR;
337     }
338   /* The agent will terminate its response with "OK". */
339   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
340     {
341       bye_gpg_agent(sd);
342       return SVN_NO_ERROR;
343     }
344   if (strncmp(buffer, "OK", 2) != 0)
345     {
346       bye_gpg_agent(sd);
347       return SVN_NO_ERROR;
348     }
349
350   *new_sd = sd;
351   return SVN_NO_ERROR;
352 }
353
354 static svn_boolean_t
355 send_options(int sd, char *buf, size_t n, apr_pool_t *scratch_pool)
356 {
357   const char *tty_name;
358   const char *tty_type;
359   const char *lc_ctype;
360   const char *display;
361
362   /* Send TTY_NAME to the gpg-agent daemon. */
363   tty_name = getenv("GPG_TTY");
364   if (tty_name != NULL)
365     {
366       if (!send_option(sd, buf, n, "ttyname", tty_name, scratch_pool))
367         return FALSE;
368     }
369
370   /* Send TTY_TYPE to the gpg-agent daemon. */
371   tty_type = getenv("TERM");
372   if (tty_type != NULL)
373     {
374       if (!send_option(sd, buf, n, "ttytype", tty_type, scratch_pool))
375         return FALSE;
376     }
377
378   /* Compute LC_CTYPE. */
379   lc_ctype = getenv("LC_ALL");
380   if (lc_ctype == NULL)
381     lc_ctype = getenv("LC_CTYPE");
382   if (lc_ctype == NULL)
383     lc_ctype = getenv("LANG");
384
385   /* Send LC_CTYPE to the gpg-agent daemon. */
386   if (lc_ctype != NULL)
387     {
388       if (!send_option(sd, buf, n, "lc-ctype", lc_ctype, scratch_pool))
389         return FALSE;
390     }
391
392   /* Send DISPLAY to the gpg-agent daemon. */
393   display = getenv("DISPLAY");
394   if (display != NULL)
395     {
396       if (!send_option(sd, buf, n, "display", display, scratch_pool))
397         return FALSE;
398     }
399
400   return TRUE;
401 }
402
403 /* Implementation of svn_auth__password_get_t that retrieves the password
404    from gpg-agent */
405 static svn_error_t *
406 password_get_gpg_agent(svn_boolean_t *done,
407                        const char **password,
408                        apr_hash_t *creds,
409                        const char *realmstring,
410                        const char *username,
411                        apr_hash_t *parameters,
412                        svn_boolean_t non_interactive,
413                        apr_pool_t *pool)
414 {
415   int sd;
416   char *p = NULL;
417   char *ep = NULL;
418   char *buffer;
419   const char *request = NULL;
420   const char *cache_id = NULL;
421   char *password_prompt;
422   char *realm_prompt;
423   char *error_prompt;
424   int *attempt;
425
426   *done = FALSE;
427
428   attempt = svn_hash_gets(parameters, ATTEMPT_PARAMETER);
429
430   SVN_ERR(find_running_gpg_agent(&sd, pool));
431   if (sd == -1)
432     return SVN_NO_ERROR;
433
434   buffer = apr_palloc(pool, BUFFER_SIZE);
435
436   if (!send_options(sd, buffer, BUFFER_SIZE, pool))
437     {
438       bye_gpg_agent(sd);
439       return SVN_NO_ERROR;
440     }
441
442   SVN_ERR(get_cache_id(&cache_id, realmstring, pool, pool));
443
444   password_prompt = apr_psprintf(pool, _("Password for '%s': "), username);
445   realm_prompt = apr_psprintf(pool, _("Enter your Subversion password for %s"),
446                               realmstring);
447   if (*attempt == 1)
448     /* X means no error to the gpg-agent protocol */
449     error_prompt = apr_pstrdup(pool, "X");
450   else
451     error_prompt = apr_pstrdup(pool, _("Authentication failed"));
452
453   request = apr_psprintf(pool,
454                          "GET_PASSPHRASE --data %s"
455                          "%s %s %s %s\n",
456                          non_interactive ? "--no-ask " : "",
457                          cache_id,
458                          escape_blanks(error_prompt),
459                          escape_blanks(password_prompt),
460                          escape_blanks(realm_prompt));
461
462   if (write(sd, request, strlen(request)) == -1)
463     {
464       bye_gpg_agent(sd);
465       return SVN_NO_ERROR;
466     }
467   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
468     {
469       bye_gpg_agent(sd);
470       return SVN_NO_ERROR;
471     }
472
473   bye_gpg_agent(sd);
474
475   if (strncmp(buffer, "ERR", 3) == 0)
476     return SVN_NO_ERROR;
477
478   p = NULL;
479   if (strncmp(buffer, "D", 1) == 0)
480     p = &buffer[2];
481
482   if (!p)
483     return SVN_NO_ERROR;
484
485   ep = strchr(p, '\n');
486   if (ep != NULL)
487     *ep = '\0';
488
489   *password = unescape_assuan(p);
490
491   *done = TRUE;
492   return SVN_NO_ERROR;
493 }
494
495
496 /* Implementation of svn_auth__password_set_t that would store the
497    password in GPG Agent if that's how this particular integration
498    worked.  But it isn't.  GPG Agent stores the password provided by
499    the user via the pinentry program immediately upon its provision
500    (and regardless of its accuracy as passwords go), so we just need
501    to check if a running GPG Agent exists. */
502 static svn_error_t *
503 password_set_gpg_agent(svn_boolean_t *done,
504                        apr_hash_t *creds,
505                        const char *realmstring,
506                        const char *username,
507                        const char *password,
508                        apr_hash_t *parameters,
509                        svn_boolean_t non_interactive,
510                        apr_pool_t *pool)
511 {
512   int sd;
513
514   *done = FALSE;
515
516   SVN_ERR(find_running_gpg_agent(&sd, pool));
517   if (sd == -1)
518     return SVN_NO_ERROR;
519
520   bye_gpg_agent(sd);
521   *done = TRUE;
522
523   return SVN_NO_ERROR;
524 }
525
526
527 /* An implementation of svn_auth_provider_t::first_credentials() */
528 static svn_error_t *
529 simple_gpg_agent_first_creds(void **credentials,
530                              void **iter_baton,
531                              void *provider_baton,
532                              apr_hash_t *parameters,
533                              const char *realmstring,
534                              apr_pool_t *pool)
535 {
536   svn_error_t *err;
537   int *attempt = apr_palloc(pool, sizeof(*attempt));
538
539   *attempt = 1;
540   svn_hash_sets(parameters, ATTEMPT_PARAMETER, attempt);
541   err = svn_auth__simple_creds_cache_get(credentials, iter_baton,
542                                          provider_baton, parameters,
543                                          realmstring, password_get_gpg_agent,
544                                          SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
545                                          pool);
546   *iter_baton = attempt;
547
548   return err;
549 }
550
551 /* An implementation of svn_auth_provider_t::next_credentials() */
552 static svn_error_t *
553 simple_gpg_agent_next_creds(void **credentials,
554                             void *iter_baton,
555                             void *provider_baton,
556                             apr_hash_t *parameters,
557                             const char *realmstring,
558                             apr_pool_t *pool)
559 {
560   int *attempt = (int *)iter_baton;
561   int sd;
562   char *buffer;
563   const char *cache_id = NULL;
564   const char *request = NULL;
565
566   *credentials = NULL;
567
568   /* The users previous credentials failed so first remove the cached entry,
569    * before trying to retrieve them again.  Because gpg-agent stores cached
570    * credentials immediately upon retrieving them, this gives us the
571    * opportunity to remove the invalid credentials and prompt the
572    * user again.  While it's possible that server side issues could trigger
573    * this, this cache is ephemeral so at worst we're just speeding up
574    * when the user would need to re-enter their password. */
575
576   if (svn_hash_gets(parameters, SVN_AUTH_PARAM_NON_INTERACTIVE))
577     {
578       /* In this case since we're running non-interactively we do not
579        * want to clear the cache since the user was never prompted by
580        * gpg-agent to set a password. */
581       return SVN_NO_ERROR;
582     }
583
584   *attempt = *attempt + 1;
585
586   SVN_ERR(find_running_gpg_agent(&sd, pool));
587   if (sd == -1)
588     return SVN_NO_ERROR;
589
590   buffer = apr_palloc(pool, BUFFER_SIZE);
591
592   if (!send_options(sd, buffer, BUFFER_SIZE, pool))
593     {
594       bye_gpg_agent(sd);
595       return SVN_NO_ERROR;
596     }
597
598   SVN_ERR(get_cache_id(&cache_id, realmstring, pool, pool));
599
600   request = apr_psprintf(pool, "CLEAR_PASSPHRASE %s\n", cache_id);
601
602   if (write(sd, request, strlen(request)) == -1)
603     {
604       bye_gpg_agent(sd);
605       return SVN_NO_ERROR;
606     }
607
608   if (!receive_from_gpg_agent(sd, buffer, BUFFER_SIZE))
609     {
610       bye_gpg_agent(sd);
611       return SVN_NO_ERROR;
612     }
613
614   if (strncmp(buffer, "OK\n", 3) != 0)
615     {
616       bye_gpg_agent(sd);
617       return SVN_NO_ERROR;
618     }
619
620   /* TODO: This attempt limit hard codes it at 3 attempts (or 2 retries)
621    * which matches svn command line client's retry_limit as set in
622    * svn_cmdline_create_auth_baton().  It would be nice to have that
623    * limit reflected here but that violates the boundry between the
624    * prompt provider and the cache provider.  gpg-agent is acting as
625    * both here due to the peculiarties of their design so we'll have to
626    * live with this for now.  Note that when these failures get exceeded
627    * it'll eventually fall back on the retry limits of whatever prompt
628    * provider is in effect, so this effectively doubles the limit. */
629   if (*attempt < 4)
630     return svn_auth__simple_creds_cache_get(credentials, &iter_baton,
631                                             provider_baton, parameters,
632                                             realmstring,
633                                             password_get_gpg_agent,
634                                             SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
635                                             pool);
636
637   return SVN_NO_ERROR;
638 }
639
640
641 /* An implementation of svn_auth_provider_t::save_credentials() */
642 static svn_error_t *
643 simple_gpg_agent_save_creds(svn_boolean_t *saved,
644                             void *credentials,
645                             void *provider_baton,
646                             apr_hash_t *parameters,
647                             const char *realmstring,
648                             apr_pool_t *pool)
649 {
650   return svn_auth__simple_creds_cache_set(saved, credentials,
651                                           provider_baton, parameters,
652                                           realmstring, password_set_gpg_agent,
653                                           SVN_AUTH__GPG_AGENT_PASSWORD_TYPE,
654                                           pool);
655 }
656
657
658 static const svn_auth_provider_t gpg_agent_simple_provider = {
659   SVN_AUTH_CRED_SIMPLE,
660   simple_gpg_agent_first_creds,
661   simple_gpg_agent_next_creds,
662   simple_gpg_agent_save_creds
663 };
664
665
666 /* Public API */
667 void
668 svn_auth__get_gpg_agent_simple_provider(svn_auth_provider_object_t **provider,
669                                        apr_pool_t *pool)
670 {
671   svn_auth_provider_object_t *po = apr_pcalloc(pool, sizeof(*po));
672
673   po->vtable = &gpg_agent_simple_provider;
674   *provider = po;
675 }
676
677 #endif /* SVN_HAVE_GPG_AGENT */
678 #endif /* !WIN32 */