3 * Support for attaching to the runtime from other processes.
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2007-2009 Novell, Inc (http://www.novell.com)
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #define DISABLE_ATTACH
18 #ifndef DISABLE_ATTACH
23 #include <sys/types.h>
24 #include <sys/socket.h>
27 #include <netinet/in.h>
35 #include <mono/metadata/assembly-internals.h>
36 #include <mono/metadata/metadata.h>
37 #include <mono/metadata/class-internals.h>
38 #include <mono/metadata/object-internals.h>
39 #include <mono/metadata/threads-types.h>
40 #include <mono/metadata/gc-internals.h>
41 #include <mono/utils/mono-threads.h>
44 #include <mono/utils/w32api.h>
47 * This module enables other processes to attach to a running mono process and
48 * load agent assemblies.
49 * Communication is done through a UNIX Domain Socket located at
50 * /tmp/mono-<USER>/.mono-<PID>.
51 * We use a simplified version of the .net remoting protocol.
52 * To increase security, and to avoid spinning up a listener thread on startup,
53 * we follow the java implementation, and only start up the attach mechanism
54 * when we receive a QUIT signal and there is a file named
55 * '.mono_attach_pid<PID>' in /tmp.
58 * - This module allows loading of arbitrary code into a running mono runtime, so
59 * it is security critical.
60 * - Security is based on controlling access to the unix file to which the unix
61 * domain socket is bound. Permissions/ownership are set such that only the owner
62 * of the process can access the socket.
63 * - As an additional measure, the socket is only created when the process receives
64 * a SIGQUIT signal, which only its owner/root can send.
65 * - The socket is kept in a directory whose ownership is checked before creating
66 * the socket. This could allow an attacker a kind of DOS attack by creating the
67 * directory with the wrong permissions/ownership. However, the only thing such
68 * an attacker could prevent is the attaching of agents to the mono runtime.
79 /*******************************************************************/
80 /* Remoting Protocol type definitions from [MS-NRBF] and [MS-NRTP] */
81 /*******************************************************************/
90 static AgentConfig config;
92 static int listen_fd, conn_fd;
94 static char *ipc_filename;
96 static char *server_uri;
98 static MonoThreadHandle *receiver_thread_handle;
100 static gboolean stop_receiver_thread;
102 static gboolean needs_to_start, started;
104 static void transport_connect (void);
106 static gsize WINAPI receiver_thread (void *arg);
108 static void transport_start_receive (void);
111 * Functions to decode protocol data
114 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
117 g_assert (*endbuf <= limit);
122 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
125 g_assert (*endbuf <= limit);
127 return (((int)buf [0]) << 0) | (((int)buf [1]) << 8) | (((int)buf [2]) << 16) | (((int)buf [3]) << 24);
131 decode_string_value (guint8 *buf, guint8 **endbuf, guint8 *limit)
138 type = decode_byte (p, &p, limit);
139 if (type == PRIM_TYPE_NULL) {
143 g_assert (type == PRIM_TYPE_STRING);
147 guint8 b = decode_byte (p, &p, limit);
155 g_assert (length < (1 << 16));
157 s = (char *)g_malloc (length + 1);
159 g_assert (p + length <= limit);
160 memcpy (s, p, length);
169 /********************************/
170 /* AGENT IMPLEMENTATION */
171 /********************************/
174 mono_attach_parse_options (char *options)
178 if (!strcmp (options, "disable"))
179 config.enabled = FALSE;
183 mono_attach_init (void)
185 config.enabled = TRUE;
191 * Start the attach mechanism if needed. This is called from a signal handler so it must be signal safe.
193 * Returns: whenever it was started.
196 mono_attach_start (void)
204 /* Check for the existence of the trigger file */
207 * We don't do anything with this file, and the only thing an attacker can do
208 * by creating it is to enable the attach mechanism if the process receives a
209 * SIGQUIT signal, which can only be sent by the owner/root.
211 snprintf (path, sizeof (path), "/tmp/.mono_attach_pid%"PRIdMAX"", (intmax_t) getpid ());
212 fd = open (path, O_RDONLY);
218 /* Act like we started */
225 * Our startup includes non signal-safe code, so ask the finalizer thread to
226 * do the actual startup.
228 needs_to_start = TRUE;
229 mono_gc_finalize_notify ();
234 /* Called by the finalizer thread when it is woken up */
236 mono_attach_maybe_start (void)
241 needs_to_start = FALSE;
243 transport_start_receive ();
250 mono_attach_cleanup (void)
255 unlink (ipc_filename);
257 stop_receiver_thread = TRUE;
259 /* This will cause receiver_thread () to break out of the read () call */
262 /* Wait for the receiver thread to exit */
263 if (receiver_thread_handle)
264 mono_thread_info_wait_one_handle (receiver_thread_handle, 0, FALSE);
268 mono_attach_load_agent (MonoDomain *domain, char *agent, char *args, MonoObject **exc)
271 MonoAssembly *agent_assembly;
275 MonoArray *main_args;
277 MonoImageOpenStatus open_status;
279 agent_assembly = mono_assembly_open_predicate (agent, FALSE, FALSE, NULL, NULL, &open_status);
280 if (!agent_assembly) {
281 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
287 * Can't use mono_jit_exec (), as it sets things which might confuse the
290 image = mono_assembly_get_image (agent_assembly);
291 entry = mono_image_get_entry_point (image);
293 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
298 method = mono_get_method_checked (image, entry, NULL, NULL, &error);
300 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (&error));
301 mono_error_cleanup (&error);
307 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, (args == NULL) ? 0 : 1, &error);
308 if (main_args == NULL) {
309 g_print ("Could not allocate main method args due to %s\n", mono_error_get_message (&error));
310 mono_error_cleanup (&error);
316 MonoString *args_str = mono_string_new_checked (domain, args, &error);
317 if (!is_ok (&error)) {
318 g_print ("Could not allocate main method arg string due to %s\n", mono_error_get_message (&error));
319 mono_error_cleanup (&error);
323 mono_array_set (main_args, MonoString*, 0, args_str);
328 mono_runtime_try_invoke (method, NULL, pa, exc, &error);
329 if (!is_ok (&error)) {
330 g_print ("The entry point method of assembly '%s' could not be executed due to %s\n", agent, mono_error_get_message (&error));
331 mono_error_cleanup (&error);
344 * Create a UNIX domain socket and bind it to a file in /tmp.
346 * SECURITY: This routine is _very_ security critical since we depend on the UNIX
347 * permissions system to prevent attackers from connecting to the socket.
352 struct sockaddr_un name;
355 char *filename, *directory;
361 if (getuid () != geteuid ()) {
362 fprintf (stderr, "attach: disabled listening on an IPC socket when running in setuid mode.\n");
366 /* Create the socket. */
367 sock = socket (PF_UNIX, SOCK_STREAM, 0);
369 perror ("attach: failed to create IPC socket");
374 * For security reasons, create a directory to hold the listening socket,
375 * since there is a race between bind () and chmod () below.
377 /* FIXME: Use TMP ? */
379 #ifdef HAVE_GETPWUID_R
380 res = getpwuid_r (getuid (), &pwbuf, buf, sizeof (buf), &pw);
382 pw = getpwuid(getuid ());
383 res = pw != NULL ? 0 : 1;
386 fprintf (stderr, "attach: getpwuid_r () failed.\n");
390 directory = g_strdup_printf ("/tmp/mono-%s", pw->pw_name);
391 res = mkdir (directory, S_IRUSR | S_IWUSR | S_IXUSR);
393 if (errno == EEXIST) {
394 /* Check type and permissions */
395 res = lstat (directory, &stat);
397 perror ("attach: lstat () failed");
400 if (!S_ISDIR (stat.st_mode)) {
401 fprintf (stderr, "attach: path '%s' is not a directory.\n", directory);
404 if (stat.st_uid != getuid ()) {
405 fprintf (stderr, "attach: directory '%s' is not owned by the current user.\n", directory);
408 if ((stat.st_mode & S_IRWXG) != 0 || (stat.st_mode & S_IRWXO) || ((stat.st_mode & S_IRWXU) != (S_IRUSR | S_IWUSR | S_IXUSR))) {
409 fprintf (stderr, "attach: directory '%s' should have protection 0700.\n", directory);
413 perror ("attach: mkdir () failed");
418 filename = g_strdup_printf ("%s/.mono-%"PRIdMAX"", directory, (intmax_t) getpid ());
421 /* Bind a name to the socket. */
422 name.sun_family = AF_UNIX;
423 strcpy (name.sun_path, filename);
425 size = (offsetof (struct sockaddr_un, sun_path)
426 + strlen (name.sun_path) + 1);
428 if (bind (sock, (struct sockaddr *) &name, size) < 0) {
429 fprintf (stderr, "attach: failed to bind IPC socket '%s': %s\n", filename, strerror (errno));
434 /* Set permissions */
435 res = chmod (filename, S_IRUSR | S_IWUSR);
437 perror ("attach: failed to set permissions on IPC socket");
443 res = listen (sock, 16);
445 fprintf (stderr, "attach: listen () failed: %s\n", strerror (errno));
451 ipc_filename = g_strdup (filename);
453 server_uri = g_strdup_printf ("unix://%s/.mono-%"PRIdMAX"?/vm", directory, (intmax_t) getpid ());
460 transport_connect (void)
468 transport_send (int fd, guint8 *data, int len)
472 stats.bytes_sent += len;
473 //printf ("X: %d\n", stats.bytes_sent);
475 res = write (fd, data, len);
477 /* FIXME: What to do here ? */
484 transport_start_receive (void)
487 MonoInternalThread *internal;
489 transport_connect ();
494 internal = mono_thread_create_internal (mono_get_root_domain (), receiver_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, &error);
495 mono_error_assert_ok (&error);
497 receiver_thread_handle = mono_threads_open_thread_handle (internal->handle);
498 g_assert (receiver_thread_handle);
502 receiver_thread (void *arg)
505 int res, content_len;
509 MonoInternalThread *internal;
511 internal = mono_thread_internal_current ();
512 MonoString *attach_str = mono_string_new_checked (mono_domain_get (), "Attach receiver", &error);
513 mono_error_assert_ok (&error);
514 mono_thread_set_name_internal (internal, attach_str, TRUE, FALSE, &error);
515 mono_error_assert_ok (&error);
516 /* Ask the runtime to not abort this thread */
517 //internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
518 /* Ask the runtime to not wait for this thread */
519 internal->state |= ThreadState_Background;
521 printf ("attach: Listening on '%s'...\n", server_uri);
524 conn_fd = accept (listen_fd, NULL, NULL);
526 /* Probably closed by mono_attach_cleanup () */
529 printf ("attach: Connected.\n");
532 char *cmd, *agent_name, *agent_args;
536 res = read (conn_fd, buffer, 6);
538 if (res == -1 && errno == EINTR)
541 if (res == -1 || stop_receiver_thread)
547 if ((strncmp ((char*)buffer, "MONO", 4) != 0) || buffer [4] != 1 || buffer [5] != 0) {
548 fprintf (stderr, "attach: message from server has unknown header.\n");
552 /* Read content length */
553 res = read (conn_fd, buffer, 4);
560 content_len = decode_int (p, &p, p_end);
562 /* Read message body */
563 body = (guint8 *)g_malloc (content_len);
564 res = read (conn_fd, body, content_len);
567 p_end = body + content_len;
569 cmd = decode_string_value (p, &p, p_end);
572 g_assert (!strcmp (cmd, "attach"));
574 agent_name = decode_string_value (p, &p, p_end);
575 agent_args = decode_string_value (p, &p, p_end);
577 printf ("attach: Loading agent '%s'.\n", agent_name);
578 mono_attach_load_agent (mono_domain_get (), agent_name, agent_args, &exc);
582 // FIXME: Send back a result
588 printf ("attach: Disconnected.\n");
590 if (stop_receiver_thread)
597 #else /* DISABLE_ATTACH */
600 mono_attach_parse_options (char *options)
605 mono_attach_init (void)
610 mono_attach_start (void)
616 mono_attach_maybe_start (void)
621 mono_attach_cleanup (void)
625 #endif /* DISABLE_ATTACH */