1 /*
2  *  OpenVPN -- An application to securely tunnel IP networks
3  *             over a single TCP/UDP port, with support for SSL/TLS-based
4  *             session authentication and key exchange,
5  *             packet encryption, packet authentication, and
6  *             packet compression.
7  *
8  *  Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2
12  *  as published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License along
20  *  with this program; if not, write to the Free Software Foundation, Inc.,
21  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #include "syshead.h"
31 
32 #ifdef ENABLE_MANAGEMENT
33 
34 #include "error.h"
35 #include "fdmisc.h"
36 #include "options.h"
37 #include "sig.h"
38 #include "event.h"
39 #include "otime.h"
40 #include "integer.h"
41 #include "misc.h"
42 #include "ssl.h"
43 #include "common.h"
44 #include "manage.h"
45 
46 #include "memdbg.h"
47 
48 #ifdef ENABLE_PKCS11
49 #include "pkcs11.h"
50 #endif
51 
52 #define MANAGEMENT_ECHO_PULL_INFO 0
53 
54 #if MANAGEMENT_ECHO_PULL_INFO
55 #define MANAGEMENT_ECHO_FLAGS LOG_PRINT_INTVAL
56 #else
57 #define MANAGEMENT_ECHO_FLAGS 0
58 #endif
59 
60 /* tag for blank username/password */
61 static const char blank_up[] = "[[BLANK]]";
62 
63 struct management *management; /* GLOBAL */
64 
65 /* static forward declarations */
66 static void man_output_standalone(struct management *man, volatile int *signal_received);
67 
68 static void man_reset_client_socket(struct management *man, const bool exiting);
69 
70 static void
man_help(void)71 man_help(void)
72 {
73     msg(M_CLIENT, "Management Interface for %s", title_string);
74     msg(M_CLIENT, "Commands:");
75     msg(M_CLIENT, "auth-retry t           : Auth failure retry mode (none,interact,nointeract).");
76     msg(M_CLIENT, "bytecount n            : Show bytes in/out, update every n secs (0=off).");
77     msg(M_CLIENT, "echo [on|off] [N|all]  : Like log, but only show messages in echo buffer.");
78     msg(M_CLIENT, "cr-response response   : Send a challenge response answer via CR_RESPONSE to server");
79     msg(M_CLIENT, "exit|quit              : Close management session.");
80     msg(M_CLIENT, "forget-passwords       : Forget passwords entered so far.");
81     msg(M_CLIENT, "help                   : Print this message.");
82     msg(M_CLIENT, "hold [on|off|release]  : Set/show hold flag to on/off state, or");
83     msg(M_CLIENT, "                         release current hold and start tunnel.");
84     msg(M_CLIENT, "kill cn                : Kill the client instance(s) having common name cn.");
85     msg(M_CLIENT, "kill IP:port           : Kill the client instance connecting from IP:port.");
86     msg(M_CLIENT, "load-stats             : Show global server load stats.");
87     msg(M_CLIENT, "log [on|off] [N|all]   : Turn on/off realtime log display");
88     msg(M_CLIENT, "                         + show last N lines or 'all' for entire history.");
89     msg(M_CLIENT, "mute [n]               : Set log mute level to n, or show level if n is absent.");
90     msg(M_CLIENT, "needok type action     : Enter confirmation for NEED-OK request of 'type',");
91     msg(M_CLIENT, "                         where action = 'ok' or 'cancel'.");
92     msg(M_CLIENT, "needstr type action    : Enter confirmation for NEED-STR request of 'type',");
93     msg(M_CLIENT, "                         where action is reply string.");
94     msg(M_CLIENT, "net                    : (Windows only) Show network info and routing table.");
95     msg(M_CLIENT, "password type p        : Enter password p for a queried OpenVPN password.");
96     msg(M_CLIENT, "remote type [host port] : Override remote directive, type=ACCEPT|MOD|SKIP.");
97     msg(M_CLIENT, "proxy type [host port flags] : Enter dynamic proxy server info.");
98     msg(M_CLIENT, "pid                    : Show process ID of the current OpenVPN process.");
99 #ifdef ENABLE_PKCS11
100     msg(M_CLIENT, "pkcs11-id-count        : Get number of available PKCS#11 identities.");
101     msg(M_CLIENT, "pkcs11-id-get index    : Get PKCS#11 identity at index.");
102 #endif
103     msg(M_CLIENT, "client-auth CID KID    : Authenticate client-id/key-id CID/KID (MULTILINE)");
104     msg(M_CLIENT, "client-auth-nt CID KID : Authenticate client-id/key-id CID/KID");
105     msg(M_CLIENT, "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log reason");
106     msg(M_CLIENT, "                             text R and optional client reason text CR");
107     msg(M_CLIENT, "client-pending-auth CID MSG : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg"
108         "                          to the client and wait for a final client-auth/client-deny");
109     msg(M_CLIENT, "client-kill CID [M]    : Kill client instance CID with message M (def=RESTART)");
110     msg(M_CLIENT, "env-filter [level]     : Set env-var filter level");
111 #ifdef MANAGEMENT_PF
112     msg(M_CLIENT, "client-pf CID          : Define packet filter for client CID (MULTILINE)");
113 #endif
114     msg(M_CLIENT, "rsa-sig                : Enter a signature in response to >RSA_SIGN challenge");
115     msg(M_CLIENT, "                         Enter signature base64 on subsequent lines followed by END");
116     msg(M_CLIENT, "pk-sig                 : Enter a signature in response to >PK_SIGN challenge");
117     msg(M_CLIENT, "                         Enter signature base64 on subsequent lines followed by END");
118     msg(M_CLIENT, "certificate            : Enter a client certificate in response to >NEED-CERT challenge");
119     msg(M_CLIENT, "                         Enter certificate base64 on subsequent lines followed by END");
120     msg(M_CLIENT, "signal s               : Send signal s to daemon,");
121     msg(M_CLIENT, "                         s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.");
122     msg(M_CLIENT, "state [on|off] [N|all] : Like log, but show state history.");
123     msg(M_CLIENT, "status [n]             : Show current daemon status info using format #n.");
124     msg(M_CLIENT, "test n                 : Produce n lines of output for testing/debugging.");
125     msg(M_CLIENT, "username type u        : Enter username u for a queried OpenVPN username.");
126     msg(M_CLIENT, "verb [n]               : Set log verbosity level to n, or show if n is absent.");
127     msg(M_CLIENT, "version [n]            : Set client's version to n or show current version of daemon.");
128     msg(M_CLIENT, "END");
129 }
130 
131 static const char *
man_state_name(const int state)132 man_state_name(const int state)
133 {
134     switch (state)
135     {
136         case OPENVPN_STATE_INITIAL:
137             return "INITIAL";
138 
139         case OPENVPN_STATE_CONNECTING:
140             return "CONNECTING";
141 
142         case OPENVPN_STATE_WAIT:
143             return "WAIT";
144 
145         case OPENVPN_STATE_AUTH:
146             return "AUTH";
147 
148         case OPENVPN_STATE_GET_CONFIG:
149             return "GET_CONFIG";
150 
151         case OPENVPN_STATE_ASSIGN_IP:
152             return "ASSIGN_IP";
153 
154         case OPENVPN_STATE_ADD_ROUTES:
155             return "ADD_ROUTES";
156 
157         case OPENVPN_STATE_CONNECTED:
158             return "CONNECTED";
159 
160         case OPENVPN_STATE_RECONNECTING:
161             return "RECONNECTING";
162 
163         case OPENVPN_STATE_EXITING:
164             return "EXITING";
165 
166         case OPENVPN_STATE_RESOLVE:
167             return "RESOLVE";
168 
169         case OPENVPN_STATE_TCP_CONNECT:
170             return "TCP_CONNECT";
171 
172         case OPENVPN_STATE_AUTH_PENDING:
173             return "AUTH_PENDING";
174 
175         default:
176             return "?";
177     }
178 }
179 
180 static void
man_welcome(struct management * man)181 man_welcome(struct management *man)
182 {
183     msg(M_CLIENT, ">INFO:OpenVPN Management Interface Version %d -- type 'help' for more info",
184         MANAGEMENT_VERSION);
185     if (man->persist.special_state_msg)
186     {
187         msg(M_CLIENT, "%s", man->persist.special_state_msg);
188     }
189 }
190 
191 static inline bool
man_password_needed(struct management * man)192 man_password_needed(struct management *man)
193 {
194     return man->settings.up.defined && !man->connection.password_verified;
195 }
196 
197 static void
man_check_password(struct management * man,const char * line)198 man_check_password(struct management *man, const char *line)
199 {
200     if (man_password_needed(man))
201     {
202         if (streq(line, man->settings.up.password))
203         {
204             man->connection.password_verified = true;
205             msg(M_CLIENT, "SUCCESS: password is correct");
206             man_welcome(man);
207         }
208         else
209         {
210             man->connection.password_verified = false;
211             msg(M_CLIENT, "ERROR: bad password");
212             if (++man->connection.password_tries >= MANAGEMENT_N_PASSWORD_RETRIES)
213             {
214                 msg(M_WARN, "MAN: client connection rejected after %d failed password attempts",
215                     MANAGEMENT_N_PASSWORD_RETRIES);
216                 man->connection.halt = true;
217             }
218         }
219     }
220 }
221 
222 static void
man_update_io_state(struct management * man)223 man_update_io_state(struct management *man)
224 {
225     if (socket_defined(man->connection.sd_cli))
226     {
227         if (buffer_list_defined(man->connection.out))
228         {
229             man->connection.state = MS_CC_WAIT_WRITE;
230         }
231         else
232         {
233             man->connection.state = MS_CC_WAIT_READ;
234         }
235     }
236 }
237 
238 static void
man_output_list_push_finalize(struct management * man)239 man_output_list_push_finalize(struct management *man)
240 {
241     if (management_connected(man))
242     {
243         man_update_io_state(man);
244         if (!man->persist.standalone_disabled)
245         {
246             volatile int signal_received = 0;
247             man_output_standalone(man, &signal_received);
248         }
249     }
250 }
251 
252 static void
man_output_list_push_str(struct management * man,const char * str)253 man_output_list_push_str(struct management *man, const char *str)
254 {
255     if (management_connected(man) && str)
256     {
257         buffer_list_push(man->connection.out, str);
258     }
259 }
260 
261 static void
man_output_list_push(struct management * man,const char * str)262 man_output_list_push(struct management *man, const char *str)
263 {
264     man_output_list_push_str(man, str);
265     man_output_list_push_finalize(man);
266 }
267 
268 static void
man_prompt(struct management * man)269 man_prompt(struct management *man)
270 {
271     if (man_password_needed(man))
272     {
273         man_output_list_push(man, "ENTER PASSWORD:");
274     }
275 #if 0 /* should we use prompt? */
276     else
277     {
278         man_output_list_push(man, ">");
279     }
280 #endif
281 }
282 
283 static void
man_delete_unix_socket(struct management * man)284 man_delete_unix_socket(struct management *man)
285 {
286 #if UNIX_SOCK_SUPPORT
287     if ((man->settings.flags & (MF_UNIX_SOCK|MF_CONNECT_AS_CLIENT)) == MF_UNIX_SOCK)
288     {
289         socket_delete_unix(&man->settings.local_unix);
290     }
291 #endif
292 }
293 
294 static void
man_close_socket(struct management * man,const socket_descriptor_t sd)295 man_close_socket(struct management *man, const socket_descriptor_t sd)
296 {
297 #ifndef _WIN32
298     /*
299      * Windows doesn't need this because the ne32 event is permanently
300      * enabled at struct management scope.
301      */
302     if (man->persist.callback.delete_event)
303     {
304         (*man->persist.callback.delete_event)(man->persist.callback.arg, sd);
305     }
306 #endif
307     openvpn_close_socket(sd);
308 }
309 
310 static void
virtual_output_callback_func(void * arg,const unsigned int flags,const char * str)311 virtual_output_callback_func(void *arg, const unsigned int flags, const char *str)
312 {
313     struct management *man = (struct management *) arg;
314     static int recursive_level = 0; /* GLOBAL */
315 
316 #define AF_DID_PUSH  (1<<0)
317 #define AF_DID_RESET (1<<1)
318 
319     if (!recursive_level) /* don't allow recursion */
320     {
321         struct gc_arena gc = gc_new();
322         struct log_entry e;
323         const char *out = NULL;
324         unsigned int action_flags = 0;
325 
326         ++recursive_level;
327 
328         CLEAR(e);
329         update_time();
330         e.timestamp = now;
331         e.u.msg_flags = flags;
332         e.string = str;
333 
334         if (flags & M_FATAL)
335         {
336             man->persist.standalone_disabled = false;
337         }
338 
339         if (flags != M_CLIENT)
340         {
341             log_history_add(man->persist.log, &e);
342         }
343 
344         if (!man_password_needed(man))
345         {
346             if (flags == M_CLIENT)
347             {
348                 out = log_entry_print(&e, LOG_PRINT_CRLF, &gc);
349             }
350             else if (man->connection.log_realtime)
351             {
352                 out = log_entry_print(&e, LOG_PRINT_INT_DATE
353                                       |   LOG_PRINT_MSG_FLAGS
354                                       |   LOG_PRINT_LOG_PREFIX
355                                       |   LOG_PRINT_CRLF, &gc);
356             }
357             if (out)
358             {
359                 man_output_list_push_str(man, out);
360                 action_flags |= AF_DID_PUSH;
361             }
362             if (flags & M_FATAL)
363             {
364                 out = log_entry_print(&e, LOG_FATAL_NOTIFY|LOG_PRINT_CRLF, &gc);
365                 if (out)
366                 {
367                     man_output_list_push_str(man, out);
368                     action_flags |= (AF_DID_PUSH|AF_DID_RESET);
369                 }
370             }
371         }
372 
373         gc_free(&gc);
374 
375         if (action_flags & AF_DID_PUSH)
376         {
377             man_output_list_push_finalize(man);
378         }
379         if (action_flags & AF_DID_RESET)
380         {
381             man_reset_client_socket(man, true);
382         }
383 
384         --recursive_level;
385     }
386 }
387 
388 /*
389  * Given a signal, return the signal with possible remapping applied,
390  * or -1 if the signal should be ignored.
391  */
392 static int
man_mod_signal(const struct management * man,const int signum)393 man_mod_signal(const struct management *man, const int signum)
394 {
395     const unsigned int flags = man->settings.mansig;
396     int s = signum;
397     if (s == SIGUSR1)
398     {
399         if (flags & MANSIG_MAP_USR1_TO_HUP)
400         {
401             s = SIGHUP;
402         }
403         if (flags & MANSIG_MAP_USR1_TO_TERM)
404         {
405             s = SIGTERM;
406         }
407     }
408     if (flags & MANSIG_IGNORE_USR1_HUP)
409     {
410         if (s == SIGHUP || s == SIGUSR1)
411         {
412             s = -1;
413         }
414     }
415     return s;
416 }
417 
418 static void
man_signal(struct management * man,const char * name)419 man_signal(struct management *man, const char *name)
420 {
421     const int sig = parse_signal(name);
422     if (sig >= 0)
423     {
424         const int sig_mod = man_mod_signal(man, sig);
425         if (sig_mod >= 0)
426         {
427             throw_signal(sig_mod);
428             msg(M_CLIENT, "SUCCESS: signal %s thrown", signal_name(sig_mod, true));
429         }
430         else
431         {
432             if (man->persist.special_state_msg)
433             {
434                 msg(M_CLIENT, "%s", man->persist.special_state_msg);
435             }
436             else
437             {
438                 msg(M_CLIENT, "ERROR: signal '%s' is currently ignored", name);
439             }
440         }
441     }
442     else
443     {
444         msg(M_CLIENT, "ERROR: signal '%s' is not a known signal type", name);
445     }
446 }
447 
448 static void
man_status(struct management * man,const int version,struct status_output * so)449 man_status(struct management *man, const int version, struct status_output *so)
450 {
451     if (man->persist.callback.status)
452     {
453         (*man->persist.callback.status)(man->persist.callback.arg, version, so);
454     }
455     else
456     {
457         msg(M_CLIENT, "ERROR: The 'status' command is not supported by the current daemon mode");
458     }
459 }
460 
461 static void
man_bytecount(struct management * man,const int update_seconds)462 man_bytecount(struct management *man, const int update_seconds)
463 {
464     if (update_seconds >= 0)
465     {
466         man->connection.bytecount_update_seconds = update_seconds;
467     }
468     else
469     {
470         man->connection.bytecount_update_seconds = 0;
471     }
472     msg(M_CLIENT, "SUCCESS: bytecount interval changed");
473 }
474 
475 void
man_bytecount_output_client(struct management * man)476 man_bytecount_output_client(struct management *man)
477 {
478     char in[32];
479     char out[32];
480     /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
481     openvpn_snprintf(in, sizeof(in), counter_format, man->persist.bytes_in);
482     openvpn_snprintf(out, sizeof(out), counter_format, man->persist.bytes_out);
483     msg(M_CLIENT, ">BYTECOUNT:%s,%s", in, out);
484     man->connection.bytecount_last_update = now;
485 }
486 
487 void
man_bytecount_output_server(struct management * man,const counter_type * bytes_in_total,const counter_type * bytes_out_total,struct man_def_auth_context * mdac)488 man_bytecount_output_server(struct management *man,
489                             const counter_type *bytes_in_total,
490                             const counter_type *bytes_out_total,
491                             struct man_def_auth_context *mdac)
492 {
493     char in[32];
494     char out[32];
495     /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
496     openvpn_snprintf(in, sizeof(in), counter_format, *bytes_in_total);
497     openvpn_snprintf(out, sizeof(out), counter_format, *bytes_out_total);
498     msg(M_CLIENT, ">BYTECOUNT_CLI:%lu,%s,%s", mdac->cid, in, out);
499     mdac->bytecount_last_update = now;
500 }
501 
502 static void
man_kill(struct management * man,const char * victim)503 man_kill(struct management *man, const char *victim)
504 {
505     struct gc_arena gc = gc_new();
506 
507     if (man->persist.callback.kill_by_cn && man->persist.callback.kill_by_addr)
508     {
509         struct buffer buf;
510         char p1[128];
511         char p2[128];
512         int n_killed;
513 
514         buf_set_read(&buf, (uint8_t *) victim, strlen(victim) + 1);
515         buf_parse(&buf, ':', p1, sizeof(p1));
516         buf_parse(&buf, ':', p2, sizeof(p2));
517 
518         if (strlen(p1) && strlen(p2))
519         {
520             /* IP:port specified */
521             bool status;
522             const in_addr_t addr = getaddr(GETADDR_HOST_ORDER|GETADDR_MSG_VIRT_OUT, p1, 0, &status, NULL);
523             if (status)
524             {
525                 const int port = atoi(p2);
526                 if (port > 0 && port < 65536)
527                 {
528                     n_killed = (*man->persist.callback.kill_by_addr)(man->persist.callback.arg, addr, port);
529                     if (n_killed > 0)
530                     {
531                         msg(M_CLIENT, "SUCCESS: %d client(s) at address %s:%d killed",
532                             n_killed,
533                             print_in_addr_t(addr, 0, &gc),
534                             port);
535                     }
536                     else
537                     {
538                         msg(M_CLIENT, "ERROR: client at address %s:%d not found",
539                             print_in_addr_t(addr, 0, &gc),
540                             port);
541                     }
542                 }
543                 else
544                 {
545                     msg(M_CLIENT, "ERROR: port number is out of range: %s", p2);
546                 }
547             }
548             else
549             {
550                 msg(M_CLIENT, "ERROR: error parsing IP address: %s", p1);
551             }
552         }
553         else if (strlen(p1))
554         {
555             /* common name specified */
556             n_killed = (*man->persist.callback.kill_by_cn)(man->persist.callback.arg, p1);
557             if (n_killed > 0)
558             {
559                 msg(M_CLIENT, "SUCCESS: common name '%s' found, %d client(s) killed", p1, n_killed);
560             }
561             else
562             {
563                 msg(M_CLIENT, "ERROR: common name '%s' not found", p1);
564             }
565         }
566         else
567         {
568             msg(M_CLIENT, "ERROR: kill parse");
569         }
570     }
571     else
572     {
573         msg(M_CLIENT, "ERROR: The 'kill' command is not supported by the current daemon mode");
574     }
575 
576     gc_free(&gc);
577 }
578 
579 /*
580  * General-purpose history command handler
581  * for the log and echo commands.
582  */
583 static void
man_history(struct management * man,const char * parm,const char * type,struct log_history * log,bool * realtime,const unsigned int lep_flags)584 man_history(struct management *man,
585             const char *parm,
586             const char *type,
587             struct log_history *log,
588             bool *realtime,
589             const unsigned int lep_flags)
590 {
591     struct gc_arena gc = gc_new();
592     int n = 0;
593 
594     if (streq(parm, "on"))
595     {
596         *realtime = true;
597         msg(M_CLIENT, "SUCCESS: real-time %s notification set to ON", type);
598     }
599     else if (streq(parm, "off"))
600     {
601         *realtime = false;
602         msg(M_CLIENT, "SUCCESS: real-time %s notification set to OFF", type);
603     }
604     else if (streq(parm, "all") || (n = atoi(parm)) > 0)
605     {
606         const int size = log_history_size(log);
607         const int start = (n ? n : size) - 1;
608         int i;
609 
610         for (i = start; i >= 0; --i)
611         {
612             const struct log_entry *e = log_history_ref(log, i);
613             if (e)
614             {
615                 const char *out = log_entry_print(e, lep_flags, &gc);
616                 virtual_output_callback_func(man, M_CLIENT, out);
617             }
618         }
619         msg(M_CLIENT, "END");
620     }
621     else
622     {
623         msg(M_CLIENT, "ERROR: %s parameter must be 'on' or 'off' or some number n or 'all'", type);
624     }
625 
626     gc_free(&gc);
627 }
628 
629 static void
man_log(struct management * man,const char * parm)630 man_log(struct management *man, const char *parm)
631 {
632     man_history(man,
633                 parm,
634                 "log",
635                 man->persist.log,
636                 &man->connection.log_realtime,
637                 LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS);
638 }
639 
640 static void
man_echo(struct management * man,const char * parm)641 man_echo(struct management *man, const char *parm)
642 {
643     man_history(man,
644                 parm,
645                 "echo",
646                 man->persist.echo,
647                 &man->connection.echo_realtime,
648                 LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS);
649 }
650 
651 static void
man_state(struct management * man,const char * parm)652 man_state(struct management *man, const char *parm)
653 {
654     man_history(man,
655                 parm,
656                 "state",
657                 man->persist.state,
658                 &man->connection.state_realtime,
659                 LOG_PRINT_INT_DATE|LOG_PRINT_STATE
660                 |LOG_PRINT_LOCAL_IP|LOG_PRINT_REMOTE_IP);
661 }
662 
663 static void
man_up_finalize(struct management * man)664 man_up_finalize(struct management *man)
665 {
666     switch (man->connection.up_query_mode)
667     {
668         case UP_QUERY_USER_PASS:
669             if (!strlen(man->connection.up_query.username))
670             {
671                 break;
672             }
673 
674         /* fall through */
675         case UP_QUERY_PASS:
676         case UP_QUERY_NEED_OK:
677         case UP_QUERY_NEED_STR:
678             if (strlen(man->connection.up_query.password))
679             {
680                 man->connection.up_query.defined = true;
681             }
682             break;
683 
684         case UP_QUERY_DISABLED:
685             man->connection.up_query.defined = false;
686             break;
687 
688         default:
689             ASSERT(0);
690     }
691 }
692 
693 static void
man_query_user_pass(struct management * man,const char * type,const char * string,const bool needed,const char * prompt,char * dest,int len)694 man_query_user_pass(struct management *man,
695                     const char *type,
696                     const char *string,
697                     const bool needed,
698                     const char *prompt,
699                     char *dest,
700                     int len)
701 {
702     if (needed)
703     {
704         ASSERT(man->connection.up_query_type);
705         if (streq(man->connection.up_query_type, type))
706         {
707             strncpynt(dest, string, len);
708             man_up_finalize(man);
709             msg(M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified",
710                 type,
711                 prompt);
712         }
713         else
714         {
715             msg(M_CLIENT, "ERROR: %s of type '%s' entered, but we need one of type '%s'",
716                 prompt,
717                 type,
718                 man->connection.up_query_type);
719         }
720     }
721     else
722     {
723         msg(M_CLIENT, "ERROR: no %s is currently needed at this time", prompt);
724     }
725 }
726 
727 static void
man_query_username(struct management * man,const char * type,const char * string)728 man_query_username(struct management *man, const char *type, const char *string)
729 {
730     const bool needed = ((man->connection.up_query_mode == UP_QUERY_USER_PASS
731                           ) && man->connection.up_query_type);
732     man_query_user_pass(man, type, string, needed, "username", man->connection.up_query.username, USER_PASS_LEN);
733 }
734 
735 static void
man_query_password(struct management * man,const char * type,const char * string)736 man_query_password(struct management *man, const char *type, const char *string)
737 {
738     const bool needed = ((man->connection.up_query_mode == UP_QUERY_PASS
739                           || man->connection.up_query_mode == UP_QUERY_USER_PASS
740                           ) && man->connection.up_query_type);
741     if (!string[0]) /* allow blank passwords to be passed through using the blank_up tag */
742     {
743         string = blank_up;
744     }
745     man_query_user_pass(man, type, string, needed, "password", man->connection.up_query.password, USER_PASS_LEN);
746 }
747 
748 static void
man_query_need_ok(struct management * man,const char * type,const char * action)749 man_query_need_ok(struct management *man, const char *type, const char *action)
750 {
751     const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_OK) && man->connection.up_query_type);
752     man_query_user_pass(man, type, action, needed, "needok-confirmation", man->connection.up_query.password, USER_PASS_LEN);
753 }
754 
755 static void
man_query_need_str(struct management * man,const char * type,const char * action)756 man_query_need_str(struct management *man, const char *type, const char *action)
757 {
758     const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_STR) && man->connection.up_query_type);
759     man_query_user_pass(man, type, action, needed, "needstr-string", man->connection.up_query.password, USER_PASS_LEN);
760 }
761 
762 static void
man_forget_passwords(struct management * man)763 man_forget_passwords(struct management *man)
764 {
765     ssl_purge_auth(false);
766     msg(M_CLIENT, "SUCCESS: Passwords were forgotten");
767 }
768 
769 static void
man_net(struct management * man)770 man_net(struct management *man)
771 {
772     if (man->persist.callback.show_net)
773     {
774         (*man->persist.callback.show_net)(man->persist.callback.arg, M_CLIENT);
775     }
776     else
777     {
778         msg(M_CLIENT, "ERROR: The 'net' command is not supported by the current daemon mode");
779     }
780 }
781 
782 static void
man_send_cc_message(struct management * man,const char * message,const char * parameters)783 man_send_cc_message(struct management *man, const char *message, const char *parameters)
784 {
785     if (man->persist.callback.send_cc_message)
786     {
787         const bool status = (*man->persist.callback.send_cc_message)
788                                 (man->persist.callback.arg, message, parameters);
789         if (status)
790         {
791             msg(M_CLIENT, "SUCCESS: command succeeded");
792         }
793         else
794         {
795             msg(M_CLIENT, "ERROR: command failed");
796         }
797     }
798     else
799     {
800         msg(M_CLIENT, "ERROR: This command is not supported by the current daemon mode");
801     }
802 }
803 #ifdef ENABLE_PKCS11
804 
805 static void
man_pkcs11_id_count(struct management * man)806 man_pkcs11_id_count(struct management *man)
807 {
808     msg(M_CLIENT, ">PKCS11ID-COUNT:%d", pkcs11_management_id_count());
809 }
810 
811 static void
man_pkcs11_id_get(struct management * man,const int index)812 man_pkcs11_id_get(struct management *man, const int index)
813 {
814     char *id = NULL;
815     char *base64 = NULL;
816 
817     if (pkcs11_management_id_get(index, &id, &base64))
818     {
819         msg(M_CLIENT, ">PKCS11ID-ENTRY:'%d', ID:'%s', BLOB:'%s'", index, id, base64);
820     }
821     else
822     {
823         msg(M_CLIENT, ">PKCS11ID-ENTRY:'%d'", index);
824     }
825 
826     free(id);
827     free(base64);
828 }
829 
830 #endif /* ifdef ENABLE_PKCS11 */
831 
832 static void
man_hold(struct management * man,const char * cmd)833 man_hold(struct management *man, const char *cmd)
834 {
835     if (cmd)
836     {
837         if (streq(cmd, "on"))
838         {
839             man->settings.flags |= MF_HOLD;
840             msg(M_CLIENT, "SUCCESS: hold flag set to ON");
841         }
842         else if (streq(cmd, "off"))
843         {
844             man->settings.flags &= ~MF_HOLD;
845             msg(M_CLIENT, "SUCCESS: hold flag set to OFF");
846         }
847         else if (streq(cmd, "release"))
848         {
849             man->persist.hold_release = true;
850             msg(M_CLIENT, "SUCCESS: hold release succeeded");
851         }
852         else
853         {
854             msg(M_CLIENT, "ERROR: bad hold command parameter");
855         }
856     }
857     else
858     {
859         msg(M_CLIENT, "SUCCESS: hold=%d", BOOL_CAST(man->settings.flags & MF_HOLD));
860     }
861 }
862 
863 #define IER_RESET      0
864 #define IER_NEW        1
865 
866 static void
in_extra_reset(struct man_connection * mc,const int mode)867 in_extra_reset(struct man_connection *mc, const int mode)
868 {
869     if (mc)
870     {
871         if (mode != IER_NEW)
872         {
873             mc->in_extra_cmd = IEC_UNDEF;
874             mc->in_extra_cid = 0;
875             mc->in_extra_kid = 0;
876         }
877         if (mc->in_extra)
878         {
879             buffer_list_free(mc->in_extra);
880             mc->in_extra = NULL;
881         }
882         if (mode == IER_NEW)
883         {
884             mc->in_extra = buffer_list_new(0);
885         }
886     }
887 }
888 
889 static void
in_extra_dispatch(struct management * man)890 in_extra_dispatch(struct management *man)
891 {
892     switch (man->connection.in_extra_cmd)
893     {
894         case IEC_CLIENT_AUTH:
895             if (man->persist.callback.client_auth)
896             {
897                 const bool status = (*man->persist.callback.client_auth)
898                                         (man->persist.callback.arg,
899                                         man->connection.in_extra_cid,
900                                         man->connection.in_extra_kid,
901                                         true,
902                                         NULL,
903                                         NULL,
904                                         man->connection.in_extra);
905                 man->connection.in_extra = NULL;
906                 if (status)
907                 {
908                     msg(M_CLIENT, "SUCCESS: client-auth command succeeded");
909                 }
910                 else
911                 {
912                     msg(M_CLIENT, "ERROR: client-auth command failed");
913                 }
914             }
915             else
916             {
917                 msg(M_CLIENT, "ERROR: The client-auth command is not supported by the current daemon mode");
918             }
919             break;
920 
921 #ifdef MANAGEMENT_PF
922         case IEC_CLIENT_PF:
923             if (man->persist.callback.client_pf)
924             {
925                 const bool status = (*man->persist.callback.client_pf)
926                                         (man->persist.callback.arg,
927                                         man->connection.in_extra_cid,
928                                         man->connection.in_extra);
929                 man->connection.in_extra = NULL;
930                 if (status)
931                 {
932                     msg(M_CLIENT, "SUCCESS: client-pf command succeeded");
933                 }
934                 else
935                 {
936                     msg(M_CLIENT, "ERROR: client-pf command failed");
937                 }
938             }
939             else
940             {
941                 msg(M_CLIENT, "ERROR: The client-pf command is not supported by the current daemon mode");
942             }
943             break;
944 
945 #endif /* ifdef MANAGEMENT_PF */
946         case IEC_PK_SIGN:
947             man->connection.ext_key_state = EKS_READY;
948             buffer_list_free(man->connection.ext_key_input);
949             man->connection.ext_key_input = man->connection.in_extra;
950             man->connection.in_extra = NULL;
951             return;
952 
953         case IEC_CERTIFICATE:
954             man->connection.ext_cert_state = EKS_READY;
955             buffer_list_free(man->connection.ext_cert_input);
956             man->connection.ext_cert_input = man->connection.in_extra;
957             man->connection.in_extra = NULL;
958             return;
959     }
960     in_extra_reset(&man->connection, IER_RESET);
961 }
962 
963 static bool
parse_cid(const char * str,unsigned long * cid)964 parse_cid(const char *str, unsigned long *cid)
965 {
966     if (sscanf(str, "%lu", cid) == 1)
967     {
968         return true;
969     }
970     else
971     {
972         msg(M_CLIENT, "ERROR: cannot parse CID");
973         return false;
974     }
975 }
976 
977 static bool
parse_uint(const char * str,const char * what,unsigned int * uint)978 parse_uint(const char *str, const char* what, unsigned int *uint)
979 {
980     if (sscanf(str, "%u", uint) == 1)
981     {
982         return true;
983     }
984     else
985     {
986         msg(M_CLIENT, "ERROR: cannot parse %s", what);
987         return false;
988     }
989 }
990 
991 /**
992  * Will send a notification to the client that succesful authentication
993  * will require an additional step (web based SSO/2-factor auth/etc)
994  *
995  * @param man           The management interface struct
996  * @param cid_str       The CID in string form
997  * @param extra         The string to be send to the client containing
998  *                      the information of the additional steps
999  */
1000 static void
man_client_pending_auth(struct management * man,const char * cid_str,const char * extra,const char * timeout_str)1001 man_client_pending_auth(struct management *man, const char *cid_str,
1002                         const char *extra, const char *timeout_str)
1003 {
1004     unsigned long cid = 0;
1005     unsigned int timeout = 0;
1006     if (parse_cid(cid_str, &cid)
1007         && parse_uint(timeout_str, "TIMEOUT", &timeout))
1008     {
1009         if (man->persist.callback.client_pending_auth)
1010         {
1011             bool ret = (*man->persist.callback.client_pending_auth)
1012                            (man->persist.callback.arg, cid, extra, timeout);
1013 
1014             if (ret)
1015             {
1016                 msg(M_CLIENT, "SUCCESS: client-pending-auth command succeeded");
1017             }
1018             else
1019             {
1020                 msg(M_CLIENT, "SUCCESS: client-pending-auth command failed."
1021                     " Extra paramter might be too long");
1022             }
1023         }
1024         else
1025         {
1026             msg(M_CLIENT, "ERROR: The client-pending-auth command is not supported by the current daemon mode");
1027         }
1028     }
1029 }
1030 
1031 static void
man_client_auth(struct management * man,const char * cid_str,const char * kid_str,const bool extra)1032 man_client_auth(struct management *man, const char *cid_str, const char *kid_str, const bool extra)
1033 {
1034     struct man_connection *mc = &man->connection;
1035     mc->in_extra_cid = 0;
1036     mc->in_extra_kid = 0;
1037     if (parse_cid(cid_str, &mc->in_extra_cid)
1038         && parse_uint(kid_str, "KID", &mc->in_extra_kid))
1039     {
1040         mc->in_extra_cmd = IEC_CLIENT_AUTH;
1041         in_extra_reset(mc, IER_NEW);
1042         if (!extra)
1043         {
1044             in_extra_dispatch(man);
1045         }
1046     }
1047 }
1048 
1049 static void
man_client_deny(struct management * man,const char * cid_str,const char * kid_str,const char * reason,const char * client_reason)1050 man_client_deny(struct management *man, const char *cid_str, const char *kid_str, const char *reason, const char *client_reason)
1051 {
1052     unsigned long cid = 0;
1053     unsigned int kid = 0;
1054     if (parse_cid(cid_str, &cid) && parse_uint(kid_str, "KID", &kid))
1055     {
1056         if (man->persist.callback.client_auth)
1057         {
1058             const bool status = (*man->persist.callback.client_auth)
1059                                     (man->persist.callback.arg,
1060                                     cid,
1061                                     kid,
1062                                     false,
1063                                     reason,
1064                                     client_reason,
1065                                     NULL);
1066             if (status)
1067             {
1068                 msg(M_CLIENT, "SUCCESS: client-deny command succeeded");
1069             }
1070             else
1071             {
1072                 msg(M_CLIENT, "ERROR: client-deny command failed");
1073             }
1074         }
1075         else
1076         {
1077             msg(M_CLIENT, "ERROR: The client-deny command is not supported by the current daemon mode");
1078         }
1079     }
1080 }
1081 
1082 static void
man_client_kill(struct management * man,const char * cid_str,const char * kill_msg)1083 man_client_kill(struct management *man, const char *cid_str, const char *kill_msg)
1084 {
1085     unsigned long cid = 0;
1086     if (parse_cid(cid_str, &cid))
1087     {
1088         if (man->persist.callback.kill_by_cid)
1089         {
1090             const bool status = (*man->persist.callback.kill_by_cid)(man->persist.callback.arg, cid, kill_msg);
1091             if (status)
1092             {
1093                 msg(M_CLIENT, "SUCCESS: client-kill command succeeded");
1094             }
1095             else
1096             {
1097                 msg(M_CLIENT, "ERROR: client-kill command failed");
1098             }
1099         }
1100         else
1101         {
1102             msg(M_CLIENT, "ERROR: The client-kill command is not supported by the current daemon mode");
1103         }
1104     }
1105 }
1106 
1107 static void
man_client_n_clients(struct management * man)1108 man_client_n_clients(struct management *man)
1109 {
1110     if (man->persist.callback.n_clients)
1111     {
1112         const int nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
1113         msg(M_CLIENT, "SUCCESS: nclients=%d", nclients);
1114     }
1115     else
1116     {
1117         msg(M_CLIENT, "ERROR: The nclients command is not supported by the current daemon mode");
1118     }
1119 }
1120 
1121 static void
man_env_filter(struct management * man,const int level)1122 man_env_filter(struct management *man, const int level)
1123 {
1124     man->connection.env_filter_level = level;
1125     msg(M_CLIENT, "SUCCESS: env_filter_level=%d", level);
1126 }
1127 
1128 #ifdef MANAGEMENT_PF
1129 
1130 static void
man_client_pf(struct management * man,const char * cid_str)1131 man_client_pf(struct management *man, const char *cid_str)
1132 {
1133     struct man_connection *mc = &man->connection;
1134     mc->in_extra_cid = 0;
1135     mc->in_extra_kid = 0;
1136     if (parse_cid(cid_str, &mc->in_extra_cid))
1137     {
1138         mc->in_extra_cmd = IEC_CLIENT_PF;
1139         in_extra_reset(mc, IER_NEW);
1140     }
1141 }
1142 
1143 #endif /* MANAGEMENT_PF */
1144 
1145 static void
man_pk_sig(struct management * man,const char * cmd_name)1146 man_pk_sig(struct management *man, const char *cmd_name)
1147 {
1148     struct man_connection *mc = &man->connection;
1149     if (mc->ext_key_state == EKS_SOLICIT)
1150     {
1151         mc->ext_key_state = EKS_INPUT;
1152         mc->in_extra_cmd = IEC_PK_SIGN;
1153         in_extra_reset(mc, IER_NEW);
1154     }
1155     else
1156     {
1157         msg(M_CLIENT, "ERROR: The %s command is not currently available", cmd_name);
1158     }
1159 }
1160 
1161 static void
man_certificate(struct management * man)1162 man_certificate(struct management *man)
1163 {
1164     struct man_connection *mc = &man->connection;
1165     if (mc->ext_cert_state == EKS_SOLICIT)
1166     {
1167         mc->ext_cert_state = EKS_INPUT;
1168         mc->in_extra_cmd = IEC_CERTIFICATE;
1169         in_extra_reset(mc, IER_NEW);
1170     }
1171     else
1172     {
1173         msg(M_CLIENT, "ERROR: The certificate command is not currently available");
1174     }
1175 }
1176 
1177 static void
man_load_stats(struct management * man)1178 man_load_stats(struct management *man)
1179 {
1180     extern counter_type link_read_bytes_global;
1181     extern counter_type link_write_bytes_global;
1182     int nclients = 0;
1183 
1184     if (man->persist.callback.n_clients)
1185     {
1186         nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
1187     }
1188     msg(M_CLIENT, "SUCCESS: nclients=%d,bytesin=" counter_format ",bytesout=" counter_format,
1189         nclients,
1190         link_read_bytes_global,
1191         link_write_bytes_global);
1192 }
1193 
1194 #define MN_AT_LEAST (1<<0)
1195 /**
1196  * Checks if the correct number of arguments to a management command are present
1197  * and otherwise prints an error and returns false.
1198  *
1199  * @param p         pointer to the parameter array
1200  * @param n         number of arguments required
1201  * @param flags     if MN_AT_LEAST require at least n parameters and not exactly n
1202  * @return          Return whether p has n (or at least n) parameters
1203  */
1204 static bool
man_need(struct management * man,const char ** p,const int n,unsigned int flags)1205 man_need(struct management *man, const char **p, const int n, unsigned int flags)
1206 {
1207     int i;
1208     ASSERT(p[0]);
1209     for (i = 1; i <= n; ++i)
1210     {
1211         if (!p[i])
1212         {
1213             msg(M_CLIENT, "ERROR: the '%s' command requires %s%d parameter%s",
1214                 p[0],
1215                 (flags & MN_AT_LEAST) ? "at least " : "",
1216                 n,
1217                 n > 1 ? "s" : "");
1218             return false;
1219         }
1220     }
1221     return true;
1222 }
1223 
1224 static void
man_proxy(struct management * man,const char ** p)1225 man_proxy(struct management *man, const char **p)
1226 {
1227     if (man->persist.callback.proxy_cmd)
1228     {
1229         const bool status = (*man->persist.callback.proxy_cmd)(man->persist.callback.arg, p);
1230         if (status)
1231         {
1232             msg(M_CLIENT, "SUCCESS: proxy command succeeded");
1233         }
1234         else
1235         {
1236             msg(M_CLIENT, "ERROR: proxy command failed");
1237         }
1238     }
1239     else
1240     {
1241         msg(M_CLIENT, "ERROR: The proxy command is not supported by the current daemon mode");
1242     }
1243 }
1244 
1245 static void
man_remote(struct management * man,const char ** p)1246 man_remote(struct management *man, const char **p)
1247 {
1248     if (man->persist.callback.remote_cmd)
1249     {
1250         const bool status = (*man->persist.callback.remote_cmd)(man->persist.callback.arg, p);
1251         if (status)
1252         {
1253             msg(M_CLIENT, "SUCCESS: remote command succeeded");
1254         }
1255         else
1256         {
1257             msg(M_CLIENT, "ERROR: remote command failed");
1258         }
1259     }
1260     else
1261     {
1262         msg(M_CLIENT, "ERROR: The remote command is not supported by the current daemon mode");
1263     }
1264 }
1265 
1266 #ifdef TARGET_ANDROID
1267 static void
man_network_change(struct management * man,bool samenetwork)1268 man_network_change(struct management *man, bool samenetwork)
1269 {
1270     /* Called to signal the OpenVPN that the network configuration has changed and
1271      * the client should either float or reconnect.
1272      *
1273      * The code is currently only used by ics-openvpn
1274      */
1275     if (man->persist.callback.network_change)
1276     {
1277         int fd = (*man->persist.callback.network_change)
1278                      (man->persist.callback.arg, samenetwork);
1279         man->connection.fdtosend = fd;
1280         msg(M_CLIENT, "PROTECTFD: fd '%d' sent to be protected", fd);
1281         if (fd == -2)
1282         {
1283             man_signal(man, "SIGUSR1");
1284         }
1285     }
1286 }
1287 #endif
1288 
1289 static void
set_client_version(struct management * man,const char * version)1290 set_client_version(struct management *man, const char *version)
1291 {
1292     if (version)
1293     {
1294         man->connection.client_version = atoi(version);
1295     }
1296 }
1297 
1298 static void
man_dispatch_command(struct management * man,struct status_output * so,const char ** p,const int nparms)1299 man_dispatch_command(struct management *man, struct status_output *so, const char **p, const int nparms)
1300 {
1301     struct gc_arena gc = gc_new();
1302 
1303     ASSERT(p[0]);
1304     if (streq(p[0], "exit") || streq(p[0], "quit"))
1305     {
1306         man->connection.halt = true;
1307         goto done;
1308     }
1309     else if (streq(p[0], "help"))
1310     {
1311         man_help();
1312     }
1313     else if (streq(p[0], "version") && p[1])
1314     {
1315         set_client_version(man, p[1]);
1316     }
1317     else if (streq(p[0], "version"))
1318     {
1319         msg(M_CLIENT, "OpenVPN Version: %s", title_string);
1320         msg(M_CLIENT, "Management Version: %d", MANAGEMENT_VERSION);
1321         msg(M_CLIENT, "END");
1322     }
1323     else if (streq(p[0], "pid"))
1324     {
1325         msg(M_CLIENT, "SUCCESS: pid=%d", platform_getpid());
1326     }
1327     else if (streq(p[0], "nclients"))
1328     {
1329         man_client_n_clients(man);
1330     }
1331     else if (streq(p[0], "env-filter"))
1332     {
1333         int level = 0;
1334         if (p[1])
1335         {
1336             level = atoi(p[1]);
1337         }
1338         man_env_filter(man, level);
1339     }
1340     else if (streq(p[0], "signal"))
1341     {
1342         if (man_need(man, p, 1, 0))
1343         {
1344             man_signal(man, p[1]);
1345         }
1346     }
1347 #ifdef TARGET_ANDROID
1348     else if (streq(p[0], "network-change"))
1349     {
1350         bool samenetwork = false;
1351         if (p[1] && streq(p[1], "samenetwork"))
1352         {
1353             samenetwork = true;
1354         }
1355 
1356         man_network_change(man, samenetwork);
1357     }
1358 #endif
1359     else if (streq(p[0], "load-stats"))
1360     {
1361         man_load_stats(man);
1362     }
1363     else if (streq(p[0], "status"))
1364     {
1365         int version = 0;
1366         if (p[1])
1367         {
1368             version = atoi(p[1]);
1369         }
1370         man_status(man, version, so);
1371     }
1372     else if (streq(p[0], "kill"))
1373     {
1374         if (man_need(man, p, 1, 0))
1375         {
1376             man_kill(man, p[1]);
1377         }
1378     }
1379     else if (streq(p[0], "verb"))
1380     {
1381         if (p[1])
1382         {
1383             const int level = atoi(p[1]);
1384             if (set_debug_level(level, 0))
1385             {
1386                 msg(M_CLIENT, "SUCCESS: verb level changed");
1387             }
1388             else
1389             {
1390                 msg(M_CLIENT, "ERROR: verb level is out of range");
1391             }
1392         }
1393         else
1394         {
1395             msg(M_CLIENT, "SUCCESS: verb=%d", get_debug_level());
1396         }
1397     }
1398     else if (streq(p[0], "mute"))
1399     {
1400         if (p[1])
1401         {
1402             const int level = atoi(p[1]);
1403             if (set_mute_cutoff(level))
1404             {
1405                 msg(M_CLIENT, "SUCCESS: mute level changed");
1406             }
1407             else
1408             {
1409                 msg(M_CLIENT, "ERROR: mute level is out of range");
1410             }
1411         }
1412         else
1413         {
1414             msg(M_CLIENT, "SUCCESS: mute=%d", get_mute_cutoff());
1415         }
1416     }
1417     else if (streq(p[0], "auth-retry"))
1418     {
1419         if (p[1])
1420         {
1421             if (auth_retry_set(M_CLIENT, p[1]))
1422             {
1423                 msg(M_CLIENT, "SUCCESS: auth-retry parameter changed");
1424             }
1425             else
1426             {
1427                 msg(M_CLIENT, "ERROR: bad auth-retry parameter");
1428             }
1429         }
1430         else
1431         {
1432             msg(M_CLIENT, "SUCCESS: auth-retry=%s", auth_retry_print());
1433         }
1434     }
1435     else if (streq(p[0], "state"))
1436     {
1437         if (!p[1])
1438         {
1439             man_state(man, "1");
1440         }
1441         else
1442         {
1443             if (p[1])
1444             {
1445                 man_state(man, p[1]);
1446             }
1447             if (p[2])
1448             {
1449                 man_state(man, p[2]);
1450             }
1451         }
1452     }
1453     else if (streq(p[0], "log"))
1454     {
1455         if (man_need(man, p, 1, MN_AT_LEAST))
1456         {
1457             if (p[1])
1458             {
1459                 man_log(man, p[1]);
1460             }
1461             if (p[2])
1462             {
1463                 man_log(man, p[2]);
1464             }
1465         }
1466     }
1467     else if (streq(p[0], "echo"))
1468     {
1469         if (man_need(man, p, 1, MN_AT_LEAST))
1470         {
1471             if (p[1])
1472             {
1473                 man_echo(man, p[1]);
1474             }
1475             if (p[2])
1476             {
1477                 man_echo(man, p[2]);
1478             }
1479         }
1480     }
1481     else if (streq(p[0], "username"))
1482     {
1483         if (man_need(man, p, 2, 0))
1484         {
1485             man_query_username(man, p[1], p[2]);
1486         }
1487     }
1488     else if (streq(p[0], "password"))
1489     {
1490         if (man_need(man, p, 2, 0))
1491         {
1492             man_query_password(man, p[1], p[2]);
1493         }
1494     }
1495     else if (streq(p[0], "forget-passwords"))
1496     {
1497         man_forget_passwords(man);
1498     }
1499     else if (streq(p[0], "needok"))
1500     {
1501         if (man_need(man, p, 2, 0))
1502         {
1503             man_query_need_ok(man, p[1], p[2]);
1504         }
1505     }
1506     else if (streq(p[0], "needstr"))
1507     {
1508         if (man_need(man, p, 2, 0))
1509         {
1510             man_query_need_str(man, p[1], p[2]);
1511         }
1512     }
1513     else if (streq(p[0], "cr-response"))
1514     {
1515         if (man_need(man, p, 1, 0))
1516         {
1517             man_send_cc_message(man, "CR_RESPONSE", p[1]);
1518         }
1519     }
1520     else if (streq(p[0], "net"))
1521     {
1522         man_net(man);
1523     }
1524     else if (streq(p[0], "hold"))
1525     {
1526         man_hold(man, p[1]);
1527     }
1528     else if (streq(p[0], "bytecount"))
1529     {
1530         if (man_need(man, p, 1, 0))
1531         {
1532             man_bytecount(man, atoi(p[1]));
1533         }
1534     }
1535     else if (streq(p[0], "client-kill"))
1536     {
1537         if (man_need(man, p, 1, MN_AT_LEAST))
1538         {
1539             man_client_kill(man, p[1], p[2]);
1540         }
1541     }
1542     else if (streq(p[0], "client-deny"))
1543     {
1544         if (man_need(man, p, 3, MN_AT_LEAST))
1545         {
1546             man_client_deny(man, p[1], p[2], p[3], p[4]);
1547         }
1548     }
1549     else if (streq(p[0], "client-auth-nt"))
1550     {
1551         if (man_need(man, p, 2, 0))
1552         {
1553             man_client_auth(man, p[1], p[2], false);
1554         }
1555     }
1556     else if (streq(p[0], "client-auth"))
1557     {
1558         if (man_need(man, p, 2, 0))
1559         {
1560             man_client_auth(man, p[1], p[2], true);
1561         }
1562     }
1563     else if (streq(p[0], "client-pending-auth"))
1564     {
1565         if (man_need(man, p, 3, 0))
1566         {
1567             man_client_pending_auth(man, p[1], p[2], p[3]);
1568         }
1569     }
1570 #ifdef MANAGEMENT_PF
1571     else if (streq(p[0], "client-pf"))
1572     {
1573         if (man_need(man, p, 1, 0))
1574         {
1575             man_client_pf(man, p[1]);
1576         }
1577     }
1578 #endif
1579     else if (streq(p[0], "rsa-sig"))
1580     {
1581         man_pk_sig(man, "rsa-sig");
1582     }
1583     else if (streq(p[0], "pk-sig"))
1584     {
1585         man_pk_sig(man, "pk-sig");
1586     }
1587     else if (streq(p[0], "certificate"))
1588     {
1589         man_certificate(man);
1590     }
1591 #ifdef ENABLE_PKCS11
1592     else if (streq(p[0], "pkcs11-id-count"))
1593     {
1594         man_pkcs11_id_count(man);
1595     }
1596     else if (streq(p[0], "pkcs11-id-get"))
1597     {
1598         if (man_need(man, p, 1, 0))
1599         {
1600             man_pkcs11_id_get(man, atoi(p[1]));
1601         }
1602     }
1603 #endif
1604     else if (streq(p[0], "proxy"))
1605     {
1606         if (man_need(man, p, 1, MN_AT_LEAST))
1607         {
1608             man_proxy(man, p);
1609         }
1610     }
1611     else if (streq(p[0], "remote"))
1612     {
1613         if (man_need(man, p, 1, MN_AT_LEAST))
1614         {
1615             man_remote(man, p);
1616         }
1617     }
1618 #if 1
1619     else if (streq(p[0], "test"))
1620     {
1621         if (man_need(man, p, 1, 0))
1622         {
1623             int i;
1624             const int n = atoi(p[1]);
1625             for (i = 0; i < n; ++i)
1626             {
1627                 msg(M_CLIENT, "[%d] The purpose of this command is to generate large amounts of output.", i);
1628             }
1629         }
1630     }
1631 #endif
1632     else
1633     {
1634         msg(M_CLIENT, "ERROR: unknown command, enter 'help' for more options");
1635     }
1636 
1637 done:
1638     gc_free(&gc);
1639 }
1640 
1641 #ifdef _WIN32
1642 
1643 static void
man_start_ne32(struct management * man)1644 man_start_ne32(struct management *man)
1645 {
1646     switch (man->connection.state)
1647     {
1648         case MS_LISTEN:
1649             net_event_win32_start(&man->connection.ne32, FD_ACCEPT, man->connection.sd_top);
1650             break;
1651 
1652         case MS_CC_WAIT_READ:
1653         case MS_CC_WAIT_WRITE:
1654             net_event_win32_start(&man->connection.ne32, FD_READ|FD_WRITE|FD_CLOSE, man->connection.sd_cli);
1655             break;
1656 
1657         default:
1658             ASSERT(0);
1659     }
1660 }
1661 
1662 static void
man_stop_ne32(struct management * man)1663 man_stop_ne32(struct management *man)
1664 {
1665     net_event_win32_stop(&man->connection.ne32);
1666 }
1667 
1668 #endif /* ifdef _WIN32 */
1669 
1670 static void
man_record_peer_info(struct management * man)1671 man_record_peer_info(struct management *man)
1672 {
1673     struct gc_arena gc = gc_new();
1674     if (man->settings.write_peer_info_file)
1675     {
1676         bool success = false;
1677 #ifdef HAVE_GETSOCKNAME
1678         if (socket_defined(man->connection.sd_cli))
1679         {
1680             struct sockaddr_in addr;
1681             socklen_t addrlen = sizeof(addr);
1682             int status;
1683 
1684             CLEAR(addr);
1685             status = getsockname(man->connection.sd_cli, (struct sockaddr *)&addr, &addrlen);
1686             if (!status && addrlen == sizeof(addr))
1687             {
1688                 const in_addr_t a = ntohl(addr.sin_addr.s_addr);
1689                 const int p = ntohs(addr.sin_port);
1690                 FILE *fp = platform_fopen(man->settings.write_peer_info_file, "w");
1691                 if (fp)
1692                 {
1693                     fprintf(fp, "%s\n%d\n", print_in_addr_t(a, 0, &gc), p);
1694                     if (!fclose(fp))
1695                     {
1696                         success = true;
1697                     }
1698                 }
1699             }
1700         }
1701 #endif /* ifdef HAVE_GETSOCKNAME */
1702         if (!success)
1703         {
1704             msg(D_MANAGEMENT, "MANAGEMENT: failed to write peer info to file %s",
1705                 man->settings.write_peer_info_file);
1706             throw_signal_soft(SIGTERM, "management-connect-failed");
1707         }
1708     }
1709     gc_free(&gc);
1710 }
1711 
1712 static void
man_connection_settings_reset(struct management * man)1713 man_connection_settings_reset(struct management *man)
1714 {
1715     man->connection.state_realtime = false;
1716     man->connection.log_realtime = false;
1717     man->connection.echo_realtime = false;
1718     man->connection.bytecount_update_seconds = 0;
1719     man->connection.password_verified = false;
1720     man->connection.password_tries = 0;
1721     man->connection.halt = false;
1722     man->connection.state = MS_CC_WAIT_WRITE;
1723 }
1724 
1725 static void
man_new_connection_post(struct management * man,const char * description)1726 man_new_connection_post(struct management *man, const char *description)
1727 {
1728     struct gc_arena gc = gc_new();
1729 
1730     set_nonblock(man->connection.sd_cli);
1731 
1732     man_connection_settings_reset(man);
1733 
1734 #ifdef _WIN32
1735     man_start_ne32(man);
1736 #endif
1737 
1738 #if UNIX_SOCK_SUPPORT
1739     if (man->settings.flags & MF_UNIX_SOCK)
1740     {
1741         msg(D_MANAGEMENT, "MANAGEMENT: %s %s",
1742             description,
1743             sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1744     }
1745     else
1746 #endif
1747     msg(D_MANAGEMENT, "MANAGEMENT: %s %s",
1748         description,
1749         print_sockaddr(man->settings.local->ai_addr, &gc));
1750 
1751     buffer_list_reset(man->connection.out);
1752 
1753     if (!man_password_needed(man))
1754     {
1755         man_welcome(man);
1756     }
1757     man_prompt(man);
1758     man_update_io_state(man);
1759 
1760     gc_free(&gc);
1761 }
1762 
1763 #if UNIX_SOCK_SUPPORT
1764 static bool
man_verify_unix_peer_uid_gid(struct management * man,const socket_descriptor_t sd)1765 man_verify_unix_peer_uid_gid(struct management *man, const socket_descriptor_t sd)
1766 {
1767     if (socket_defined(sd) && (man->settings.client_uid != -1 || man->settings.client_gid != -1))
1768     {
1769         static const char err_prefix[] = "MANAGEMENT: unix domain socket client connection rejected --";
1770         int uid, gid;
1771         if (unix_socket_get_peer_uid_gid(man->connection.sd_cli, &uid, &gid))
1772         {
1773             if (man->settings.client_uid != -1 && man->settings.client_uid != uid)
1774             {
1775                 msg(D_MANAGEMENT, "%s UID of socket peer (%d) doesn't match required value (%d) as given by --management-client-user",
1776                     err_prefix, uid, man->settings.client_uid);
1777                 return false;
1778             }
1779             if (man->settings.client_gid != -1 && man->settings.client_gid != gid)
1780             {
1781                 msg(D_MANAGEMENT, "%s GID of socket peer (%d) doesn't match required value (%d) as given by --management-client-group",
1782                     err_prefix, gid, man->settings.client_gid);
1783                 return false;
1784             }
1785         }
1786         else
1787         {
1788             msg(D_MANAGEMENT, "%s cannot get UID/GID of socket peer", err_prefix);
1789             return false;
1790         }
1791     }
1792     return true;
1793 }
1794 #endif /* if UNIX_SOCK_SUPPORT */
1795 
1796 static void
man_accept(struct management * man)1797 man_accept(struct management *man)
1798 {
1799     struct link_socket_actual act;
1800     CLEAR(act);
1801 
1802     /*
1803      * Accept the TCP or Unix domain socket client.
1804      */
1805 #if UNIX_SOCK_SUPPORT
1806     if (man->settings.flags & MF_UNIX_SOCK)
1807     {
1808         struct sockaddr_un remote;
1809         man->connection.sd_cli = socket_accept_unix(man->connection.sd_top, &remote);
1810         if (!man_verify_unix_peer_uid_gid(man, man->connection.sd_cli))
1811         {
1812             sd_close(&man->connection.sd_cli);
1813         }
1814     }
1815     else
1816 #endif
1817     man->connection.sd_cli = socket_do_accept(man->connection.sd_top, &act, false);
1818 
1819     if (socket_defined(man->connection.sd_cli))
1820     {
1821         man->connection.remote = act.dest;
1822 
1823         if (socket_defined(man->connection.sd_top))
1824         {
1825 #ifdef _WIN32
1826             man_stop_ne32(man);
1827 #endif
1828         }
1829 
1830         man_new_connection_post(man, "Client connected from");
1831     }
1832 }
1833 
1834 static void
man_listen(struct management * man)1835 man_listen(struct management *man)
1836 {
1837     struct gc_arena gc = gc_new();
1838 
1839     /*
1840      * Initialize state
1841      */
1842     man->connection.state = MS_LISTEN;
1843     man->connection.sd_cli = SOCKET_UNDEFINED;
1844 
1845     /*
1846      * Initialize listening socket
1847      */
1848     if (man->connection.sd_top == SOCKET_UNDEFINED)
1849     {
1850 #if UNIX_SOCK_SUPPORT
1851         if (man->settings.flags & MF_UNIX_SOCK)
1852         {
1853             man_delete_unix_socket(man);
1854             man->connection.sd_top = create_socket_unix();
1855             socket_bind_unix(man->connection.sd_top, &man->settings.local_unix, "MANAGEMENT");
1856         }
1857         else
1858 #endif
1859         {
1860             man->connection.sd_top = create_socket_tcp(man->settings.local);
1861             socket_bind(man->connection.sd_top, man->settings.local,
1862                         man->settings.local->ai_family, "MANAGEMENT", false);
1863         }
1864 
1865         /*
1866          * Listen for connection
1867          */
1868         if (listen(man->connection.sd_top, 1))
1869         {
1870             msg(M_ERR, "MANAGEMENT: listen() failed");
1871         }
1872 
1873         /*
1874          * Set misc socket properties
1875          */
1876         set_nonblock(man->connection.sd_top);
1877 
1878 #if UNIX_SOCK_SUPPORT
1879         if (man->settings.flags & MF_UNIX_SOCK)
1880         {
1881             msg(D_MANAGEMENT, "MANAGEMENT: unix domain socket listening on %s",
1882                 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1883         }
1884         else
1885 #endif
1886         msg(D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s",
1887             print_sockaddr(man->settings.local->ai_addr, &gc));
1888     }
1889 
1890 #ifdef _WIN32
1891     man_start_ne32(man);
1892 #endif
1893 
1894     gc_free(&gc);
1895 }
1896 
1897 static void
man_connect(struct management * man)1898 man_connect(struct management *man)
1899 {
1900     struct gc_arena gc = gc_new();
1901     int status;
1902     int signal_received = 0;
1903 
1904     /*
1905      * Initialize state
1906      */
1907     man->connection.state = MS_INITIAL;
1908     man->connection.sd_top = SOCKET_UNDEFINED;
1909 
1910 #if UNIX_SOCK_SUPPORT
1911     if (man->settings.flags & MF_UNIX_SOCK)
1912     {
1913         man->connection.sd_cli = create_socket_unix();
1914         status = socket_connect_unix(man->connection.sd_cli, &man->settings.local_unix);
1915         if (!status && !man_verify_unix_peer_uid_gid(man, man->connection.sd_cli))
1916         {
1917 #ifdef EPERM
1918             status = EPERM;
1919 #else
1920             status = 1;
1921 #endif
1922             sd_close(&man->connection.sd_cli);
1923         }
1924     }
1925     else
1926 #endif
1927     {
1928         man->connection.sd_cli = create_socket_tcp(man->settings.local);
1929         status = openvpn_connect(man->connection.sd_cli,
1930                                  man->settings.local->ai_addr,
1931                                  5,
1932                                  &signal_received);
1933     }
1934 
1935     if (signal_received)
1936     {
1937         throw_signal(signal_received);
1938         goto done;
1939     }
1940 
1941     if (status)
1942     {
1943 #if UNIX_SOCK_SUPPORT
1944         if (man->settings.flags & MF_UNIX_SOCK)
1945         {
1946             msg(D_LINK_ERRORS | M_ERRNO,
1947                 "MANAGEMENT: connect to unix socket %s failed",
1948                 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1949         }
1950         else
1951 #endif
1952         msg(D_LINK_ERRORS | M_ERRNO,
1953             "MANAGEMENT: connect to %s failed",
1954             print_sockaddr(man->settings.local->ai_addr, &gc));
1955         throw_signal_soft(SIGTERM, "management-connect-failed");
1956         goto done;
1957     }
1958 
1959     man_record_peer_info(man);
1960     man_new_connection_post(man, "Connected to management server at");
1961 
1962 done:
1963     gc_free(&gc);
1964 }
1965 
1966 static void
man_reset_client_socket(struct management * man,const bool exiting)1967 man_reset_client_socket(struct management *man, const bool exiting)
1968 {
1969     if (socket_defined(man->connection.sd_cli))
1970     {
1971 #ifdef _WIN32
1972         man_stop_ne32(man);
1973 #endif
1974         man_close_socket(man, man->connection.sd_cli);
1975         man->connection.sd_cli = SOCKET_UNDEFINED;
1976         man->connection.state = MS_INITIAL;
1977         command_line_reset(man->connection.in);
1978         buffer_list_reset(man->connection.out);
1979         in_extra_reset(&man->connection, IER_RESET);
1980         msg(D_MANAGEMENT, "MANAGEMENT: Client disconnected");
1981     }
1982     if (!exiting)
1983     {
1984         if (man->settings.flags & MF_FORGET_DISCONNECT)
1985         {
1986             ssl_purge_auth(false);
1987         }
1988 
1989         if (man->settings.flags & MF_SIGNAL)
1990         {
1991             int mysig = man_mod_signal(man, SIGUSR1);
1992             if (mysig >= 0)
1993             {
1994                 msg(D_MANAGEMENT, "MANAGEMENT: Triggering management signal");
1995                 throw_signal_soft(mysig, "management-disconnect");
1996             }
1997         }
1998 
1999         if (man->settings.flags & MF_CONNECT_AS_CLIENT)
2000         {
2001             msg(D_MANAGEMENT, "MANAGEMENT: Triggering management exit");
2002             throw_signal_soft(SIGTERM, "management-exit");
2003         }
2004         else
2005         {
2006             man_listen(man);
2007         }
2008     }
2009 }
2010 
2011 static void
man_process_command(struct management * man,const char * line)2012 man_process_command(struct management *man, const char *line)
2013 {
2014     struct gc_arena gc = gc_new();
2015     struct status_output *so;
2016     int nparms;
2017     char *parms[MAX_PARMS+1];
2018 
2019     CLEAR(parms);
2020     so = status_open(NULL, 0, -1, &man->persist.vout, 0);
2021     in_extra_reset(&man->connection, IER_RESET);
2022 
2023     if (man_password_needed(man))
2024     {
2025         man_check_password(man, line);
2026     }
2027     else
2028     {
2029         nparms = parse_line(line, parms, MAX_PARMS, "TCP", 0, M_CLIENT, &gc);
2030         if (parms[0] && streq(parms[0], "password"))
2031         {
2032             msg(D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD 'password [...]'");
2033         }
2034         else if (!streq(line, "load-stats"))
2035         {
2036             msg(D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD '%s'", line);
2037         }
2038 
2039 #if 0
2040         /* DEBUGGING -- print args */
2041         {
2042             int i;
2043             for (i = 0; i < nparms; ++i)
2044             {
2045                 msg(M_INFO, "[%d] '%s'", i, parms[i]);
2046             }
2047         }
2048 #endif
2049 
2050         if (nparms > 0)
2051         {
2052             man_dispatch_command(man, so, (const char **)parms, nparms);
2053         }
2054     }
2055 
2056     CLEAR(parms);
2057     status_close(so);
2058     gc_free(&gc);
2059 }
2060 
2061 static bool
man_io_error(struct management * man,const char * prefix)2062 man_io_error(struct management *man, const char *prefix)
2063 {
2064     const int err = openvpn_errno();
2065 
2066     if (!ignore_sys_error(err))
2067     {
2068         struct gc_arena gc = gc_new();
2069         msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix,
2070             strerror(err));
2071         gc_free(&gc);
2072         return true;
2073     }
2074     else
2075     {
2076         return false;
2077     }
2078 }
2079 
2080 #ifdef TARGET_ANDROID
2081 static ssize_t
man_send_with_fd(int fd,void * ptr,size_t nbytes,int flags,int sendfd)2082 man_send_with_fd(int fd, void *ptr, size_t nbytes, int flags, int sendfd)
2083 {
2084     struct msghdr msg = { 0 };
2085     struct iovec iov[1];
2086 
2087     union {
2088         struct cmsghdr cm;
2089         char control[CMSG_SPACE(sizeof(int))];
2090     } control_un;
2091     struct cmsghdr *cmptr;
2092 
2093     msg.msg_control = control_un.control;
2094     msg.msg_controllen = sizeof(control_un.control);
2095 
2096     cmptr = CMSG_FIRSTHDR(&msg);
2097     cmptr->cmsg_len = CMSG_LEN(sizeof(int));
2098     cmptr->cmsg_level = SOL_SOCKET;
2099     cmptr->cmsg_type = SCM_RIGHTS;
2100     *((int *) CMSG_DATA(cmptr)) = sendfd;
2101 
2102     msg.msg_name = NULL;
2103     msg.msg_namelen = 0;
2104 
2105     iov[0].iov_base = ptr;
2106     iov[0].iov_len = nbytes;
2107     msg.msg_iov = iov;
2108     msg.msg_iovlen = 1;
2109 
2110     return (sendmsg(fd, &msg, flags));
2111 }
2112 
2113 static ssize_t
man_recv_with_fd(int fd,void * ptr,size_t nbytes,int flags,int * recvfd)2114 man_recv_with_fd(int fd, void *ptr, size_t nbytes, int flags, int *recvfd)
2115 {
2116     struct msghdr msghdr = { 0 };
2117     struct iovec iov[1];
2118     ssize_t n;
2119 
2120     union {
2121         struct cmsghdr cm;
2122         char control[CMSG_SPACE(sizeof(int))];
2123     } control_un;
2124     struct cmsghdr  *cmptr;
2125 
2126     msghdr.msg_control  = control_un.control;
2127     msghdr.msg_controllen = sizeof(control_un.control);
2128 
2129     msghdr.msg_name = NULL;
2130     msghdr.msg_namelen = 0;
2131 
2132     iov[0].iov_base = ptr;
2133     iov[0].iov_len = nbytes;
2134     msghdr.msg_iov = iov;
2135     msghdr.msg_iovlen = 1;
2136 
2137     if ( (n = recvmsg(fd, &msghdr, flags)) <= 0)
2138     {
2139         return (n);
2140     }
2141 
2142     if ( (cmptr = CMSG_FIRSTHDR(&msghdr)) != NULL
2143          && cmptr->cmsg_len == CMSG_LEN(sizeof(int)))
2144     {
2145         if (cmptr->cmsg_level != SOL_SOCKET)
2146         {
2147             msg(M_ERR, "control level != SOL_SOCKET");
2148         }
2149         if (cmptr->cmsg_type != SCM_RIGHTS)
2150         {
2151             msg(M_ERR, "control type != SCM_RIGHTS");
2152         }
2153         *recvfd = *((int *) CMSG_DATA(cmptr));
2154     }
2155     else
2156     {
2157         *recvfd = -1;       /* descriptor was not passed */
2158 
2159     }
2160     return (n);
2161 }
2162 
2163 /*
2164  * The android control method will instruct the GUI part of openvpn to do
2165  * the route/ifconfig/open tun command.   See doc/android.txt for details.
2166  */
2167 bool
management_android_control(struct management * man,const char * command,const char * msg)2168 management_android_control(struct management *man, const char *command, const char *msg)
2169 {
2170     struct user_pass up;
2171     CLEAR(up);
2172     strncpy(up.username, msg, sizeof(up.username)-1);
2173 
2174     management_query_user_pass(management, &up, command, GET_USER_PASS_NEED_OK,(void *) 0);
2175     return strcmp("ok", up.password)==0;
2176 }
2177 
2178 /*
2179  * In Android 4.4 it is not possible to open a new tun device and then close the
2180  * old tun device without breaking the whole VPNService stack until the device
2181  * is rebooted. This management method ask the UI what method should be taken to
2182  * ensure the optimal solution for the situation
2183  */
2184 int
managment_android_persisttun_action(struct management * man)2185 managment_android_persisttun_action(struct management *man)
2186 {
2187     struct user_pass up;
2188     CLEAR(up);
2189     strcpy(up.username,"tunmethod");
2190     management_query_user_pass(management, &up, "PERSIST_TUN_ACTION",
2191                                GET_USER_PASS_NEED_OK,(void *) 0);
2192     if (!strcmp("NOACTION", up.password))
2193     {
2194         return ANDROID_KEEP_OLD_TUN;
2195     }
2196     else if (!strcmp("OPEN_AFTER_CLOSE", up.password))
2197     {
2198         return ANDROID_OPEN_AFTER_CLOSE;
2199     }
2200     else if (!strcmp("OPEN_BEFORE_CLOSE", up.password))
2201     {
2202         return ANDROID_OPEN_BEFORE_CLOSE;
2203     }
2204     else
2205     {
2206         msg(M_ERR, "Got unrecognised '%s' from management for PERSIST_TUN_ACTION query", up.password);
2207     }
2208 
2209     ASSERT(0);
2210     return ANDROID_OPEN_AFTER_CLOSE;
2211 }
2212 
2213 
2214 #endif /* ifdef TARGET_ANDROID */
2215 
2216 static int
man_read(struct management * man)2217 man_read(struct management *man)
2218 {
2219     /*
2220      * read command line from socket
2221      */
2222     unsigned char buf[256];
2223     int len = 0;
2224 
2225 #ifdef TARGET_ANDROID
2226     int fd;
2227     len = man_recv_with_fd(man->connection.sd_cli, buf, sizeof(buf), MSG_NOSIGNAL, &fd);
2228     if (fd >= 0)
2229     {
2230         man->connection.lastfdreceived = fd;
2231     }
2232 #else  /* ifdef TARGET_ANDROID */
2233     len = recv(man->connection.sd_cli, buf, sizeof(buf), MSG_NOSIGNAL);
2234 #endif
2235 
2236     if (len == 0)
2237     {
2238         man_reset_client_socket(man, false);
2239     }
2240     else if (len > 0)
2241     {
2242         bool processed_command = false;
2243 
2244         ASSERT(len <= (int) sizeof(buf));
2245         command_line_add(man->connection.in, buf, len);
2246 
2247         /*
2248          * Reset output object
2249          */
2250         buffer_list_reset(man->connection.out);
2251 
2252         /*
2253          * process command line if complete
2254          */
2255         {
2256             const char *line;
2257             while ((line = command_line_get(man->connection.in)))
2258             {
2259                 if (man->connection.in_extra)
2260                 {
2261                     if (!strcmp(line, "END"))
2262                     {
2263                         in_extra_dispatch(man);
2264                     }
2265                     else
2266                     {
2267                         buffer_list_push(man->connection.in_extra, line);
2268                     }
2269                 }
2270                 else
2271                 {
2272                     man_process_command(man, (char *) line);
2273                 }
2274                 if (man->connection.halt)
2275                 {
2276                     break;
2277                 }
2278                 command_line_next(man->connection.in);
2279                 processed_command = true;
2280             }
2281         }
2282 
2283         /*
2284          * Reset output state to MS_CC_WAIT_(READ|WRITE)
2285          */
2286         if (man->connection.halt)
2287         {
2288             man_reset_client_socket(man, false);
2289             len = 0;
2290         }
2291         else
2292         {
2293             if (processed_command)
2294             {
2295                 man_prompt(man);
2296             }
2297             man_update_io_state(man);
2298         }
2299     }
2300     else /* len < 0 */
2301     {
2302         if (man_io_error(man, "recv"))
2303         {
2304             man_reset_client_socket(man, false);
2305         }
2306     }
2307     return len;
2308 }
2309 
2310 static int
man_write(struct management * man)2311 man_write(struct management *man)
2312 {
2313     const int size_hint = 1024;
2314     int sent = 0;
2315     const struct buffer *buf;
2316 
2317     buffer_list_aggregate(man->connection.out, size_hint);
2318     buf = buffer_list_peek(man->connection.out);
2319     if (buf && BLEN(buf))
2320     {
2321         const int len = min_int(size_hint, BLEN(buf));
2322 #ifdef TARGET_ANDROID
2323         if (man->connection.fdtosend > 0)
2324         {
2325             sent = man_send_with_fd(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL,man->connection.fdtosend);
2326             man->connection.fdtosend = -1;
2327         }
2328         else
2329 #endif
2330         sent = send(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL);
2331         if (sent >= 0)
2332         {
2333             buffer_list_advance(man->connection.out, sent);
2334         }
2335         else if (sent < 0)
2336         {
2337             if (man_io_error(man, "send"))
2338             {
2339                 man_reset_client_socket(man, false);
2340             }
2341         }
2342     }
2343 
2344     /*
2345      * Reset output state to MS_CC_WAIT_(READ|WRITE)
2346      */
2347     man_update_io_state(man);
2348 
2349     return sent;
2350 }
2351 
2352 static void
man_connection_clear(struct man_connection * mc)2353 man_connection_clear(struct man_connection *mc)
2354 {
2355     CLEAR(*mc);
2356 
2357     /* set initial state */
2358     mc->state = MS_INITIAL;
2359 
2360     /* clear socket descriptors */
2361     mc->sd_top = SOCKET_UNDEFINED;
2362     mc->sd_cli = SOCKET_UNDEFINED;
2363 }
2364 
2365 static void
man_persist_init(struct management * man,const int log_history_cache,const int echo_buffer_size,const int state_buffer_size)2366 man_persist_init(struct management *man,
2367                  const int log_history_cache,
2368                  const int echo_buffer_size,
2369                  const int state_buffer_size)
2370 {
2371     struct man_persist *mp = &man->persist;
2372     if (!mp->defined)
2373     {
2374         CLEAR(*mp);
2375 
2376         /* initialize log history store */
2377         mp->log = log_history_init(log_history_cache);
2378 
2379         /*
2380          * Initialize virtual output object, so that functions
2381          * which write to a virtual_output object can be redirected
2382          * here to the management object.
2383          */
2384         mp->vout.func = virtual_output_callback_func;
2385         mp->vout.arg = man;
2386         mp->vout.flags_default = M_CLIENT;
2387         msg_set_virtual_output(&mp->vout);
2388 
2389         /*
2390          * Initialize --echo list
2391          */
2392         man->persist.echo = log_history_init(echo_buffer_size);
2393 
2394         /*
2395          * Initialize --state list
2396          */
2397         man->persist.state = log_history_init(state_buffer_size);
2398 
2399         mp->defined = true;
2400     }
2401 }
2402 
2403 static void
man_persist_close(struct man_persist * mp)2404 man_persist_close(struct man_persist *mp)
2405 {
2406     if (mp->log)
2407     {
2408         msg_set_virtual_output(NULL);
2409         log_history_close(mp->log);
2410     }
2411 
2412     if (mp->echo)
2413     {
2414         log_history_close(mp->echo);
2415     }
2416 
2417     if (mp->state)
2418     {
2419         log_history_close(mp->state);
2420     }
2421 
2422     CLEAR(*mp);
2423 }
2424 
2425 static void
man_settings_init(struct man_settings * ms,const char * addr,const char * port,const char * pass_file,const char * client_user,const char * client_group,const int log_history_cache,const int echo_buffer_size,const int state_buffer_size,const char * write_peer_info_file,const int remap_sigusr1,const unsigned int flags)2426 man_settings_init(struct man_settings *ms,
2427                   const char *addr,
2428                   const char *port,
2429                   const char *pass_file,
2430                   const char *client_user,
2431                   const char *client_group,
2432                   const int log_history_cache,
2433                   const int echo_buffer_size,
2434                   const int state_buffer_size,
2435                   const char *write_peer_info_file,
2436                   const int remap_sigusr1,
2437                   const unsigned int flags)
2438 {
2439     if (!ms->defined)
2440     {
2441         CLEAR(*ms);
2442 
2443         ms->flags = flags;
2444         ms->client_uid = -1;
2445         ms->client_gid = -1;
2446 
2447         /*
2448          * Get username/password
2449          */
2450         if (pass_file)
2451         {
2452             get_user_pass(&ms->up, pass_file, "Management", GET_USER_PASS_PASSWORD_ONLY);
2453         }
2454 
2455         /*
2456          * lookup client UID/GID if specified
2457          */
2458         if (client_user)
2459         {
2460             struct platform_state_user s;
2461             platform_user_get(client_user, &s);
2462             ms->client_uid = platform_state_user_uid(&s);
2463             msg(D_MANAGEMENT, "MANAGEMENT: client_uid=%d", ms->client_uid);
2464             ASSERT(ms->client_uid >= 0);
2465         }
2466         if (client_group)
2467         {
2468             struct platform_state_group s;
2469             platform_group_get(client_group, &s);
2470             ms->client_gid = platform_state_group_gid(&s);
2471             msg(D_MANAGEMENT, "MANAGEMENT: client_gid=%d", ms->client_gid);
2472             ASSERT(ms->client_gid >= 0);
2473         }
2474 
2475         ms->write_peer_info_file = string_alloc(write_peer_info_file, NULL);
2476 
2477 #if UNIX_SOCK_SUPPORT
2478         if (ms->flags & MF_UNIX_SOCK)
2479         {
2480             sockaddr_unix_init(&ms->local_unix, addr);
2481         }
2482         else
2483 #endif
2484         {
2485 
2486             /*
2487              * Run management over tunnel, or
2488              * separate channel?
2489              */
2490             if (streq(addr, "tunnel") && !(flags & MF_CONNECT_AS_CLIENT))
2491             {
2492                 ms->management_over_tunnel = true;
2493             }
2494             else
2495             {
2496                 int status;
2497                 int resolve_flags = GETADDR_RESOLVE|GETADDR_WARN_ON_SIGNAL|GETADDR_FATAL;
2498 
2499                 if (!(flags & MF_CONNECT_AS_CLIENT))
2500                 {
2501                     resolve_flags |= GETADDR_PASSIVE;
2502                 }
2503 
2504                 status = openvpn_getaddrinfo(resolve_flags, addr, port, 0,
2505                                              NULL, AF_UNSPEC, &ms->local);
2506                 ASSERT(status==0);
2507             }
2508         }
2509 
2510         /*
2511          * Log history and echo buffer may need to be resized
2512          */
2513         ms->log_history_cache = log_history_cache;
2514         ms->echo_buffer_size = echo_buffer_size;
2515         ms->state_buffer_size = state_buffer_size;
2516 
2517         /*
2518          * Set remap sigusr1 flags
2519          */
2520         if (remap_sigusr1 == SIGHUP)
2521         {
2522             ms->mansig |= MANSIG_MAP_USR1_TO_HUP;
2523         }
2524         else if (remap_sigusr1 == SIGTERM)
2525         {
2526             ms->mansig |= MANSIG_MAP_USR1_TO_TERM;
2527         }
2528 
2529         ms->defined = true;
2530     }
2531 }
2532 
2533 static void
man_settings_close(struct man_settings * ms)2534 man_settings_close(struct man_settings *ms)
2535 {
2536     if (ms->local)
2537     {
2538         freeaddrinfo(ms->local);
2539     }
2540     free(ms->write_peer_info_file);
2541     CLEAR(*ms);
2542 }
2543 
2544 
2545 static void
man_connection_init(struct management * man)2546 man_connection_init(struct management *man)
2547 {
2548     if (man->connection.state == MS_INITIAL)
2549     {
2550 #ifdef _WIN32
2551         /*
2552          * This object is a sort of TCP/IP helper
2553          * for Windows.
2554          */
2555         net_event_win32_init(&man->connection.ne32);
2556 #endif
2557 
2558         /*
2559          * Allocate helper objects for command line input and
2560          * command output from/to the socket.
2561          */
2562         man->connection.in = command_line_new(1024);
2563         man->connection.out = buffer_list_new(0);
2564 
2565         /*
2566          * Initialize event set for standalone usage, when we are
2567          * running outside of the primary event loop.
2568          */
2569         {
2570             int maxevents = 1;
2571             man->connection.es = event_set_init(&maxevents, EVENT_METHOD_FAST);
2572         }
2573 
2574         man->connection.client_version = 1; /* default version */
2575 
2576         /*
2577          * Listen/connect socket
2578          */
2579         if (man->settings.flags & MF_CONNECT_AS_CLIENT)
2580         {
2581             man_connect(man);
2582         }
2583         else
2584         {
2585             man_listen(man);
2586         }
2587     }
2588 }
2589 
2590 static void
man_connection_close(struct management * man)2591 man_connection_close(struct management *man)
2592 {
2593     struct man_connection *mc = &man->connection;
2594 
2595     event_free(mc->es);
2596 #ifdef _WIN32
2597     net_event_win32_close(&mc->ne32);
2598 #endif
2599     if (socket_defined(mc->sd_top))
2600     {
2601         man_close_socket(man, mc->sd_top);
2602         man_delete_unix_socket(man);
2603     }
2604     if (socket_defined(mc->sd_cli))
2605     {
2606         man_close_socket(man, mc->sd_cli);
2607     }
2608 
2609     command_line_free(mc->in);
2610     buffer_list_free(mc->out);
2611 
2612     in_extra_reset(&man->connection, IER_RESET);
2613     buffer_list_free(mc->ext_key_input);
2614     man_connection_clear(mc);
2615 }
2616 
2617 struct management *
management_init(void)2618 management_init(void)
2619 {
2620     struct management *man;
2621     ALLOC_OBJ_CLEAR(man, struct management);
2622 
2623     man_persist_init(man,
2624                      MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
2625                      MANAGEMENT_ECHO_BUFFER_SIZE,
2626                      MANAGEMENT_STATE_BUFFER_SIZE);
2627 
2628     man_connection_clear(&man->connection);
2629 
2630     return man;
2631 }
2632 
2633 bool
management_open(struct management * man,const char * addr,const char * port,const char * pass_file,const char * client_user,const char * client_group,const int log_history_cache,const int echo_buffer_size,const int state_buffer_size,const char * write_peer_info_file,const int remap_sigusr1,const unsigned int flags)2634 management_open(struct management *man,
2635                 const char *addr,
2636                 const char *port,
2637                 const char *pass_file,
2638                 const char *client_user,
2639                 const char *client_group,
2640                 const int log_history_cache,
2641                 const int echo_buffer_size,
2642                 const int state_buffer_size,
2643                 const char *write_peer_info_file,
2644                 const int remap_sigusr1,
2645                 const unsigned int flags)
2646 {
2647     bool ret = false;
2648 
2649     /*
2650      * Save the settings only if they have not
2651      * been saved before.
2652      */
2653     man_settings_init(&man->settings,
2654                       addr,
2655                       port,
2656                       pass_file,
2657                       client_user,
2658                       client_group,
2659                       log_history_cache,
2660                       echo_buffer_size,
2661                       state_buffer_size,
2662                       write_peer_info_file,
2663                       remap_sigusr1,
2664                       flags);
2665 
2666     /*
2667      * The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
2668      * but may be changed here.  Ditto for echo and state buffers.
2669      */
2670     log_history_resize(man->persist.log, man->settings.log_history_cache);
2671     log_history_resize(man->persist.echo, man->settings.echo_buffer_size);
2672     log_history_resize(man->persist.state, man->settings.state_buffer_size);
2673 
2674     /*
2675      * If connection object is uninitialized and we are not doing
2676      * over-the-tunnel management, then open (listening) connection.
2677      */
2678     if (man->connection.state == MS_INITIAL)
2679     {
2680         if (!man->settings.management_over_tunnel)
2681         {
2682             man_connection_init(man);
2683             ret = true;
2684         }
2685     }
2686 
2687     return ret;
2688 }
2689 
2690 void
management_close(struct management * man)2691 management_close(struct management *man)
2692 {
2693     man_output_list_push_finalize(man); /* flush output queue */
2694     man_connection_close(man);
2695     man_settings_close(&man->settings);
2696     man_persist_close(&man->persist);
2697     free(man);
2698 }
2699 
2700 void
management_set_callback(struct management * man,const struct management_callback * cb)2701 management_set_callback(struct management *man,
2702                         const struct management_callback *cb)
2703 {
2704     man->persist.standalone_disabled = true;
2705     man->persist.callback = *cb;
2706 }
2707 
2708 void
management_clear_callback(struct management * man)2709 management_clear_callback(struct management *man)
2710 {
2711     man->persist.standalone_disabled = false;
2712     man->persist.hold_release = false;
2713     CLEAR(man->persist.callback);
2714     man_output_list_push_finalize(man); /* flush output queue */
2715 }
2716 
2717 void
management_set_state(struct management * man,const int state,const char * detail,const in_addr_t * tun_local_ip,const struct in6_addr * tun_local_ip6,const struct openvpn_sockaddr * local,const struct openvpn_sockaddr * remote)2718 management_set_state(struct management *man,
2719                      const int state,
2720                      const char *detail,
2721                      const in_addr_t *tun_local_ip,
2722                      const struct in6_addr *tun_local_ip6,
2723                      const struct openvpn_sockaddr *local,
2724                      const struct openvpn_sockaddr *remote)
2725 {
2726     if (man->persist.state && (!(man->settings.flags & MF_SERVER) || state < OPENVPN_STATE_CLIENT_BASE))
2727     {
2728         struct gc_arena gc = gc_new();
2729         struct log_entry e;
2730         const char *out = NULL;
2731 
2732         update_time();
2733         CLEAR(e);
2734         e.timestamp = now;
2735         e.u.state = state;
2736         e.string = detail;
2737         if (tun_local_ip)
2738         {
2739             e.local_ip = *tun_local_ip;
2740         }
2741         if (tun_local_ip6)
2742         {
2743             e.local_ip6 = *tun_local_ip6;
2744         }
2745         if (local)
2746         {
2747             e.local_sock = *local;
2748         }
2749         if (remote)
2750         {
2751             e.remote_sock = *remote;
2752         }
2753 
2754         log_history_add(man->persist.state, &e);
2755 
2756         if (man->connection.state_realtime)
2757         {
2758             out = log_entry_print(&e, LOG_PRINT_STATE_PREFIX
2759                                   |   LOG_PRINT_INT_DATE
2760                                   |   LOG_PRINT_STATE
2761                                   |   LOG_PRINT_LOCAL_IP
2762                                   |   LOG_PRINT_REMOTE_IP
2763                                   |   LOG_PRINT_CRLF
2764                                   |   LOG_ECHO_TO_LOG, &gc);
2765         }
2766 
2767         if (out)
2768         {
2769             man_output_list_push(man, out);
2770         }
2771 
2772         gc_free(&gc);
2773     }
2774 }
2775 
2776 static bool
env_filter_match(const char * env_str,const int env_filter_level)2777 env_filter_match(const char *env_str, const int env_filter_level)
2778 {
2779     static const char *env_names[] = {
2780         "username=",
2781         "password=",
2782         "X509_0_CN=",
2783         "tls_serial_",
2784         "untrusted_ip=",
2785         "ifconfig_local=",
2786         "ifconfig_netmask=",
2787         "daemon_start_time=",
2788         "daemon_pid=",
2789         "dev=",
2790         "ifconfig_pool_remote_ip=",
2791         "ifconfig_pool_netmask=",
2792         "time_duration=",
2793         "bytes_sent=",
2794         "bytes_received=",
2795         "session_id=",
2796         "session_state="
2797     };
2798 
2799     if (env_filter_level == 0)
2800     {
2801         return true;
2802     }
2803     else if (env_filter_level <= 1 && !strncmp(env_str, "X509_", 5))
2804     {
2805         return true;
2806     }
2807     else if (env_filter_level <= 2)
2808     {
2809         size_t i;
2810         for (i = 0; i < SIZE(env_names); ++i)
2811         {
2812             const char *en = env_names[i];
2813             const size_t len = strlen(en);
2814             if (!strncmp(env_str, en, len))
2815             {
2816                 return true;
2817             }
2818         }
2819         return false;
2820     }
2821     return false;
2822 }
2823 
2824 static void
man_output_env(const struct env_set * es,const bool tail,const int env_filter_level,const char * prefix)2825 man_output_env(const struct env_set *es, const bool tail, const int env_filter_level, const char *prefix)
2826 {
2827     if (es)
2828     {
2829         struct env_item *e;
2830         for (e = es->list; e != NULL; e = e->next)
2831         {
2832             if (e->string && (!env_filter_level || env_filter_match(e->string, env_filter_level)))
2833             {
2834                 msg(M_CLIENT, ">%s:ENV,%s", prefix, e->string);
2835             }
2836         }
2837     }
2838     if (tail)
2839     {
2840         msg(M_CLIENT, ">%s:ENV,END", prefix);
2841     }
2842 }
2843 
2844 static void
man_output_extra_env(struct management * man,const char * prefix)2845 man_output_extra_env(struct management *man, const char *prefix)
2846 {
2847     struct gc_arena gc = gc_new();
2848     struct env_set *es = env_set_create(&gc);
2849     if (man->persist.callback.n_clients)
2850     {
2851         const int nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
2852         setenv_int(es, "n_clients", nclients);
2853     }
2854     man_output_env(es, false, man->connection.env_filter_level, prefix);
2855     gc_free(&gc);
2856 }
2857 
2858 void
management_up_down(struct management * man,const char * updown,const struct env_set * es)2859 management_up_down(struct management *man, const char *updown, const struct env_set *es)
2860 {
2861     if (man->settings.flags & MF_UP_DOWN)
2862     {
2863         msg(M_CLIENT, ">UPDOWN:%s", updown);
2864         man_output_env(es, true, 0, "UPDOWN");
2865     }
2866 }
2867 
2868 void
management_notify(struct management * man,const char * severity,const char * type,const char * text)2869 management_notify(struct management *man, const char *severity, const char *type, const char *text)
2870 {
2871     msg(M_CLIENT, ">NOTIFY:%s,%s,%s", severity, type, text);
2872 }
2873 
2874 void
management_notify_generic(struct management * man,const char * str)2875 management_notify_generic(struct management *man, const char *str)
2876 {
2877     msg(M_CLIENT, "%s", str);
2878 }
2879 
2880 static void
man_output_peer_info_env(struct management * man,const struct man_def_auth_context * mdac)2881 man_output_peer_info_env(struct management *man, const struct man_def_auth_context *mdac)
2882 {
2883     char line[256];
2884     if (man->persist.callback.get_peer_info)
2885     {
2886         const char *peer_info = (*man->persist.callback.get_peer_info)(man->persist.callback.arg, mdac->cid);
2887         if (peer_info)
2888         {
2889             struct buffer buf;
2890             buf_set_read(&buf, (const uint8_t *) peer_info, strlen(peer_info));
2891             while (buf_parse(&buf, '\n', line, sizeof(line)))
2892             {
2893                 chomp(line);
2894                 if (validate_peer_info_line(line))
2895                 {
2896                     msg(M_CLIENT, ">CLIENT:ENV,%s", line);
2897                 }
2898                 else
2899                 {
2900                     msg(D_MANAGEMENT, "validation failed on peer_info line received from client");
2901                 }
2902             }
2903         }
2904     }
2905 }
2906 
2907 void
management_notify_client_needing_auth(struct management * management,const unsigned int mda_key_id,struct man_def_auth_context * mdac,const struct env_set * es)2908 management_notify_client_needing_auth(struct management *management,
2909                                       const unsigned int mda_key_id,
2910                                       struct man_def_auth_context *mdac,
2911                                       const struct env_set *es)
2912 {
2913     if (!(mdac->flags & DAF_CONNECTION_CLOSED))
2914     {
2915         const char *mode = "CONNECT";
2916         if (mdac->flags & DAF_CONNECTION_ESTABLISHED)
2917         {
2918             mode = "REAUTH";
2919         }
2920         msg(M_CLIENT, ">CLIENT:%s,%lu,%u", mode, mdac->cid, mda_key_id);
2921         man_output_extra_env(management, "CLIENT");
2922         if (management->connection.env_filter_level>0)
2923         {
2924             man_output_peer_info_env(management, mdac);
2925         }
2926         man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2927         mdac->flags |= DAF_INITIAL_AUTH;
2928     }
2929 }
2930 
2931 void
management_notify_client_cr_response(unsigned mda_key_id,const struct man_def_auth_context * mdac,const struct env_set * es,const char * response)2932 management_notify_client_cr_response(unsigned mda_key_id,
2933                                      const struct man_def_auth_context *mdac,
2934                                      const struct env_set *es,
2935                                      const char *response)
2936 {
2937     struct gc_arena gc;
2938     if (management)
2939     {
2940         gc = gc_new();
2941 
2942         struct buffer out = alloc_buf_gc(256, &gc);
2943         msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s",
2944             mdac->cid, mda_key_id, response);
2945         man_output_extra_env(management, "CLIENT");
2946         if (management->connection.env_filter_level>0)
2947         {
2948             man_output_peer_info_env(management, mdac);
2949         }
2950         man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2951         management_notify_generic(management, BSTR(&out));
2952 
2953         gc_free(&gc);
2954     }
2955 }
2956 
2957 void
management_connection_established(struct management * management,struct man_def_auth_context * mdac,const struct env_set * es)2958 management_connection_established(struct management *management,
2959                                   struct man_def_auth_context *mdac,
2960                                   const struct env_set *es)
2961 {
2962     mdac->flags |= DAF_CONNECTION_ESTABLISHED;
2963     msg(M_CLIENT, ">CLIENT:ESTABLISHED,%lu", mdac->cid);
2964     man_output_extra_env(management, "CLIENT");
2965     man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2966 }
2967 
2968 void
management_notify_client_close(struct management * management,struct man_def_auth_context * mdac,const struct env_set * es)2969 management_notify_client_close(struct management *management,
2970                                struct man_def_auth_context *mdac,
2971                                const struct env_set *es)
2972 {
2973     if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
2974     {
2975         msg(M_CLIENT, ">CLIENT:DISCONNECT,%lu", mdac->cid);
2976         man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2977         mdac->flags |= DAF_CONNECTION_CLOSED;
2978     }
2979 }
2980 
2981 void
management_learn_addr(struct management * management,struct man_def_auth_context * mdac,const struct mroute_addr * addr,const bool primary)2982 management_learn_addr(struct management *management,
2983                       struct man_def_auth_context *mdac,
2984                       const struct mroute_addr *addr,
2985                       const bool primary)
2986 {
2987     struct gc_arena gc = gc_new();
2988     if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
2989     {
2990         msg(M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d",
2991             mdac->cid,
2992             mroute_addr_print_ex(addr, MAPF_SUBNET, &gc),
2993             BOOL_CAST(primary));
2994     }
2995     gc_free(&gc);
2996 }
2997 
2998 void
management_echo(struct management * man,const char * string,const bool pull)2999 management_echo(struct management *man, const char *string, const bool pull)
3000 {
3001     if (man->persist.echo)
3002     {
3003         struct gc_arena gc = gc_new();
3004         struct log_entry e;
3005         const char *out = NULL;
3006 
3007         update_time();
3008         CLEAR(e);
3009         e.timestamp = now;
3010         e.string = string;
3011         e.u.intval = BOOL_CAST(pull);
3012 
3013         log_history_add(man->persist.echo, &e);
3014 
3015         if (man->connection.echo_realtime)
3016         {
3017             out = log_entry_print(&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc);
3018         }
3019 
3020         if (out)
3021         {
3022             man_output_list_push(man, out);
3023         }
3024 
3025         gc_free(&gc);
3026     }
3027 }
3028 
3029 void
management_post_tunnel_open(struct management * man,const in_addr_t tun_local_ip)3030 management_post_tunnel_open(struct management *man, const in_addr_t tun_local_ip)
3031 {
3032     /*
3033      * If we are running management over the tunnel,
3034      * this is the place to initialize the connection.
3035      */
3036     if (man->settings.management_over_tunnel
3037         && man->connection.state == MS_INITIAL)
3038     {
3039         /* listen on our local TUN/TAP IP address */
3040         struct in_addr ia;
3041         int ret;
3042 
3043         ia.s_addr = htonl(tun_local_ip);
3044         ret = openvpn_getaddrinfo(GETADDR_PASSIVE, inet_ntoa(ia), NULL, 0, NULL,
3045                                   AF_INET, &man->settings.local);
3046         ASSERT(ret==0);
3047         man_connection_init(man);
3048     }
3049 
3050 }
3051 
3052 void
management_pre_tunnel_close(struct management * man)3053 management_pre_tunnel_close(struct management *man)
3054 {
3055     if (man->settings.management_over_tunnel)
3056     {
3057         man_connection_close(man);
3058     }
3059 }
3060 
3061 void
management_auth_failure(struct management * man,const char * type,const char * reason)3062 management_auth_failure(struct management *man, const char *type, const char *reason)
3063 {
3064     if (reason)
3065     {
3066         msg(M_CLIENT, ">PASSWORD:Verification Failed: '%s' ['%s']", type, reason);
3067     }
3068     else
3069     {
3070         msg(M_CLIENT, ">PASSWORD:Verification Failed: '%s'", type);
3071     }
3072 }
3073 
3074 void
management_auth_token(struct management * man,const char * token)3075 management_auth_token(struct management *man, const char *token)
3076 {
3077     msg(M_CLIENT, ">PASSWORD:Auth-Token:%s", token);
3078 }
3079 
3080 static inline bool
man_persist_state(unsigned int * persistent,const int n)3081 man_persist_state(unsigned int *persistent, const int n)
3082 {
3083     if (persistent)
3084     {
3085         if (*persistent == (unsigned int)n)
3086         {
3087             return false;
3088         }
3089         *persistent = n;
3090     }
3091     return true;
3092 }
3093 
3094 #ifdef _WIN32
3095 
3096 void
management_socket_set(struct management * man,struct event_set * es,void * arg,unsigned int * persistent)3097 management_socket_set(struct management *man,
3098                       struct event_set *es,
3099                       void *arg,
3100                       unsigned int *persistent)
3101 {
3102     if (man->connection.state != MS_INITIAL)
3103     {
3104         event_t ev = net_event_win32_get_event(&man->connection.ne32);
3105         net_event_win32_reset_write(&man->connection.ne32);
3106 
3107         switch (man->connection.state)
3108         {
3109             case MS_LISTEN:
3110                 if (man_persist_state(persistent, 1))
3111                 {
3112                     event_ctl(es, ev, EVENT_READ, arg);
3113                 }
3114                 break;
3115 
3116             case MS_CC_WAIT_READ:
3117                 if (man_persist_state(persistent, 2))
3118                 {
3119                     event_ctl(es, ev, EVENT_READ, arg);
3120                 }
3121                 break;
3122 
3123             case MS_CC_WAIT_WRITE:
3124                 if (man_persist_state(persistent, 3))
3125                 {
3126                     event_ctl(es, ev, EVENT_READ|EVENT_WRITE, arg);
3127                 }
3128                 break;
3129 
3130             default:
3131                 ASSERT(0);
3132         }
3133     }
3134 }
3135 
3136 void
management_io(struct management * man)3137 management_io(struct management *man)
3138 {
3139     if (man->connection.state != MS_INITIAL)
3140     {
3141         long net_events;
3142         net_event_win32_reset(&man->connection.ne32);
3143         net_events = net_event_win32_get_event_mask(&man->connection.ne32);
3144 
3145         if (net_events & FD_CLOSE)
3146         {
3147             man_reset_client_socket(man, false);
3148         }
3149         else
3150         {
3151             if (man->connection.state == MS_LISTEN)
3152             {
3153                 if (net_events & FD_ACCEPT)
3154                 {
3155                     man_accept(man);
3156                     net_event_win32_clear_selected_events(&man->connection.ne32, FD_ACCEPT);
3157                 }
3158             }
3159             else if (man->connection.state == MS_CC_WAIT_READ || man->connection.state == MS_CC_WAIT_WRITE)
3160             {
3161                 if (net_events & FD_READ)
3162                 {
3163                     while (man_read(man) > 0)
3164                     {
3165                     }
3166                     net_event_win32_clear_selected_events(&man->connection.ne32, FD_READ);
3167                 }
3168 
3169                 if (net_events & FD_WRITE)
3170                 {
3171                     int status;
3172                     status = man_write(man);
3173                     if (status < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
3174                     {
3175                         net_event_win32_clear_selected_events(&man->connection.ne32, FD_WRITE);
3176                     }
3177                 }
3178             }
3179         }
3180     }
3181 }
3182 
3183 #else  /* ifdef _WIN32 */
3184 
3185 void
management_socket_set(struct management * man,struct event_set * es,void * arg,unsigned int * persistent)3186 management_socket_set(struct management *man,
3187                       struct event_set *es,
3188                       void *arg,
3189                       unsigned int *persistent)
3190 {
3191     switch (man->connection.state)
3192     {
3193         case MS_LISTEN:
3194             if (man_persist_state(persistent, 1))
3195             {
3196                 event_ctl(es, man->connection.sd_top, EVENT_READ, arg);
3197             }
3198             break;
3199 
3200         case MS_CC_WAIT_READ:
3201             if (man_persist_state(persistent, 2))
3202             {
3203                 event_ctl(es, man->connection.sd_cli, EVENT_READ, arg);
3204             }
3205             break;
3206 
3207         case MS_CC_WAIT_WRITE:
3208             if (man_persist_state(persistent, 3))
3209             {
3210                 event_ctl(es, man->connection.sd_cli, EVENT_WRITE, arg);
3211             }
3212             break;
3213 
3214         case MS_INITIAL:
3215             break;
3216 
3217         default:
3218             ASSERT(0);
3219     }
3220 }
3221 
3222 void
management_io(struct management * man)3223 management_io(struct management *man)
3224 {
3225     switch (man->connection.state)
3226     {
3227         case MS_LISTEN:
3228             man_accept(man);
3229             break;
3230 
3231         case MS_CC_WAIT_READ:
3232             man_read(man);
3233             break;
3234 
3235         case MS_CC_WAIT_WRITE:
3236             man_write(man);
3237             break;
3238 
3239         case MS_INITIAL:
3240             break;
3241 
3242         default:
3243             ASSERT(0);
3244     }
3245 }
3246 
3247 #endif /* ifdef _WIN32 */
3248 
3249 static inline bool
man_standalone_ok(const struct management * man)3250 man_standalone_ok(const struct management *man)
3251 {
3252     return !man->settings.management_over_tunnel && man->connection.state != MS_INITIAL;
3253 }
3254 
3255 static bool
man_check_for_signals(volatile int * signal_received)3256 man_check_for_signals(volatile int *signal_received)
3257 {
3258     if (signal_received)
3259     {
3260         get_signal(signal_received);
3261         if (*signal_received)
3262         {
3263             return true;
3264         }
3265     }
3266     return false;
3267 }
3268 
3269 /*
3270  * Wait for socket I/O when outside primary event loop
3271  */
3272 static int
man_block(struct management * man,volatile int * signal_received,const time_t expire)3273 man_block(struct management *man, volatile int *signal_received, const time_t expire)
3274 {
3275     struct timeval tv;
3276     struct event_set_return esr;
3277     int status = -1;
3278 
3279     if (man_standalone_ok(man))
3280     {
3281         /* expire time can be already overdue, for this case init zero
3282          * timeout to avoid waiting first time and exit loop early with
3283          * either obtained event or timeout.
3284          */
3285         tv.tv_usec = 0;
3286         tv.tv_sec = 0;
3287 
3288         while (true)
3289         {
3290             event_reset(man->connection.es);
3291             management_socket_set(man, man->connection.es, NULL, NULL);
3292             if (man_check_for_signals(signal_received))
3293             {
3294                 status = -1;
3295                 break;
3296             }
3297             status = event_wait(man->connection.es, &tv, &esr, 1);
3298             update_time();
3299             if (man_check_for_signals(signal_received))
3300             {
3301                 status = -1;
3302                 break;
3303             }
3304 
3305             if (status > 0)
3306             {
3307                 break;
3308             }
3309             else if (expire && now >= expire)
3310             {
3311                 /* set SIGINT signal if expiration time exceeded */
3312                 status = 0;
3313                 if (signal_received)
3314                 {
3315                     *signal_received = SIGINT;
3316                 }
3317                 break;
3318             }
3319 
3320             /* wait one second more */
3321             tv.tv_sec = 1;
3322             tv.tv_usec = 0;
3323         }
3324     }
3325     return status;
3326 }
3327 
3328 /*
3329  * Perform management socket output outside primary event loop
3330  */
3331 static void
man_output_standalone(struct management * man,volatile int * signal_received)3332 man_output_standalone(struct management *man, volatile int *signal_received)
3333 {
3334     if (man_standalone_ok(man))
3335     {
3336         while (man->connection.state == MS_CC_WAIT_WRITE)
3337         {
3338             management_io(man);
3339             if (man->connection.state == MS_CC_WAIT_WRITE)
3340             {
3341                 man_block(man, signal_received, 0);
3342             }
3343             if (signal_received && *signal_received)
3344             {
3345                 break;
3346             }
3347         }
3348     }
3349 }
3350 
3351 /*
3352  * Process management event loop outside primary event loop
3353  */
3354 static int
man_standalone_event_loop(struct management * man,volatile int * signal_received,const time_t expire)3355 man_standalone_event_loop(struct management *man, volatile int *signal_received, const time_t expire)
3356 {
3357     int status = -1;
3358     if (man_standalone_ok(man))
3359     {
3360         status = man_block(man, signal_received, expire);
3361         if (status > 0)
3362         {
3363             management_io(man);
3364         }
3365     }
3366     return status;
3367 }
3368 
3369 #define MWCC_PASSWORD_WAIT (1<<0)
3370 #define MWCC_HOLD_WAIT     (1<<1)
3371 #define MWCC_OTHER_WAIT    (1<<2)
3372 
3373 /*
3374  * Block until client connects
3375  */
3376 static void
man_wait_for_client_connection(struct management * man,volatile int * signal_received,const time_t expire,unsigned int flags)3377 man_wait_for_client_connection(struct management *man,
3378                                volatile int *signal_received,
3379                                const time_t expire,
3380                                unsigned int flags)
3381 {
3382     ASSERT(man_standalone_ok(man));
3383     if (man->connection.state == MS_LISTEN)
3384     {
3385         if (flags & MWCC_PASSWORD_WAIT)
3386         {
3387             msg(D_MANAGEMENT, "Need password(s) from management interface, waiting...");
3388         }
3389         if (flags & MWCC_HOLD_WAIT)
3390         {
3391             msg(D_MANAGEMENT, "Need hold release from management interface, waiting...");
3392         }
3393         if (flags & MWCC_OTHER_WAIT)
3394         {
3395             msg(D_MANAGEMENT, "Need information from management interface, waiting...");
3396         }
3397         do
3398         {
3399             man_standalone_event_loop(man, signal_received, expire);
3400             if (signal_received && *signal_received)
3401             {
3402                 break;
3403             }
3404         } while (man->connection.state == MS_LISTEN || man_password_needed(man));
3405     }
3406 }
3407 
3408 /*
3409  * Process the management event loop for sec seconds
3410  */
3411 void
management_event_loop_n_seconds(struct management * man,int sec)3412 management_event_loop_n_seconds(struct management *man, int sec)
3413 {
3414     if (man_standalone_ok(man))
3415     {
3416         volatile int signal_received = 0;
3417         const bool standalone_disabled_save = man->persist.standalone_disabled;
3418         time_t expire = 0;
3419 
3420         man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3421 
3422         /* set expire time */
3423         update_time();
3424         if (sec >= 0)
3425         {
3426             expire = now + sec;
3427         }
3428 
3429         /* if no client connection, wait for one */
3430         man_wait_for_client_connection(man, &signal_received, expire, 0);
3431         if (signal_received)
3432         {
3433             return;
3434         }
3435 
3436         /* run command processing event loop */
3437         do
3438         {
3439             man_standalone_event_loop(man, &signal_received, expire);
3440             if (!signal_received)
3441             {
3442                 man_check_for_signals(&signal_received);
3443             }
3444             if (signal_received)
3445             {
3446                 return;
3447             }
3448             update_time();
3449         } while (expire && expire > now);
3450 
3451         /* revert state */
3452         man->persist.standalone_disabled = standalone_disabled_save;
3453     }
3454     else if (sec > 0)
3455     {
3456         sleep(sec);
3457     }
3458 }
3459 
3460 /*
3461  * Get a username/password from management channel in standalone mode.
3462  */
3463 bool
management_query_user_pass(struct management * man,struct user_pass * up,const char * type,const unsigned int flags,const char * static_challenge)3464 management_query_user_pass(struct management *man,
3465                            struct user_pass *up,
3466                            const char *type,
3467                            const unsigned int flags,
3468                            const char *static_challenge)
3469 {
3470     struct gc_arena gc = gc_new();
3471     bool ret = false;
3472 
3473     if (man_standalone_ok(man))
3474     {
3475         volatile int signal_received = 0;
3476         const bool standalone_disabled_save = man->persist.standalone_disabled;
3477         struct buffer alert_msg = alloc_buf_gc(128, &gc);
3478         const char *alert_type = NULL;
3479         const char *prefix = NULL;
3480         unsigned int up_query_mode = 0;
3481         const char *sc = NULL;
3482         ret = true;
3483         man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3484         man->persist.special_state_msg = NULL;
3485 
3486         CLEAR(man->connection.up_query);
3487 
3488         if (flags & GET_USER_PASS_NEED_OK)
3489         {
3490             up_query_mode = UP_QUERY_NEED_OK;
3491             prefix = "NEED-OK";
3492             alert_type = "confirmation";
3493         }
3494         else if (flags & GET_USER_PASS_NEED_STR)
3495         {
3496             up_query_mode = UP_QUERY_NEED_STR;
3497             prefix = "NEED-STR";
3498             alert_type = "string";
3499         }
3500         else if (flags & GET_USER_PASS_PASSWORD_ONLY)
3501         {
3502             up_query_mode = UP_QUERY_PASS;
3503             prefix = "PASSWORD";
3504             alert_type = "password";
3505         }
3506         else
3507         {
3508             up_query_mode = UP_QUERY_USER_PASS;
3509             prefix = "PASSWORD";
3510             alert_type = "username/password";
3511             if (static_challenge)
3512             {
3513                 sc = static_challenge;
3514             }
3515         }
3516         buf_printf(&alert_msg, ">%s:Need '%s' %s",
3517                    prefix,
3518                    type,
3519                    alert_type);
3520 
3521         if (flags & (GET_USER_PASS_NEED_OK | GET_USER_PASS_NEED_STR))
3522         {
3523             buf_printf(&alert_msg, " MSG:%s", up->username);
3524         }
3525 
3526         if (sc)
3527         {
3528             buf_printf(&alert_msg, " SC:%d,%s",
3529                        BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALLENGE_ECHO),
3530                        sc);
3531         }
3532 
3533         man_wait_for_client_connection(man, &signal_received, 0, MWCC_PASSWORD_WAIT);
3534         if (signal_received)
3535         {
3536             ret = false;
3537         }
3538 
3539         if (ret)
3540         {
3541             man->persist.special_state_msg = BSTR(&alert_msg);
3542             msg(M_CLIENT, "%s", man->persist.special_state_msg);
3543 
3544             /* tell command line parser which info we need */
3545             man->connection.up_query_mode = up_query_mode;
3546             man->connection.up_query_type = type;
3547 
3548             /* run command processing event loop until we get our username/password/response */
3549             do
3550             {
3551                 man_standalone_event_loop(man, &signal_received, 0);
3552                 if (!signal_received)
3553                 {
3554                     man_check_for_signals(&signal_received);
3555                 }
3556                 if (signal_received)
3557                 {
3558                     ret = false;
3559                     break;
3560                 }
3561             } while (!man->connection.up_query.defined);
3562         }
3563 
3564         /* revert state */
3565         man->connection.up_query_mode = UP_QUERY_DISABLED;
3566         man->connection.up_query_type = NULL;
3567         man->persist.standalone_disabled = standalone_disabled_save;
3568         man->persist.special_state_msg = NULL;
3569 
3570         /* pass through blank passwords */
3571         if (!strcmp(man->connection.up_query.password, blank_up))
3572         {
3573             CLEAR(man->connection.up_query.password);
3574         }
3575 
3576         /*
3577          * Transfer u/p to return object, zero any record
3578          * we hold in the management object.
3579          */
3580         if (ret)
3581         {
3582             /* preserve caller's settings */
3583             man->connection.up_query.nocache = up->nocache;
3584             *up = man->connection.up_query;
3585         }
3586         secure_memzero(&man->connection.up_query, sizeof(man->connection.up_query));
3587     }
3588 
3589     gc_free(&gc);
3590     return ret;
3591 }
3592 
3593 static int
management_query_multiline(struct management * man,const char * b64_data,const char * prompt,const char * cmd,int * state,struct buffer_list ** input)3594 management_query_multiline(struct management *man,
3595                            const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3596 {
3597     struct gc_arena gc = gc_new();
3598     int ret = 0;
3599     volatile int signal_received = 0;
3600     struct buffer alert_msg = clear_buf();
3601     const bool standalone_disabled_save = man->persist.standalone_disabled;
3602     struct man_connection *mc = &man->connection;
3603 
3604     if (man_standalone_ok(man))
3605     {
3606         man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3607         man->persist.special_state_msg = NULL;
3608 
3609         *state = EKS_SOLICIT;
3610 
3611         if (b64_data)
3612         {
3613             alert_msg = alloc_buf_gc(strlen(b64_data)+strlen(prompt)+3, &gc);
3614             buf_printf(&alert_msg, ">%s:%s", prompt, b64_data);
3615         }
3616         else
3617         {
3618             alert_msg = alloc_buf_gc(strlen(prompt)+3, &gc);
3619             buf_printf(&alert_msg, ">%s", prompt);
3620         }
3621 
3622         man_wait_for_client_connection(man, &signal_received, 0, MWCC_OTHER_WAIT);
3623 
3624         if (signal_received)
3625         {
3626             goto done;
3627         }
3628 
3629         man->persist.special_state_msg = BSTR(&alert_msg);
3630         msg(M_CLIENT, "%s", man->persist.special_state_msg);
3631 
3632         /* run command processing event loop until we get our signature */
3633         do
3634         {
3635             man_standalone_event_loop(man, &signal_received, 0);
3636             if (!signal_received)
3637             {
3638                 man_check_for_signals(&signal_received);
3639             }
3640             if (signal_received)
3641             {
3642                 goto done;
3643             }
3644         } while (*state != EKS_READY);
3645 
3646         ret = 1;
3647     }
3648 
3649 done:
3650     if (*state == EKS_READY && ret)
3651     {
3652         msg(M_CLIENT, "SUCCESS: %s command succeeded", cmd);
3653     }
3654     else if (*state == EKS_INPUT || *state == EKS_READY)
3655     {
3656         msg(M_CLIENT, "ERROR: %s command failed", cmd);
3657     }
3658 
3659     /* revert state */
3660     man->persist.standalone_disabled = standalone_disabled_save;
3661     man->persist.special_state_msg = NULL;
3662     in_extra_reset(mc, IER_RESET);
3663     *state = EKS_UNDEF;
3664 
3665     gc_free(&gc);
3666     return ret;
3667 }
3668 
3669 static char *
3670 /* returns allocated base64 signature */
management_query_multiline_flatten_newline(struct management * man,const char * b64_data,const char * prompt,const char * cmd,int * state,struct buffer_list ** input)3671 management_query_multiline_flatten_newline(struct management *man,
3672                                            const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3673 {
3674     int ok;
3675     char *result = NULL;
3676     struct buffer *buf;
3677 
3678     ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
3679     if (ok && buffer_list_defined(*input))
3680     {
3681         buffer_list_aggregate_separator(*input, 10000, "\n");
3682         buf = buffer_list_peek(*input);
3683         if (buf && BLEN(buf) > 0)
3684         {
3685             result = (char *) malloc(BLEN(buf)+1);
3686             check_malloc_return(result);
3687             memcpy(result, buf->data, BLEN(buf));
3688             result[BLEN(buf)] = '\0';
3689         }
3690     }
3691 
3692     buffer_list_free(*input);
3693     *input = NULL;
3694 
3695     return result;
3696 }
3697 
3698 static char *
3699 /* returns allocated base64 signature */
management_query_multiline_flatten(struct management * man,const char * b64_data,const char * prompt,const char * cmd,int * state,struct buffer_list ** input)3700 management_query_multiline_flatten(struct management *man,
3701                                    const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3702 {
3703     int ok;
3704     char *result = NULL;
3705     struct buffer *buf;
3706 
3707     ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
3708     if (ok && buffer_list_defined(*input))
3709     {
3710         buffer_list_aggregate(*input, 2048);
3711         buf = buffer_list_peek(*input);
3712         if (buf && BLEN(buf) > 0)
3713         {
3714             result = (char *) malloc(BLEN(buf)+1);
3715             check_malloc_return(result);
3716             memcpy(result, buf->data, BLEN(buf));
3717             result[BLEN(buf)] = '\0';
3718         }
3719     }
3720 
3721     buffer_list_free(*input);
3722     *input = NULL;
3723 
3724     return result;
3725 }
3726 
3727 char *
3728 /* returns allocated base64 signature */
management_query_pk_sig(struct management * man,const char * b64_data,const char * algorithm)3729 management_query_pk_sig(struct management *man, const char *b64_data,
3730                         const char *algorithm)
3731 {
3732     const char *prompt = "PK_SIGN";
3733     const char *desc = "pk-sign";
3734     struct buffer buf_data = alloc_buf(strlen(b64_data) + strlen(algorithm) + 20);
3735 
3736     if (man->connection.client_version <= 1)
3737     {
3738         prompt = "RSA_SIGN";
3739         desc = "rsa-sign";
3740     }
3741 
3742     buf_write(&buf_data, b64_data, (int) strlen(b64_data));
3743     if (man->connection.client_version > 2)
3744     {
3745         buf_write(&buf_data, ",", (int) strlen(","));
3746         buf_write(&buf_data, algorithm, (int) strlen(algorithm));
3747     }
3748     char *ret = management_query_multiline_flatten(man,
3749                                                    (char *)buf_bptr(&buf_data), prompt, desc,
3750                                                    &man->connection.ext_key_state, &man->connection.ext_key_input);
3751     free_buf(&buf_data);
3752     return ret;
3753 }
3754 
3755 char *
management_query_cert(struct management * man,const char * cert_name)3756 management_query_cert(struct management *man, const char *cert_name)
3757 {
3758     const char prompt_1[] = "NEED-CERTIFICATE:";
3759     struct buffer buf_prompt = alloc_buf(strlen(cert_name) + 20);
3760     buf_write(&buf_prompt, prompt_1, strlen(prompt_1));
3761     buf_write(&buf_prompt, cert_name, strlen(cert_name)+1); /* +1 for \0 */
3762 
3763     char *result;
3764     result = management_query_multiline_flatten_newline(management,
3765                                                         NULL, (char *)buf_bptr(&buf_prompt), "certificate",
3766                                                         &man->connection.ext_cert_state, &man->connection.ext_cert_input);
3767     free_buf(&buf_prompt);
3768     return result;
3769 }
3770 
3771 /*
3772  * Return true if management_hold() would block
3773  */
3774 bool
management_would_hold(struct management * man)3775 management_would_hold(struct management *man)
3776 {
3777     return (man->settings.flags & MF_HOLD) && !man->persist.hold_release && man_standalone_ok(man);
3778 }
3779 
3780 /*
3781  * Return true if (from the management interface's perspective) OpenVPN should
3782  * daemonize.
3783  */
3784 bool
management_should_daemonize(struct management * man)3785 management_should_daemonize(struct management *man)
3786 {
3787     return management_would_hold(man) || (man->settings.flags & MF_QUERY_PASSWORDS);
3788 }
3789 
3790 /*
3791  * If the hold flag is enabled, hibernate until a management client releases the hold.
3792  * Return true if the caller should not sleep for an additional time interval.
3793  */
3794 bool
management_hold(struct management * man,int holdtime)3795 management_hold(struct management *man, int holdtime)
3796 {
3797     if (management_would_hold(man))
3798     {
3799         volatile int signal_received = 0;
3800         const bool standalone_disabled_save = man->persist.standalone_disabled;
3801         struct gc_arena gc = gc_new();
3802 
3803         man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3804         man->persist.special_state_msg = NULL;
3805         man->settings.mansig |= MANSIG_IGNORE_USR1_HUP;
3806 
3807         man_wait_for_client_connection(man, &signal_received, 0, MWCC_HOLD_WAIT);
3808 
3809         if (!signal_received)
3810         {
3811             struct buffer out = alloc_buf_gc(128, &gc);
3812             buf_printf(&out, ">HOLD:Waiting for hold release:%d", holdtime);
3813             man->persist.special_state_msg = BSTR(&out);
3814             msg(M_CLIENT, "%s", man->persist.special_state_msg);
3815 
3816             /* run command processing event loop until we get our username/password */
3817             do
3818             {
3819                 man_standalone_event_loop(man, &signal_received, 0);
3820                 if (!signal_received)
3821                 {
3822                     man_check_for_signals(&signal_received);
3823                 }
3824                 if (signal_received)
3825                 {
3826                     break;
3827                 }
3828             } while (!man->persist.hold_release);
3829         }
3830 
3831         /* revert state */
3832         man->persist.standalone_disabled = standalone_disabled_save;
3833         man->persist.special_state_msg = NULL;
3834         man->settings.mansig &= ~MANSIG_IGNORE_USR1_HUP;
3835 
3836         gc_free(&gc);
3837         return true;
3838     }
3839     return false;
3840 }
3841 
3842 /*
3843  * struct command_line
3844  */
3845 
3846 struct command_line *
command_line_new(const int buf_len)3847 command_line_new(const int buf_len)
3848 {
3849     struct command_line *cl;
3850     ALLOC_OBJ_CLEAR(cl, struct command_line);
3851     cl->buf = alloc_buf(buf_len);
3852     cl->residual = alloc_buf(buf_len);
3853     return cl;
3854 }
3855 
3856 void
command_line_reset(struct command_line * cl)3857 command_line_reset(struct command_line *cl)
3858 {
3859     buf_clear(&cl->buf);
3860     buf_clear(&cl->residual);
3861 }
3862 
3863 void
command_line_free(struct command_line * cl)3864 command_line_free(struct command_line *cl)
3865 {
3866     if (!cl)
3867     {
3868         return;
3869     }
3870     command_line_reset(cl);
3871     free_buf(&cl->buf);
3872     free_buf(&cl->residual);
3873     free(cl);
3874 }
3875 
3876 void
command_line_add(struct command_line * cl,const unsigned char * buf,const int len)3877 command_line_add(struct command_line *cl, const unsigned char *buf, const int len)
3878 {
3879     int i;
3880     for (i = 0; i < len; ++i)
3881     {
3882         if (buf[i] && char_class(buf[i], (CC_PRINT|CC_NEWLINE)))
3883         {
3884             if (!buf_write_u8(&cl->buf, buf[i]))
3885             {
3886                 buf_clear(&cl->buf);
3887             }
3888         }
3889     }
3890 }
3891 
3892 const char *
command_line_get(struct command_line * cl)3893 command_line_get(struct command_line *cl)
3894 {
3895     int i;
3896     const char *ret = NULL;
3897 
3898     i = buf_substring_len(&cl->buf, '\n');
3899     if (i >= 0)
3900     {
3901         buf_copy_excess(&cl->residual, &cl->buf, i);
3902         buf_chomp(&cl->buf);
3903         ret = BSTR(&cl->buf);
3904     }
3905     return ret;
3906 }
3907 
3908 void
command_line_next(struct command_line * cl)3909 command_line_next(struct command_line *cl)
3910 {
3911     buf_clear(&cl->buf);
3912     buf_copy(&cl->buf, &cl->residual);
3913     buf_clear(&cl->residual);
3914 }
3915 
3916 /*
3917  * struct log_entry
3918  */
3919 
3920 const char *
log_entry_print(const struct log_entry * e,unsigned int flags,struct gc_arena * gc)3921 log_entry_print(const struct log_entry *e, unsigned int flags, struct gc_arena *gc)
3922 {
3923     struct buffer out = alloc_buf_gc(ERR_BUF_SIZE, gc);
3924     if (flags & LOG_FATAL_NOTIFY)
3925     {
3926         buf_printf(&out, ">FATAL:");
3927     }
3928     if (flags & LOG_PRINT_LOG_PREFIX)
3929     {
3930         buf_printf(&out, ">LOG:");
3931     }
3932     if (flags & LOG_PRINT_ECHO_PREFIX)
3933     {
3934         buf_printf(&out, ">ECHO:");
3935     }
3936     if (flags & LOG_PRINT_STATE_PREFIX)
3937     {
3938         buf_printf(&out, ">STATE:");
3939     }
3940     if (flags & LOG_PRINT_INT_DATE)
3941     {
3942         buf_printf(&out, "%u,", (unsigned int)e->timestamp);
3943     }
3944     if (flags & LOG_PRINT_MSG_FLAGS)
3945     {
3946         buf_printf(&out, "%s,", msg_flags_string(e->u.msg_flags, gc));
3947     }
3948     if (flags & LOG_PRINT_STATE)
3949     {
3950         buf_printf(&out, "%s,", man_state_name(e->u.state));
3951     }
3952     if (flags & LOG_PRINT_INTVAL)
3953     {
3954         buf_printf(&out, "%d,", e->u.intval);
3955     }
3956     if (e->string)
3957     {
3958         buf_printf(&out, "%s", e->string);
3959     }
3960     if (flags & LOG_PRINT_LOCAL_IP)
3961     {
3962         buf_printf(&out, ",%s", print_in_addr_t(e->local_ip, IA_EMPTY_IF_UNDEF, gc));
3963     }
3964     if (flags & LOG_PRINT_REMOTE_IP)
3965     {
3966         buf_printf(&out, ",%s", (!addr_defined(&e->remote_sock) ? "," :
3967                                  print_sockaddr_ex(&e->remote_sock.addr.sa, ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)));
3968         buf_printf(&out, ",%s", (!addr_defined(&e->local_sock) ? "," :
3969                                  print_sockaddr_ex(&e->local_sock.addr.sa, ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)));
3970     }
3971     if (flags & LOG_PRINT_LOCAL_IP && !IN6_IS_ADDR_UNSPECIFIED(&e->local_ip6))
3972     {
3973         buf_printf(&out, ",%s", print_in6_addr(e->local_ip6, IA_EMPTY_IF_UNDEF, gc));
3974     }
3975     if (flags & LOG_ECHO_TO_LOG)
3976     {
3977         msg(D_MANAGEMENT, "MANAGEMENT: %s", BSTR(&out));
3978     }
3979     if (flags & LOG_PRINT_CRLF)
3980     {
3981         buf_printf(&out, "\r\n");
3982     }
3983     return BSTR(&out);
3984 }
3985 
3986 static void
log_entry_free_contents(struct log_entry * e)3987 log_entry_free_contents(struct log_entry *e)
3988 {
3989     /* Cast away constness of const char* */
3990     free((char *)e->string);
3991     CLEAR(*e);
3992 }
3993 
3994 /*
3995  * struct log_history
3996  */
3997 
3998 static inline int
log_index(const struct log_history * h,int i)3999 log_index(const struct log_history *h, int i)
4000 {
4001     return modulo_add(h->base, i, h->capacity);
4002 }
4003 
4004 static void
log_history_obj_init(struct log_history * h,int capacity)4005 log_history_obj_init(struct log_history *h, int capacity)
4006 {
4007     CLEAR(*h);
4008     h->capacity = capacity;
4009     ALLOC_ARRAY_CLEAR(h->array, struct log_entry, capacity);
4010 }
4011 
4012 struct log_history *
log_history_init(const int capacity)4013 log_history_init(const int capacity)
4014 {
4015     struct log_history *h;
4016     ASSERT(capacity > 0);
4017     ALLOC_OBJ(h, struct log_history);
4018     log_history_obj_init(h, capacity);
4019     return h;
4020 }
4021 
4022 static void
log_history_free_contents(struct log_history * h)4023 log_history_free_contents(struct log_history *h)
4024 {
4025     int i;
4026     for (i = 0; i < h->size; ++i)
4027     {
4028         log_entry_free_contents(&h->array[log_index(h, i)]);
4029     }
4030     free(h->array);
4031 }
4032 
4033 void
log_history_close(struct log_history * h)4034 log_history_close(struct log_history *h)
4035 {
4036     log_history_free_contents(h);
4037     free(h);
4038 }
4039 
4040 void
log_history_add(struct log_history * h,const struct log_entry * le)4041 log_history_add(struct log_history *h, const struct log_entry *le)
4042 {
4043     struct log_entry *e;
4044     ASSERT(h->size >= 0 && h->size <= h->capacity);
4045     if (h->size == h->capacity)
4046     {
4047         e = &h->array[h->base];
4048         log_entry_free_contents(e);
4049         h->base = log_index(h, 1);
4050     }
4051     else
4052     {
4053         e = &h->array[log_index(h, h->size)];
4054         ++h->size;
4055     }
4056 
4057     *e = *le;
4058     e->string = string_alloc(le->string, NULL);
4059 }
4060 
4061 void
log_history_resize(struct log_history * h,const int capacity)4062 log_history_resize(struct log_history *h, const int capacity)
4063 {
4064     if (capacity != h->capacity)
4065     {
4066         struct log_history newlog;
4067         int i;
4068 
4069         ASSERT(capacity > 0);
4070         log_history_obj_init(&newlog, capacity);
4071 
4072         for (i = 0; i < h->size; ++i)
4073         {
4074             log_history_add(&newlog, &h->array[log_index(h, i)]);
4075         }
4076 
4077         log_history_free_contents(h);
4078         *h = newlog;
4079     }
4080 }
4081 
4082 const struct log_entry *
log_history_ref(const struct log_history * h,const int index)4083 log_history_ref(const struct log_history *h, const int index)
4084 {
4085     if (index >= 0 && index < h->size)
4086     {
4087         return &h->array[log_index(h, (h->size - 1) - index)];
4088     }
4089     else
4090     {
4091         return NULL;
4092     }
4093 }
4094 
4095 void
management_sleep(const int n)4096 management_sleep(const int n)
4097 {
4098     if (n < 0)
4099     {
4100         return;
4101     }
4102     else if (management)
4103     {
4104         management_event_loop_n_seconds(management, n);
4105     }
4106     else if (n > 0)
4107     {
4108         sleep(n);
4109     }
4110 }
4111 
4112 #else  /* ifdef ENABLE_MANAGEMENT */
4113 
4114 void
management_sleep(const int n)4115 management_sleep(const int n)
4116 {
4117     if (n > 0)
4118     {
4119         sleep(n);
4120     }
4121 }
4122 
4123 #endif /* ENABLE_MANAGEMENT */
4124