Index: wp-includes/post.php
===================================================================
--- wp-includes/post.php	(revision 7580)
+++ wp-includes/post.php	(working copy)
@@ -460,6 +460,10 @@
 	if (!empty($exclusions))
 		$exclusions .= ')';
 
+	// orderby
+	if ( preg_match( '/.+ (ASC|DESC)/i', $orderby ) )
+		$order = ''; // orderby has its own order, so we'll use that
+
 	$query  = "SELECT DISTINCT * FROM $wpdb->posts ";
 	$query .= empty( $category ) ? '' : ", $wpdb->term_relationships, $wpdb->term_taxonomy  ";
 	$query .= empty( $meta_key ) ? '' : ", $wpdb->postmeta ";
Index: wp-includes/media.php
===================================================================
--- wp-includes/media.php	(revision 7580)
+++ wp-includes/media.php	(working copy)
@@ -339,7 +339,12 @@
 	$output = apply_filters('post_gallery', '', $attr);
 	if ( $output != '' )
 		return $output;
-		
+
+	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
+	preg_match('/(^([a-z0-9_]+( +(ASC|DESC))?(, +?|$))+|RAND\(\))/i', $attr['orderby'], $obmatches);
+	if ( !$obmatches[0] )
+		unset($attr['orderby']);
+
 	extract(shortcode_atts(array(
 		'orderby'    => 'menu_order ASC, ID ASC',
 		'id'         => $post->ID,
@@ -352,7 +357,7 @@
 
 	$id = intval($id);
 	$orderby = addslashes($orderby);
-	$attachments = get_children("post_parent=$id&post_type=attachment&post_mime_type=image&orderby=\"{$orderby}\"");
+	$attachments = get_children("post_parent=$id&post_type=attachment&post_mime_type=image&orderby={$orderby}");
 
 	if ( empty($attachments) )
 		return '';
@@ -426,7 +431,7 @@
 function adjacent_image_link($prev = true) {
 	global $post;
 	$post = get_post($post);
-	$attachments = array_values(get_children("post_parent=$post->post_parent&post_type=attachment&post_mime_type=image&orderby=\"menu_order ASC, ID ASC\""));
+	$attachments = array_values(get_children("post_parent=$post->post_parent&post_type=attachment&post_mime_type=image&orderby=menu_order ASC, ID ASC"));
 
 	foreach ( $attachments as $k => $attachment )
 		if ( $attachment->ID == $post->ID )
