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)
14 #define DISABLE_ATTACH
16 #ifndef DISABLE_ATTACH
21 #include <sys/types.h>
22 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <sys/types.h>
35 #include <mono/metadata/assembly.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-internal.h>
41 #include <mono/utils/mono-threads.h>
45 * This module enables other processes to attach to a running mono process and
46 * load agent assemblies.
47 * Communication is done through a UNIX Domain Socket located at
48 * /tmp/mono-<USER>/.mono-<PID>.
49 * We use a simplified version of the .net remoting protocol.
50 * To increase security, and to avoid spinning up a listener thread on startup,
51 * we follow the java implementation, and only start up the attach mechanism
52 * when we receive a QUIT signal and there is a file named
53 * '.mono_attach_pid<PID>' in /tmp.
56 * - This module allows loading of arbitrary code into a running mono runtime, so
57 * it is security critical.
58 * - Security is based on controlling access to the unix file to which the unix
59 * domain socket is bound. Permissions/ownership are set such that only the owner
60 * of the process can access the socket.
61 * - As an additional measure, the socket is only created when the process receives
62 * a SIGQUIT signal, which only its owner/root can send.
63 * - The socket is kept in a directory whose ownership is checked before creating
64 * the socket. This could allow an attacker a kind of DOS attack by creating the
65 * directory with the wrong permissions/ownership. However, the only thing such
66 * an attacker could prevent is the attaching of agents to the mono runtime.
77 /*******************************************************************/
78 /* Remoting Protocol type definitions from [MS-NRBF] and [MS-NRTP] */
79 /*******************************************************************/
88 static AgentConfig config;
90 static int listen_fd, conn_fd;
92 static char *ipc_filename;
94 static char *server_uri;
96 static HANDLE receiver_thread_handle;
98 static gboolean stop_receiver_thread;
100 static gboolean needs_to_start, started;
102 #define agent_lock() EnterCriticalSection (&agent_mutex)
103 #define agent_unlock() LeaveCriticalSection (&agent_mutex)
104 static CRITICAL_SECTION agent_mutex;
106 static void transport_connect (void);
108 static guint32 WINAPI receiver_thread (void *arg);
110 static void transport_start_receive (void);
113 * Functions to decode protocol data
116 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
119 g_assert (*endbuf <= limit);
124 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
127 g_assert (*endbuf <= limit);
129 return (((int)buf [0]) << 0) | (((int)buf [1]) << 8) | (((int)buf [2]) << 16) | (((int)buf [3]) << 24);
133 decode_short (guint8 *buf, guint8 **endbuf, guint8 *limit)
136 g_assert (*endbuf <= limit);
138 return (((int)buf [0]) << 0) | (((int)buf [1]) << 8);
142 decode_string_value (guint8 *buf, guint8 **endbuf, guint8 *limit)
149 type = decode_byte (p, &p, limit);
150 if (type == PRIM_TYPE_NULL) {
154 g_assert (type == PRIM_TYPE_STRING);
158 guint8 b = decode_byte (p, &p, limit);
166 g_assert (length < (1 << 16));
168 s = g_malloc (length + 1);
170 g_assert (p + length <= limit);
171 memcpy (s, p, length);
180 /********************************/
181 /* AGENT IMPLEMENTATION */
182 /********************************/
185 mono_attach_parse_options (char *options)
189 if (!strcmp (options, "disable"))
190 config.enabled = FALSE;
194 mono_attach_init (void)
196 InitializeCriticalSection (&agent_mutex);
198 config.enabled = TRUE;
204 * Start the attach mechanism if needed. This is called from a signal handler so it must be signal safe.
206 * Returns: whenever it was started.
209 mono_attach_start (void)
217 /* Check for the existence of the trigger file */
220 * We don't do anything with this file, and the only thing an attacker can do
221 * by creating it is to enable the attach mechanism if the process receives a
222 * SIGQUIT signal, which can only be sent by the owner/root.
224 snprintf (path, sizeof (path), "/tmp/.mono_attach_pid%"PRIdMAX"", (intmax_t) getpid ());
225 fd = open (path, O_RDONLY);
231 /* Act like we started */
238 * Our startup includes non signal-safe code, so ask the finalizer thread to
239 * do the actual startup.
241 needs_to_start = TRUE;
242 mono_gc_finalize_notify ();
247 /* Called by the finalizer thread when it is woken up */
249 mono_attach_maybe_start (void)
254 needs_to_start = FALSE;
256 transport_start_receive ();
263 mono_attach_cleanup (void)
268 unlink (ipc_filename);
270 stop_receiver_thread = TRUE;
272 /* This will cause receiver_thread () to break out of the read () call */
275 /* Wait for the receiver thread to exit */
276 if (receiver_thread_handle)
277 WaitForSingleObjectEx (receiver_thread_handle, 0, FALSE);
281 mono_attach_load_agent (MonoDomain *domain, char *agent, char *args, MonoObject **exc)
283 MonoAssembly *agent_assembly;
287 MonoArray *main_args;
289 MonoImageOpenStatus open_status;
291 agent_assembly = mono_assembly_open (agent, &open_status);
292 if (!agent_assembly) {
293 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
299 * Can't use mono_jit_exec (), as it sets things which might confuse the
302 image = mono_assembly_get_image (agent_assembly);
303 entry = mono_image_get_entry_point (image);
305 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
310 method = mono_get_method (image, entry, NULL);
312 g_print ("The entry point method of assembly '%s' could not be loaded\n", agent);
318 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 1);
319 mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
321 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
327 mono_runtime_invoke (method, NULL, pa, exc);
335 * Create a UNIX domain socket and bind it to a file in /tmp.
337 * SECURITY: This routine is _very_ security critical since we depend on the UNIX
338 * permissions system to prevent attackers from connecting to the socket.
343 struct sockaddr_un name;
346 char *filename, *directory;
352 if (getuid () != geteuid ()) {
353 fprintf (stderr, "attach: disabled listening on an IPC socket when running in setuid mode.\n");
357 /* Create the socket. */
358 sock = socket (PF_UNIX, SOCK_STREAM, 0);
360 perror ("attach: failed to create IPC socket");
365 * For security reasons, create a directory to hold the listening socket,
366 * since there is a race between bind () and chmod () below.
368 /* FIXME: Use TMP ? */
370 #ifdef HAVE_GETPWUID_R
371 res = getpwuid_r (getuid (), &pwbuf, buf, sizeof (buf), &pw);
373 pw = getpwuid(getuid ());
374 res = pw != NULL ? 0 : 1;
377 fprintf (stderr, "attach: getpwuid_r () failed.\n");
381 directory = g_strdup_printf ("/tmp/mono-%s", pw->pw_name);
382 res = mkdir (directory, S_IRUSR | S_IWUSR | S_IXUSR);
384 if (errno == EEXIST) {
385 /* Check type and permissions */
386 res = lstat (directory, &stat);
388 perror ("attach: lstat () failed");
391 if (!S_ISDIR (stat.st_mode)) {
392 fprintf (stderr, "attach: path '%s' is not a directory.\n", directory);
395 if (stat.st_uid != getuid ()) {
396 fprintf (stderr, "attach: directory '%s' is not owned by the current user.\n", directory);
399 if ((stat.st_mode & S_IRWXG) != 0 || (stat.st_mode & S_IRWXO) || ((stat.st_mode & S_IRWXU) != (S_IRUSR | S_IWUSR | S_IXUSR))) {
400 fprintf (stderr, "attach: directory '%s' should have protection 0700.\n", directory);
404 perror ("attach: mkdir () failed");
409 filename = g_strdup_printf ("%s/.mono-%"PRIdMAX"", directory, (intmax_t) getpid ());
412 /* Bind a name to the socket. */
413 name.sun_family = AF_UNIX;
414 strcpy (name.sun_path, filename);
416 size = (offsetof (struct sockaddr_un, sun_path)
417 + strlen (name.sun_path) + 1);
419 if (bind (sock, (struct sockaddr *) &name, size) < 0) {
420 fprintf (stderr, "attach: failed to bind IPC socket '%s': %s\n", filename, strerror (errno));
425 /* Set permissions */
426 res = chmod (filename, S_IRUSR | S_IWUSR);
428 perror ("attach: failed to set permissions on IPC socket");
434 res = listen (sock, 16);
436 fprintf (stderr, "attach: listen () failed: %s\n", strerror (errno));
442 ipc_filename = g_strdup (filename);
444 server_uri = g_strdup_printf ("unix://%s/.mono-%"PRIdMAX"?/vm", directory, (intmax_t) getpid ());
451 transport_connect (void)
459 transport_send (int fd, guint8 *data, int len)
463 stats.bytes_sent += len;
464 //printf ("X: %d\n", stats.bytes_sent);
466 res = write (fd, data, len);
468 /* FIXME: What to do here ? */
475 transport_start_receive (void)
477 transport_connect ();
482 receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, 0, 0, NULL);
483 g_assert (receiver_thread_handle);
486 static guint32 WINAPI
487 receiver_thread (void *arg)
489 int res, content_len;
494 printf ("attach: Listening on '%s'...\n", server_uri);
497 conn_fd = accept (listen_fd, NULL, NULL);
499 /* Probably closed by mono_attach_cleanup () */
502 printf ("attach: Connected.\n");
504 mono_thread_attach (mono_get_root_domain ());
505 /* Ask the runtime to not abort this thread */
506 //mono_thread_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
507 /* Ask the runtime to not wait for this thread */
508 mono_thread_internal_current ()->state |= ThreadState_Background;
511 char *cmd, *agent_name, *agent_args;
515 res = read (conn_fd, buffer, 6);
517 if (res == -1 && errno == EINTR)
520 if (res == -1 || stop_receiver_thread)
526 if ((strncmp ((char*)buffer, "MONO", 4) != 0) || buffer [4] != 1 || buffer [5] != 0) {
527 fprintf (stderr, "attach: message from server has unknown header.\n");
531 /* Read content length */
532 res = read (conn_fd, buffer, 4);
539 content_len = decode_int (p, &p, p_end);
541 /* Read message body */
542 body = g_malloc (content_len);
543 res = read (conn_fd, body, content_len);
546 p_end = body + content_len;
548 cmd = decode_string_value (p, &p, p_end);
551 g_assert (!strcmp (cmd, "attach"));
553 agent_name = decode_string_value (p, &p, p_end);
554 agent_args = decode_string_value (p, &p, p_end);
556 printf ("attach: Loading agent '%s'.\n", agent_name);
557 mono_attach_load_agent (mono_domain_get (), agent_name, agent_args, &exc);
561 // FIXME: Send back a result
567 printf ("attach: Disconnected.\n");
569 if (stop_receiver_thread)
576 #else /* DISABLE_ATTACH */
579 mono_attach_parse_options (char *options)
584 mono_attach_init (void)
589 mono_attach_start (void)
595 mono_attach_maybe_start (void)
600 mono_attach_cleanup (void)
604 #endif /* DISABLE_ATTACH */