Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 46 total  RSS 

Post a form or upload a file with Curb

Source: Curb - libcurl bindings for ruby [rubyforge.org]
   1  
   2  # HTTP POST form:
   3  
   4    c = Curl::Easy.http_post("http://my.rails.box/thing/create",
   5                             Curl::PostField.content('thing[name]', 'box',
   6                             Curl::PostField.content('thing[type]', 'storage')
   7  
   8  # HTTP POST file upload:
   9  
  10    c = Curl::Easy.new("http://my.rails.box/files/upload")
  11    c.multipart_form_post = true
  12    c.http_post(Curl::PostField.file('myfile.rb'))

Find out the latest trends on Twitter

   1  require 'httparty'
   2  
   3  class Twitter
   4    include HTTParty
   5  end
   6  
   7  trends = Twitter.get('http://search.twitter.com/trends.json')['trends']
   8  trends.each do |subject|
   9    puts subject['name'] + ' ' + subject['url']
  10  end


output:
Android http://search.twitter.com/search?q=Android
T-Mobile G1 http://search.twitter.com/search?q=T-Mobile+G1
Sarah Palin http://search.twitter.com/search?q=Sarah+Palin
McCain http://search.twitter.com/search?q=McCain
Heroes http://search.twitter.com/search?q=Heroes
Obama http://search.twitter.com/search?q=Obama
iPhone http://search.twitter.com/search?q=iPhone
Apple http://search.twitter.com/search?q=Apple
AT&T http://search.twitter.com/search?q=AT%26T
Clay Aiken http://search.twitter.com/search?q=Clay+Aiken

References:

- Twitter API Wiki / Search API Documentation [twitter.com]
- Make HTTP fun with HTTParty [dzone.com]

List HTTP Status Codes in Rails

If you follow the Rails way of RESTful controllers you should familiarize yourself with all the return status codes available in the HTTP protocol.

The following is a handy list, like "rake routes", for listing out all the HTTP codes that you can return in your controller logic.

   1  
   2  desc 'Lists ActionController::StatusCodes::STATUS_CODES like routes'
   3  task :status_codes => :environment do
   4    puts "Status - Name"
   5    ActionController::StatusCodes::STATUS_CODES.to_a.sort.each { |code, message| 
   6      puts "#{code}    - #{message.gsub(/ /, "").underscore.to_sym}"
   7    } if ActionController::StatusCodes.constants.include?('STATUS_CODES')
   8  end

Seamlessly return a string from http or https feeds

// This class uses URI module to detect regular or secure links, and returns the response as a string, in my case to pass onto a feed parser like simple-rss. I'm working on a simple http authentication addon.

   1  
   2  #beef.
   3  require 'net/http'
   4  require 'net/https'
   5  require 'simple-rss'
   6  
   7  class SeamlessFeed
   8    def initialize(url,user=nil,password=nil)
   9      @url = URI.parse(url)
  10    end
  11  
  12    def output
  13      if self.is_secure?
  14        http = Net::HTTP.new(@url.host, 443)
  15        http.use_ssl = true
  16        http.start do |http|
  17          request = Net::HTTP::Get.new(@url.path)
  18          @response = http.request(request)
  19          @response.value
  20        end
  21      else
  22        @response = Net::HTTP.get_response(@url) #Why can't they all be like this, eh?
  23      end
  24      return @response.body
  25    end
  26  
  27    def is_readable?
  28      feed = SimpleRSS.parse(self.output)
  29      return true unless feed.channel.items.size < 1
  30    rescue SimpleRSSError
  31      return false
  32    end
  33  
  34  protected
  35    def is_secure?
  36      @url.scheme == 'https'
  37    end
  38  end

Creating a bucket in Amazon S3 through an irb session

1) Log into an irb session, and enter your S3 login details.
   1  
   2  require 'rubygems'
   3  require 'aws/s3'
   4  
   5    AWS::S3::Base.establish_connection!(
   6      :access_key_id     => 'REPLACE_ME',
   7      :secret_access_key => 'REPLACE_ME'
   8    )

output:
=> #<AWS::S3::Connection:0xb75e0594 @http=#<Net::HTTP s3.amazonaws.com:80 open=false>, @secret_access_key="", @options={:server=>"s3.amazonaws.com", :access_key_id=>"", :port=>80, :secret_access_key=>"", :persistent=>true}, @access_key_id="19S45GYAGWK8DC2B8VG2">

2) Browse the existing buckets.
   1  AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

3) Browse the buckets in a programmatical way.
   1  AWS::S3::Service.buckets.each {|b| puts b.name}

output:
ogg.twitteraudio.com
t1000
t2000


4) Add a new bucket called t3000.
   1  AWS::S3::Bucket.create('t3000')

output:
=> true

5) Observe adding the bucket again doesn't cause an error.
   1  AWS::S3::Bucket.create('t3000')

output:
=> true

6) View the buckets again.
   1  AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

Note: You would expect t3000 to be in there however it didn't appear possibly because of the bucket permissions.

7) Let's then look for bucket t3000.
   1  t3000 = AWS::S3::Bucket.find('t3000')

output:
=> #<AWS::S3::Bucket:0xb76df724 @object_cache=[], @attributes={"prefix"=>nil, "name"=>"t3000", "marker"=>nil, "max_keys"=>1000, "is_truncated"=>false, "xmlns"=>"http://s3.amazonaws.com/doc/2006-03-01/"}>

8) Now that we've found the bucket let's upload a text file called works.txt.
   1  file = "works.txt"

output:
=> "works.txt"
   1  AWS::S3::S3Object.store(file, open(file), 't3000', :access => :public_read)

output:
=> #<AWS::S3::S3Object::Response:0x-608926458 200 OK>

9) Setting the file access to :public_read allows us to view the file from the http location http://t3000.s3.amazonaws.com/works.txt

References:
http://amazon.rubyforge.org/
upload_to_s3 - Ruby S3 upload client [dzone.com]

*update: 14:30 30 April 2008 *
I didn't use Bucket.objects(:reload) which is the reason why the bucket t3000 didn't show up with the statement Service.buckets

Reference: spatten design - Amazon S3, Ruby and Rails slides [spattendesign.com]

Redirect a URL with Ruby CGI

   1  
   2  #!/usr/bin/ruby
   3  
   4  require 'cgi'
   5  
   6  cgi = CGI.new
   7  print cgi.header({'Status' => '302 Moved', 'location' =>  'http://www.wired.com'})

or
   1  
   2  url = 'http://www.wired.com/'
   3  print cgi.header({'status'=>'REDIRECT', 'Location'=>url})


References:
RE: cgi redirect [nagaokaut.ac.jp]
Ruby/CGI - assari [mokehehe.com]
HTTP/1.1: Status Code Definitions [w3.org]

https://hosted67.renlearn.com/77571/HomeConnect/Login.aspx

// description of your code here

   1  
   2  // insert code here..

ProjectX client-side code

This Ruby code uses a unified XML format to create a password record on a web server. It's intended to be run as a batch file which gets called from another Ruby application called maintain_projectx which gets called from a cronjob.

In this example the password is stored on the server not for authentication but simply to provide a reminder service in the event the user forgets it.

   1  
   2  require 'net/http'
   3  require 'rexml/document'
   4  include REXML
   5  
   6  class ProjectXClient
   7    attr :doc
   8    def initialize(raw_url)
   9      url = URI.escape(raw_url)
  10      xml_data = Net::HTTP.get_response(URI.parse(url)).body
  11      @doc = Document.new(xml_data)
  12    end
  13    
  14  end
  15  
  16  if __FILE__ == $0
  17  
  18    xml_project = <<PROJECT
  19    <project name='password'>
  20      <method name='create'>
  21        <params>
  22          <param var='password' val='p6789c'/>
  23          <param var='title' val='hotmail'/>
  24        </params>
  25      </method>
  26    </project>
  27  PROJECT
  28    
  29    pxc = ProjectXClient.new("http://yourdomain.com/p/projectx.cgi?xml_project=" + xml_project)
  30    doc = pxc.doc
  31    puts doc
  32      
  33  end
  34  

output -what's returned from the server is an XML response containing a result. The result echos the method executed and the output from that method, which in this instance is the xml record node 'entry'.
   1  
   2  <result method='rtn_create'>
   3    <append id='19367'>
   4      <entry id='19367'>
   5        <password>p6789c</password>
   6        <title>hotmail</title>
   7        <description/>
   8      </entry>
   9    </append>
  10  </result>
  11  

Getting Started With WWW::Mechanize

This Ruby code uses WWW:mechanize to act like a web browser.

   1  
   2   require 'rubygems'
   3   require 'mechanize'
   4  
   5   agent = WWW::Mechanize.new
   6   page = agent.get('http://google.com/')


Refer to the documentation at http://mechanize.rubyforge.org/mechanize/. Then gem install mechanize, and try running the code in an irb session.

output (extract):
   1  
   2  => #<WWW::Mechanize::Page
   3   {url #<URI::HTTP:0xfdbbbb286 URL:http://www.google.com/>}
   4   {meta}
   5   {title "Google"}
   6   {iframes}
   7   {frames}
   8   {links
   9    #<WWW::Mechanize::Page::Link
  10     "Images"
  11     "http://images.google.com/imghp?hl=en&tab=wi">
  12    #<WWW::Mechanize::Page::Link
  13     "Maps"
  14     "http://maps.google.com/maps?hl=en&tab=wl">
  15    #<WWW::Mechanize::Page::Link
  16     "News"
  17     "http://news.google.com/nwshp?hl=en&tab=wn">
  18    #<WWW::Mechanize::Page::Link
  19     "Shopping"
  20     "http://www.google.com/prdhp?hl=en&tab=wf">
  21    #<WWW::Mechanize::Page::Link
  22     "Gmail"
  23     "http://mail.google.com/mail/?hl=en&tab=wm">

bScan - Simple Web Aplications Scanner

// Web application scanner (ex: phpBB, myCMS, myBlog, mySite etc..) - Only in PHP !
// Find XSS, sql injection, remote file inclusion

   1  
   2  #####################################################################################
   3  #	Black_H  / Nooz -- 30:01:07 
   4  #	Bl4ck.H<>gmail<>com
   5  #
   6  
   7  class BScan
   8  
   9  #####################################################################################
  10  #	Regex
  11  #
  12  
  13  @@space    = '([[:space:]]*)'
  14  
  15  @@userdat  = '('
  16  @@userdat += '(\$_SERVER\[([\'\"]*)HTTP_)|'
  17  @@userdat += '(\$_GET)|'
  18  @@userdat += '(\$_POST)|'
  19  @@userdat += '(\$_COOKIE)|'
  20  @@userdat += '(\$_REQUEST)|'
  21  @@userdat += '(\$_FILES)|'
  22  @@userdat += '(\$_ENV)|'
  23  @@userdat += '(\$_HTTP_COOKIE_VARS)|'
  24  @@userdat += '(\$_HTTP_ENV_VARS)|'
  25  @@userdat += '(\$_HTTP_GET_VARS)|'
  26  @@userdat += '(\$_HTTP_POST_FILES)|'
  27  @@userdat += '(\$_HTTP_POST_VARS)|'
  28  @@userdat += '(\$_HTTP_SERVER_VARS\[([\'\"]*)HTTP_)'
  29  @@userdat += ')'
  30  
  31  @@regex = Hash.new
  32  @@regex = 
  33  	{'TYPE' => 'vars overwrite','LEVEL' => '2','REGEX' => /extract#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  34  	{'TYPE' => 'vars overwrite','LEVEL' => '2','REGEX' => /import_request_variables#{@@space}\((.*)\)/i},
  35  	{'TYPE' => 'fopen vuln','LEVEL' => '3','REGEX' => /fopen#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  36  	{'TYPE' => 'copy vuln','LEVEL' => '3','REGEX' => /copy#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  37  	{'TYPE' => 'fwrite vuln','LEVEL' => '3','REGEX' => /fwrite#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  38  	{'TYPE' => 'sql injection','LEVEL' => '2','REGEX' => /(mysql_query|mssql_query|mysqli_query)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  39  	{'TYPE' => 'crlf injection','LEVEL' => '1','REGEX' => /mail#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  40  	{'TYPE' => 'cross site scripting','LEVEL' => '1','REGEX' => /\<\?\=#{@@space}(.*)#{@@userdat}/i},
  41  	{'TYPE' => 'cross site scripting','LEVEL' => '1','REGEX' => /(print|echo|print_r|var_dump)#{@@space}(|\(|\")(.*)#{@@userdat}/i},
  42  	{'TYPE' => 'php code execution','LEVEL' => '3','REGEX' => /eval#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  43  	{'TYPE' => 'php code execution','LEVEL' => '3','REGEX' => /file_put_contents#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  44  	{'TYPE' => 'variable attribution', 'LEVEL' => '2','REGEX' => /(.*)\$#{@@userdat}(.*)/i},
  45  	{'TYPE' => 'chmod affectation','LEVEL' => '1','REGEX' => /chmod#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  46  	{'TYPE' => 'file disclosure','LEVEL' => '2','REGEX' => /(readfile|file_get_contents|file)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  47  	{'TYPE' => 'file disclosure','LEVEL' => '2','REGEX' => /(show_source|highlight_file)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  48  	{'TYPE' => 'bzopen vuln','LEVEL' => '2','REGEX' => /bzopen#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  49  	{'TYPE' => 'file deletion','LEVEL' => '2','REGEX' => /(rmdir|unlink|delete)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  50  	{'TYPE' => 'command execution','LEVEL' => '3','REGEX' => /(exec|system|passthru|shell_exec|proc_open|pcntl_exec)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  51  	{'TYPE' => 'buffer overflow','LEVEL' => '3','REGEX' => /(confirm_phpdoc_compiled|mssql_pconnect|mssql_connect|crack_opendict|snmpget|ibase_connect)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  52  	{'TYPE' => 'ip falsification','LEVEL' => '1','REGEX' => /(.*)(HTTP_CLIENT_IP|HTTP_X_FORWARDED_FOR|HTTP_PC_REMOTE_ADDR)(.*)/i},
  53  	{'TYPE' => 'putenv vuln','LEVEL' => '2','REGEX' => /putenv#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  54  	{'TYPE' => 'full path disclosure','LEVEL' => '1','REGEX' => /(htmlentities|htmlspecialchars)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  55  	{'TYPE' => 'magic_quotes_gpc bypass','LEVEL' => '1','REGEX' => /(stripslashes|urldecode)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
  56  	{'TYPE' => 'file inclusion','LEVEL' => '3','REGEX' => /(include|include_once|require|require_once)#{@@space}(|\(|\")(.*)#{@@userdat}/i}
  57  
  58  #####################################################################################
  59  #	Main
  60  #
  61  
  62    def initialize()
  63  
  64  	################
  65  	#	Usage
  66  
  67  if (ARGV.length < 4)
  68  puts  '
  69   ---------------------------------------------------------------------
  70  |             Credits: Black_H <bl4ck.h@gmail.com>                    |
  71  |                 URL: Lemon-Inside.sup.fr                            |
  72  |                Note: Premier code Ruby                              |
  73   ---------------------------------------------------------------------
  74  
  75   ---------------------------------------------------------------------
  76  |   Usage:  scan.rb -d <Dossier> -i <Save.html>                       |
  77  |   Ex:  scan.rb -d ./ -i output.html                                 |
  78   ---------------------------------------------------------------------		
  79   '
  80   end
  81   
  82  	################
  83  	#	Options & Vars
  84  	
  85  	@@scan_alldir =  self.options('d')
  86  	@@out_file =  self.options('i')
  87  	
  88  	@@ban = [".", "..", "scan.rb", @@out_file.to_s]
  89  
  90  	@@scan_buffer = Array.new
  91  	
  92  	################
  93  	#	Options Error ?
  94  	
  95  	if (@@scan_alldir != false and @@scan_alldir.empty? == false)
  96  	self.dscan(@@scan_alldir)
  97  	self.output(@@scan_buffer)
  98  	@@scan_buffer = ''
  99  	end
 100  
 101  
 102  	
 103  
 104    end
 105  
 106  #####################################################################################
 107  #	Dir Scan 
 108  #
 109    
 110    def dscan(dir)
 111        
 112  	d = Dir.open(dir.to_s)
 113  	d = d.sort - @@ban
 114  	
 115        d.each { |fichier|
 116  
 117        case File.ftype(dir+fichier)
 118          when "directory"
 119            self.dscan(dir + fichier + "/")
 120          when "file"
 121  		  puts  'Scan => ' + dir + fichier 
 122            self.fscan(dir + fichier)
 123        end
 124  
 125  	  }
 126    end
 127  
 128  #####################################################################################
 129  #	File Scan 
 130  #
 131    
 132    def fscan(file)
 133  
 134  	fichier = File.readlines(file)
 135  	i = 1
 136  
 137  	fichier.each { |line|
 138  						
 139  		@@regex.each  { |info|
 140  			
 141  			test = (line  =~ info['REGEX']) 
 142  		
 143  				if (test) 
 144  			
 145  				@@scan_buffer += ['FILE' => file, 'LINE' => i.to_s, 'MATCH' => line, 'LEVEL' => info['LEVEL'], 'TYPE' => info['TYPE']]
 146  				#	5 , 1 , 3 , 4 , 2
 147  				next @@scan_buffer
 148  				end
 149  		}
 150  
 151  	i += 1
 152    	} 
 153  	
 154    end
 155  
 156  #####################################################################################
 157  #	Output buffer
 158  #
 159    
 160    def output(buffer)
 161    
 162  	@html_hmodel = '<html>'
 163  	@html_hmodel += '<style type="text/css">'
 164  	@html_hmodel += '<!--'
 165  	@html_hmodel += '.level0 {background-color: #CCCCCC;}'
 166  	@html_hmodel += '.level1 {background-color: #33FF66;}'
 167  	@html_hmodel += '.level2 {background-color: #FFFF33;}'
 168  	@html_hmodel += '.level3 {background-color: #FF0000;}'
 169  	@html_hmodel += '--></style><body><h1>BScan v1.0</h1><pre>'
 170  
 171  	code = @html_hmodel
 172  	
 173  	buffer.each { |infos|
 174  	
 175  	keys = infos.keys
 176  	code += "<span class='level" + infos["LEVEL"] + "'>" + keys[1].to_s + ' : ' + infos["TYPE"] + '</span><br />'
 177  	code += "<span class='" + infos["LEVEL"] + "'>" + keys[3].to_s + ' : ' + infos["LEVEL"] + '</span><br />'
 178  	code += "<span class='" + infos["LEVEL"] + "'>" + keys[4].to_s + ' : ' + infos["FILE"] + '</span><br />'
 179  	code += "<span class='" + infos["LEVEL"] + "'>" + keys[0].to_s + ' : ' + infos["LINE"] + '</span><br />'
 180  	code += "<span class='" + infos["LEVEL"] + "'>" + keys[2].to_s + ' : ' + infos["MATCH"] + '</span><br />'
 181  	
 182  
 183  	}
 184  		code += "</pre></body></html>"
 185  		fhtml = File.open(@@out_file.to_s, "w")
 186  		fhtml.write code
 187  		code = ''
 188  
 189  	
 190    end
 191  #####################################################################################
 192  #	Parse & Get Options
 193  #
 194   
 195    def options(param)
 196    
 197  	i = 0
 198  		ARGV.each  { |valeur|
 199  		
 200      		if (valeur == '-' + param.to_s)
 201  				return ARGV[i+1]
 202  			elseif (valeur != '-' + param.to_s)
 203  				return false
 204  			end
 205  		i += 1
 206  		}
 207  		
 208  	end
 209    
 210  end
 211  
 212  scan = BScan.new
 213  
« Newer Snippets
Older Snippets »
Showing 1-10 of 46 total  RSS