11require 'digest/sha1'
22require 'securerandom'
3+ require 'shellwords'
34
45# @author Lee Hambley
56module SSHKit
@@ -145,7 +146,7 @@ def should_map?
145146
146147 def within ( &_block )
147148 return yield unless options [ :in ]
148- sprintf ( "cd #{ options [ :in ] } && %s" , yield )
149+ "cd #{ options [ :in ] . shellescape } && #{ yield } "
149150 end
150151
151152 def environment_hash
@@ -155,8 +156,7 @@ def environment_hash
155156 def environment_string
156157 environment_hash . collect do |key , value |
157158 key_string = key . is_a? ( Symbol ) ? key . to_s . upcase : key . to_s
158- escaped_value = value . to_s . gsub ( /"/ , '\"' )
159- %{#{ key_string } ="#{ escaped_value } "}
159+ "#{ key_string } =#{ value . shellescape } "
160160 end . join ( ' ' )
161161 end
162162
@@ -167,7 +167,7 @@ def with(&_block)
167167
168168 def user ( &_block )
169169 return yield unless options [ :user ]
170- "sudo -u #{ options [ :user ] } #{ environment_string + " " unless environment_string . empty? } -- sh -c ' #{ yield } ' "
170+ "sudo -u #{ options [ :user ] . shellescape } #{ environment_string + " " unless environment_string . empty? } -- sh -c #{ yield } "
171171 end
172172
173173 def in_background ( &_block )
@@ -177,12 +177,12 @@ def in_background(&_block)
177177
178178 def umask ( &_block )
179179 return yield unless SSHKit . config . umask
180- sprintf ( "umask #{ SSHKit . config . umask } && %s" , yield )
180+ "umask #{ SSHKit . config . umask } && #{ yield } "
181181 end
182182
183183 def group ( &_block )
184184 return yield unless options [ :group ]
185- %Q( sg #{ options [ :group ] } -c " #{ yield } ")
185+ " sg #{ options [ :group ] . shellescape } -c #{ yield } "
186186 # We could also use the so-called heredoc format perhaps:
187187 #"newgrp #{options[:group]} <<EOC \\\"%s\\\" EOC" % %Q{#{yield}}
188188 end
@@ -213,7 +213,9 @@ def with_redaction
213213
214214 def to_s
215215 if should_map?
216- [ SSHKit . config . command_map [ command . to_sym ] , *Array ( args ) ] . join ( ' ' )
216+ arguments = Array ( args )
217+ arguments = ( arguments . any? ? arguments . shelljoin : [ ] )
218+ [ SSHKit . config . command_map [ command . to_sym ] , *arguments ] . join ( " " )
217219 else
218220 command . to_s
219221 end
0 commit comments