Index: wp-includes/post.php
===================================================================
--- wp-includes/post.php	(revision 7587)
+++ 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 7587)
+++ wp-includes/media.php	(working copy)
@@ -339,7 +339,14 @@
 	$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
+	if ( isset( $attr['orderby'] ) ) {
+		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
+		if ( !$attr['orderby'] )
+			unset( $attr['orderby'] );
+	}
+
 	extract(shortcode_atts(array(
 		'orderby'    => 'menu_order ASC, ID ASC',
 		'id'         => $post->ID,
@@ -351,8 +358,7 @@
 	), $attr));
 
 	$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 +432,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 )
Index: wp-includes/formatting.php
===================================================================
--- wp-includes/formatting.php	(revision 7587)
+++ wp-includes/formatting.php	(working copy)
@@ -366,6 +366,15 @@
 	return $title;
 }
 
+// ensures a string is a valid SQL order by clause like: post_name ASC, ID DESC
+// accepts one or more columns, with or without ASC/DESC, and also accepts RAND()
+function sanitize_sql_orderby( $orderby ){
+	preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
+	if ( !$obmatches )
+		return false;
+	return $orderby;
+}
+
 function convert_chars($content, $deprecated = '') {
 	// Translation of invalid Unicode references range to valid range
 	$wp_htmltranswinuni = array(
