2 * attach.c: Support for attaching to the runtime from other processes.
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2007-2009 Novell, Inc (http://www.novell.com)
8 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #define DISABLE_ATTACH
17 #ifndef DISABLE_ATTACH
22 #include <sys/types.h>
23 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <sys/types.h>
36 #include <mono/metadata/assembly.h>
37 #include <mono/metadata/metadata.h>
38 #include <mono/metadata/class-internals.h>
39 #include <mono/metadata/object-internals.h>
40 #include <mono/metadata/threads-types.h>
41 #include <mono/metadata/gc-internals.h>
42 #include <mono/utils/mono-threads.h>
46 * This module enables other processes to attach to a running mono process and
47 * load agent assemblies.
48 * Communication is done through a UNIX Domain Socket located at
49 * /tmp/mono-<USER>/.mono-<PID>.
50 * We use a simplified version of the .net remoting protocol.
51 * To increase security, and to avoid spinning up a listener thread on startup,
52 * we follow the java implementation, and only start up the attach mechanism
53 * when we receive a QUIT signal and there is a file named
54 * '.mono_attach_pid<PID>' in /tmp.
57 * - This module allows loading of arbitrary code into a running mono runtime, so
58 * it is security critical.
59 * - Security is based on controlling access to the unix file to which the unix
60 * domain socket is bound. Permissions/ownership are set such that only the owner
61 * of the process can access the socket.
62 * - As an additional measure, the socket is only created when the process receives
63 * a SIGQUIT signal, which only its owner/root can send.
64 * - The socket is kept in a directory whose ownership is checked before creating
65 * the socket. This could allow an attacker a kind of DOS attack by creating the
66 * directory with the wrong permissions/ownership. However, the only thing such
67 * an attacker could prevent is the attaching of agents to the mono runtime.
78 /*******************************************************************/
79 /* Remoting Protocol type definitions from [MS-NRBF] and [MS-NRTP] */
80 /*******************************************************************/
89 static AgentConfig config;
91 static int listen_fd, conn_fd;
93 static char *ipc_filename;
95 static char *server_uri;
97 static HANDLE receiver_thread_handle;
99 static gboolean stop_receiver_thread;
101 static gboolean needs_to_start, started;
103 static void transport_connect (void);
105 static guint32 WINAPI receiver_thread (void *arg);
107 static void transport_start_receive (void);
110 * Functions to decode protocol data
113 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
116 g_assert (*endbuf <= limit);
121 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
124 g_assert (*endbuf <= limit);
126 return (((int)buf [0]) << 0) | (((int)buf [1]) << 8) | (((int)buf [2]) << 16) | (((int)buf [3]) << 24);
130 decode_string_value (guint8 *buf, guint8 **endbuf, guint8 *limit)
137 type = decode_byte (p, &p, limit);
138 if (type == PRIM_TYPE_NULL) {
142 g_assert (type == PRIM_TYPE_STRING);
146 guint8 b = decode_byte (p, &p, limit);
154 g_assert (length < (1 << 16));
156 s = (char *)g_malloc (length + 1);
158 g_assert (p + length <= limit);
159 memcpy (s, p, length);
168 /********************************/
169 /* AGENT IMPLEMENTATION */
170 /********************************/
173 mono_attach_parse_options (char *options)
177 if (!strcmp (options, "disable"))
178 config.enabled = FALSE;
182 mono_attach_init (void)
184 config.enabled = TRUE;
190 * Start the attach mechanism if needed. This is called from a signal handler so it must be signal safe.
192 * Returns: whenever it was started.
195 mono_attach_start (void)
203 /* Check for the existence of the trigger file */
206 * We don't do anything with this file, and the only thing an attacker can do
207 * by creating it is to enable the attach mechanism if the process receives a
208 * SIGQUIT signal, which can only be sent by the owner/root.
210 snprintf (path, sizeof (path), "/tmp/.mono_attach_pid%"PRIdMAX"", (intmax_t) getpid ());
211 fd = open (path, O_RDONLY);
217 /* Act like we started */
224 * Our startup includes non signal-safe code, so ask the finalizer thread to
225 * do the actual startup.
227 needs_to_start = TRUE;
228 mono_gc_finalize_notify ();
233 /* Called by the finalizer thread when it is woken up */
235 mono_attach_maybe_start (void)
240 needs_to_start = FALSE;
242 transport_start_receive ();
249 mono_attach_cleanup (void)
254 unlink (ipc_filename);
256 stop_receiver_thread = TRUE;
258 /* This will cause receiver_thread () to break out of the read () call */
261 /* Wait for the receiver thread to exit */
262 if (receiver_thread_handle)
263 WaitForSingleObjectEx (receiver_thread_handle, 0, FALSE);
267 mono_attach_load_agent (MonoDomain *domain, char *agent, char *args, MonoObject **exc)
270 MonoAssembly *agent_assembly;
274 MonoArray *main_args;
276 MonoImageOpenStatus open_status;
278 agent_assembly = mono_assembly_open (agent, &open_status);
279 if (!agent_assembly) {
280 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
286 * Can't use mono_jit_exec (), as it sets things which might confuse the
289 image = mono_assembly_get_image (agent_assembly);
290 entry = mono_image_get_entry_point (image);
292 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
297 method = mono_get_method_checked (image, entry, NULL, NULL, &error);
299 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (&error));
300 mono_error_cleanup (&error);
306 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, (args == NULL) ? 0 : 1, &error);
307 if (main_args == NULL) {
308 g_print ("Could not allocate main method args due to %s\n", mono_error_get_message (&error));
309 mono_error_cleanup (&error);
315 mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
320 mono_runtime_try_invoke (method, NULL, pa, exc, &error);
321 if (!is_ok (&error)) {
322 g_print ("The entry point method of assembly '%s' could not be executed due to %s\n", agent, mono_error_get_message (&error));
323 mono_error_cleanup (&error);
336 * Create a UNIX domain socket and bind it to a file in /tmp.
338 * SECURITY: This routine is _very_ security critical since we depend on the UNIX
339 * permissions system to prevent attackers from connecting to the socket.
344 struct sockaddr_un name;
347 char *filename, *directory;
353 if (getuid () != geteuid ()) {
354 fprintf (stderr, "attach: disabled listening on an IPC socket when running in setuid mode.\n");
358 /* Create the socket. */
359 sock = socket (PF_UNIX, SOCK_STREAM, 0);
361 perror ("attach: failed to create IPC socket");
366 * For security reasons, create a directory to hold the listening socket,
367 * since there is a race between bind () and chmod () below.
369 /* FIXME: Use TMP ? */
371 #ifdef HAVE_GETPWUID_R
372 res = getpwuid_r (getuid (), &pwbuf, buf, sizeof (buf), &pw);
374 pw = getpwuid(getuid ());
375 res = pw != NULL ? 0 : 1;
378 fprintf (stderr, "attach: getpwuid_r () failed.\n");
382 directory = g_strdup_printf ("/tmp/mono-%s", pw->pw_name);
383 res = mkdir (directory, S_IRUSR | S_IWUSR | S_IXUSR);
385 if (errno == EEXIST) {
386 /* Check type and permissions */
387 res = lstat (directory, &stat);
389 perror ("attach: lstat () failed");
392 if (!S_ISDIR (stat.st_mode)) {
393 fprintf (stderr, "attach: path '%s' is not a directory.\n", directory);
396 if (stat.st_uid != getuid ()) {
397 fprintf (stderr, "attach: directory '%s' is not owned by the current user.\n", directory);
400 if ((stat.st_mode & S_IRWXG) != 0 || (stat.st_mode & S_IRWXO) || ((stat.st_mode & S_IRWXU) != (S_IRUSR | S_IWUSR | S_IXUSR))) {
401 fprintf (stderr, "attach: directory '%s' should have protection 0700.\n", directory);
405 perror ("attach: mkdir () failed");
410 filename = g_strdup_printf ("%s/.mono-%"PRIdMAX"", directory, (intmax_t) getpid ());
413 /* Bind a name to the socket. */
414 name.sun_family = AF_UNIX;
415 strcpy (name.sun_path, filename);
417 size = (offsetof (struct sockaddr_un, sun_path)
418 + strlen (name.sun_path) + 1);
420 if (bind (sock, (struct sockaddr *) &name, size) < 0) {
421 fprintf (stderr, "attach: failed to bind IPC socket '%s': %s\n", filename, strerror (errno));
426 /* Set permissions */
427 res = chmod (filename, S_IRUSR | S_IWUSR);
429 perror ("attach: failed to set permissions on IPC socket");
435 res = listen (sock, 16);
437 fprintf (stderr, "attach: listen () failed: %s\n", strerror (errno));
443 ipc_filename = g_strdup (filename);
445 server_uri = g_strdup_printf ("unix://%s/.mono-%"PRIdMAX"?/vm", directory, (intmax_t) getpid ());
452 transport_connect (void)
460 transport_send (int fd, guint8 *data, int len)
464 stats.bytes_sent += len;
465 //printf ("X: %d\n", stats.bytes_sent);
467 res = write (fd, data, len);
469 /* FIXME: What to do here ? */
476 transport_start_receive (void)
480 transport_connect ();
487 tp.creation_flags = 0;
488 receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, &tp, NULL);
489 g_assert (receiver_thread_handle);
492 static guint32 WINAPI
493 receiver_thread (void *arg)
496 int res, content_len;
501 mono_native_thread_set_name (mono_native_thread_id_get (), "Attach receiver");
503 printf ("attach: Listening on '%s'...\n", server_uri);
506 conn_fd = accept (listen_fd, NULL, NULL);
508 /* Probably closed by mono_attach_cleanup () */
511 printf ("attach: Connected.\n");
513 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
514 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Attach receiver"), TRUE, &error);
515 mono_error_assert_ok (&error);
516 /* Ask the runtime to not abort this thread */
517 //mono_thread_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
518 /* Ask the runtime to not wait for this thread */
519 thread->internal_thread->state |= ThreadState_Background;
522 char *cmd, *agent_name, *agent_args;
526 res = read (conn_fd, buffer, 6);
528 if (res == -1 && errno == EINTR)
531 if (res == -1 || stop_receiver_thread)
537 if ((strncmp ((char*)buffer, "MONO", 4) != 0) || buffer [4] != 1 || buffer [5] != 0) {
538 fprintf (stderr, "attach: message from server has unknown header.\n");
542 /* Read content length */
543 res = read (conn_fd, buffer, 4);
550 content_len = decode_int (p, &p, p_end);
552 /* Read message body */
553 body = (guint8 *)g_malloc (content_len);
554 res = read (conn_fd, body, content_len);
557 p_end = body + content_len;
559 cmd = decode_string_value (p, &p, p_end);
562 g_assert (!strcmp (cmd, "attach"));
564 agent_name = decode_string_value (p, &p, p_end);
565 agent_args = decode_string_value (p, &p, p_end);
567 printf ("attach: Loading agent '%s'.\n", agent_name);
568 mono_attach_load_agent (mono_domain_get (), agent_name, agent_args, &exc);
572 // FIXME: Send back a result
578 printf ("attach: Disconnected.\n");
580 if (stop_receiver_thread)
587 #else /* DISABLE_ATTACH */
590 mono_attach_parse_options (char *options)
595 mono_attach_init (void)
600 mono_attach_start (void)
606 mono_attach_maybe_start (void)
611 mono_attach_cleanup (void)
615 #endif /* DISABLE_ATTACH */