rubyntlm-0.3.4/0000755000004100000410000000000012204651732013424 5ustar www-datawww-datarubyntlm-0.3.4/.travis.yml0000644000004100000410000000017212204651732015535 0ustar www-datawww-datalanguage: ruby rvm: - 1.9.3 - 1.9.2 - 1.8.7 - 2.0.0 - rbx-19mode - rbx-18mode - ruby-head - jruby-19mode rubyntlm-0.3.4/examples/0000755000004100000410000000000012204651732015242 5ustar www-datawww-datarubyntlm-0.3.4/examples/smtp.rb0000644000004100000410000000400412204651732016550 0ustar www-datawww-data# $Id: smtp.rb,v 1.2 2006/10/05 01:36:52 koheik Exp $ require 'socket' $:.unshift(File.dirname(__FILE__) + '/../lib') require 'net/ntlm' $user = nil $passwd = nil $host = "localhost" $port = 25 $debug = true def readline(f) (l = f.gets).chomp! puts "srv> " + l if $debug l end def writeline(f, str) puts "cli> " + str if $debug f.print str + "\r\n" end def main s = TCPSocket.new($host, $port) # greetings readline s writeline s, "EHLO #{$host}" while(line = readline(s)) login = true if /^250-AUTH=LOGIN/ =~ line ntlm = true if /^250-AUTH.+NTLM.*/ =~ line break if /^250 OK/ =~ line end unless ntlm and login raise RuntimeError, "it looks like the server doesn't support NTLM Login" end # send Type1 Message t1 = Net::NTLM::Message::Type1.new() writeline s, "AUTH NTLM " + t1.encode64 # receive Type2 Message, i hope line = readline s unless /334 (.+)/ =~ line raise RuntimeError, "i don't recognize this: #{line}" end t2 = Net::NTLM::Message.decode64($1) unless $user and $passwd target = t2.target_name target = Net::NTLM::decode_utf16le(target) if t2.has_flag?(:UNICODE) puts "Target: #{target}" print "User name: " ($user = $stdin.readline).chomp! print "Password: " ($passwd = $stdin.readline).chomp! end # send Type3 Message t3 = t2.response({:user => $user, :password => $passwd}, {:ntlmv2 => true}) writeline s, t3.encode64 # and result is... line = readline s unless /^235(.+)Authentication successful./i =~ line raise RuntimeError, "sorry, authentication failed." end # do real job here like... # from = $user # to = "billg" # writeline s, "MAIL FROM: #{from}" # readline s # writeline s, "RCPT TO: #{to}" # readline s # writeline s, "DATA" # readline s # writeline s, "From: #{from}" # writeline s, "To: #{to}" # writeline s, "blab blab blab..." # writeline s, "#{from}" # writeline s, "." # readline s # say bye writeline s, "QUIT" s.close end main rubyntlm-0.3.4/examples/http.rb0000644000004100000410000000332112204651732016545 0ustar www-datawww-data# $Id: http.rb,v 1.2 2006/10/05 01:36:52 koheik Exp $ require 'socket' $:.unshift(File.dirname(__FILE__) + '/../lib') require 'net/ntlm' $user = nil $passwd = nil $host = "www" $port = 80 def header(f, host) f.print "GET / HTTP/1.1\r\n" f.print "Host: #{host}\r\n" f.print "Keep-Alive: 300\r\n" f.print "Connection: keep-alive\r\n" end def main s = TCPSocket.new($host, $port) # client -> server t1 = Net::NTLM::Message::Type1.new() header(s, $host) s.print "Authorization: NTLM " + t1.encode64 + "\r\n" s.print "\r\n" # server -> client length = 0 while(line = s.gets) if /^WWW-Authenticate: (NTLM|Negotiate) (.+)\r\n/ =~ line msg = $2 end if /^Content-Length: (\d+)\r\n/ =~ line length = $1.to_i end if /^\r\n/ =~ line if length > 0 cont = s.read(length) end break end end t2 = Net::NTLM::Message.decode64(msg) unless $user and $passwd target = t2.target_name target = Net::NTLM::decode_utf16le(target) if t2.has_flag?(:UNICODE) puts "Target: #{target}" print "User name: " ($user = $stdin.readline).chomp! print "Password: " ($passwd = $stdin.readline).chomp! end # client -> server, again t3 = t2.response({:user => $user, :password => $passwd}, {:ntlmv2 => true}) header(s, $host) s.print "Authorization: NTLM " + t3.encode64 + "\r\n" s.print "\r\n" # server -> client length = 0 while(line = s.gets) if /^WWW-Authenticate: (NTLM|Negotiate) (.+)\r\n/ =~ line msg = $2 end if /^Content-Length: (\d+)\r\n/ =~ line length = $1.to_i end if /^\r\n/ =~ line if length > 0 p cont = s.read(length) end break end end s.close end main rubyntlm-0.3.4/examples/imap.rb0000644000004100000410000000350512204651732016520 0ustar www-datawww-data# $Id: imap.rb,v 1.1 2006/10/05 01:36:52 koheik Exp $ require "net/imap" $:.unshift(File.dirname(__FILE__) + '/../lib') require "net/ntlm" Net::IMAP::debug = true $host = "localhost" $port = 143 $ssl = false $user = nil $passwd = nil module Net class IMAP class NtlmAuthenticator def process(data) case @state when 1 @state = 2 t1 = Net::NTLM::Message::Type1.new() return t1.serialize when 2 @state = 3 t2 = Net::NTLM::Message.parse(data) t3 = t2.response({:user => @user, :password => @password}, {:ntlmv2 => (@ntlm_type == "ntlmv2")}) return t3.serialize end end private def initialize(user, password, ntlm_type = "ntlmv2") @user = user @password = password @ntlm_type = @ntlm_type @state = 1 end end add_authenticator "NTLM", NtlmAuthenticator class ResponseParser def continue_req match(T_PLUS) if lookahead.symbol == T_CRLF # means empty message return ContinuationRequest.new(ResponseText.new(nil, ""), @str) end match(T_SPACE) return ContinuationRequest.new(resp_text, @str) end end end end unless $user and $passwd print "User name: " ($user = $stdin.readline).chomp! print "Password: " ($passwd = $stdin.readline).chomp! end imap = Net::IMAP.new($host, $port, $ssl) imap.authenticate("NTLM", $user, $passwd) imap.examine("Inbox") # imap.search(["RECENT"]).each do |message_id| # envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"] # from = envelope.from.nil? ? "" : envelope.from[0].name # subject = envelope.subject # puts "#{message_id} #{from}: \t#{subject}" # end imap.logout # imap.disconnect rubyntlm-0.3.4/README.md0000644000004100000410000000202512204651732014702 0ustar www-datawww-data# Ruby/NTLM -- NTLM Authentication Library for Ruby [![Build Status](https://travis-ci.org/WinRb/rubyntlm.png)](https://travis-ci.org/WinRb/rubyntlm) Ruby/NTLM provides message creator and parser for the NTLM authentication. __100% Ruby__ Simple Example -------------- ### Creating NTLM Type 1 message ```ruby t1 = NTLM::Message::Type1.new() ``` ### Parsing NTLM Type 2 message from server ```ruby t2 = NTLM::Message.parse(message_from_server) ``` ### Creating NTLM Type 3 message ```ruby t3 = t2.response({:user => 'user', :password => 'passwd'}) ``` Support ------- https://groups.google.com/forum/?fromgroups#!forum/rubyntlm Contributing ------------ 1. Fork it. 2. Create a branch (git checkout -b my_feature_branch) 3. Commit your changes (git commit -am "Added a sweet feature") 4. Push to the branch (git push origin my_feature_branch) 5. Create a pull requst from your branch into master (Please be sure to provide enough detail for us to cipher what this change is doing) rubyntlm-0.3.4/Rakefile0000644000004100000410000000070212204651732015070 0ustar www-datawww-datarequire "bundler/gem_tasks" task :default => [:spec] require 'rspec/core/rake_task' desc 'Default: run specs.' task :default => :spec desc "Run specs unit tests" RSpec::Core::RakeTask.new do |t| t.pattern = "./spec/unit/*_spec.rb" end desc "Generate code coverage" RSpec::Core::RakeTask.new(:coverage) do |t| t.pattern = "./spec/unit/*_spec.rb" # don't need this, it's default. t.rcov = true t.rcov_opts = ['--exclude', 'spec'] endrubyntlm-0.3.4/spec/0000755000004100000410000000000012204651732014356 5ustar www-datawww-datarubyntlm-0.3.4/spec/unit/0000755000004100000410000000000012204651732015335 5ustar www-datawww-datarubyntlm-0.3.4/spec/unit/ntlm_spec.rb0000644000004100000410000001514712204651732017656 0ustar www-datawww-data# encoding: UTF-8 $:.unshift(File.expand_path(File.dirname(__FILE__) << '../lib')) describe Net::NTLM::Message do let(:type1_packet) {"TlRMTVNTUAABAAAAB4IIAAAAAAAgAAAAAAAAACAAAAA="} let(:type2_packet) {"TlRMTVNTUAACAAAAHAAcADgAAAAFgooCJ+UA1//+ZM4AAAAAAAAAAJAAkABUAAAABgGxHQAAAA9WAEEARwBSAEEATgBUAC0AMgAwADAAOABSADIAAgAcAFYAQQBHAFIAQQBOAFQALQAyADAAMAA4AFIAMgABABwAVgBBAEcAUgBBAE4AVAAtADIAMAAwADgAUgAyAAQAHAB2AGEAZwByAGEAbgB0AC0AMgAwADAAOABSADIAAwAcAHYAYQBnAHIAYQBuAHQALQAyADAAMAA4AFIAMgAHAAgAZBMdFHQnzgEAAAAA"} let(:type3_packet) {"TlRMTVNTUAADAAAAGAAYAEQAAADAAMAAXAAAAAAAAAAcAQAADgAOABwBAAAUABQAKgEAAAAAAAA+AQAABYKKAgAAAADVS27TfQGmWxSSbXmolTUQyxJmD8ISQuBKKHFKC8GksUZISYc8Ps9RAQEAAAAAAAAANasTdCfOAcsSZg/CEkLgAAAAAAIAHABWAEEARwBSAEEATgBUAC0AMgAwADAAOABSADIAAQAcAFYAQQBHAFIAQQBOAFQALQAyADAAMAA4AFIAMgAEABwAdgBhAGcAcgBhAG4AdAAtADIAMAAwADgAUgAyAAMAHAB2AGEAZwByAGEAbgB0AC0AMgAwADAAOABSADIABwAIAGQTHRR0J84BAAAAAAAAAAB2AGEAZwByAGEAbgB0AGsAbwBiAGUALgBsAG8AYwBhAGwA"} describe Net::NTLM::Message::Type1 do it 'should deserialize' do t1 = Net::NTLM::Message.decode64(type1_packet) t1.class.should == Net::NTLM::Message::Type1 t1.domain.should == '' t1.flag.should == 557575 t1.padding.should == '' t1.sign.should == "NTLMSSP\0" t1.type.should == 1 t1.workstation.should == '' end it 'should serialize' do t1 = Net::NTLM::Message::Type1.new t1.workstation = '' t1.encode64.should == type1_packet end end describe Net::NTLM::Message::Type2 do it 'should deserialize' do t2 = Net::NTLM::Message.decode64(type2_packet) t2.class.should == Net::NTLM::Message::Type2 t2.challenge.should == 14872292244261496103 t2.context.should == 0 t2.flag.should == 42631685 if "".respond_to?(:force_encoding) t2.padding.should == ("\x06\x01\xB1\x1D\0\0\0\x0F".force_encoding('ASCII-8BIT')) end t2.sign.should == "NTLMSSP\0" t2_target_info = Net::NTLM::EncodeUtil.decode_utf16le(t2.target_info) if RUBY_VERSION == "1.8.7" t2_target_info.should == "\x02\x1CVAGRANT-2008R2\x01\x1CVAGRANT-2008R2\x04\x1Cvagrant-2008R2\x03\x1Cvagrant-2008R2\a\b\e$(D+&\e(B\0\0" else t2_target_info.should == "\u0002\u001CVAGRANT-2008R2\u0001\u001CVAGRANT-2008R2\u0004\u001Cvagrant-2008R2\u0003\u001Cvagrant-2008R2\a\b፤ᐝ❴ǎ\0\0" end Net::NTLM::EncodeUtil.decode_utf16le(t2.target_name).should == "VAGRANT-2008R2" t2.type.should == 2 end it 'should serialize' do source = Net::NTLM::Message.decode64(type2_packet) t2 = Net::NTLM::Message::Type2.new t2.challenge = source.challenge t2.context = source.context t2.flag = source.flag t2.padding = source.padding t2.sign = source.sign t2.target_info = source.target_info t2.target_name = source.target_name t2.type = source.type t2.enable(:context) t2.enable(:target_info) t2.enable(:padding) t2.encode64.should == type2_packet end it 'should generate a type 3 response' do t2 = Net::NTLM::Message.decode64(type2_packet) type3_known = Net::NTLM::Message.decode64(type3_packet) type3_known.flag = 0x028a8205 type3_known.enable(:session_key) type3_known.enable(:flag) t3 = t2.response({:user => 'vagrant', :password => 'vagrant', :domain => ''}, {:ntlmv2 => true, :workstation => 'kobe.local'}) t3.domain.should == type3_known.domain t3.flag.should == type3_known.flag t3.sign.should == "NTLMSSP\0" t3.workstation.should == "k\0o\0b\0e\0.\0l\0o\0c\0a\0l\0" t3.user.should == "v\0a\0g\0r\0a\0n\0t\0" t3.session_key.should == '' end end end describe Net::NTLM do let(:passwd) {"SecREt01"} let(:user) {"user"} let(:domain) {"domain"} let(:challenge) {["0123456789abcdef"].pack("H*")} let(:client_ch) {["ffffff0011223344"].pack("H*")} let(:timestamp) {1055844000} let(:trgt_info) {[ "02000c0044004f004d00410049004e00" + "01000c00530045005200560045005200" + "0400140064006f006d00610069006e00" + "2e0063006f006d000300220073006500" + "72007600650072002e0064006f006d00" + "610069006e002e0063006f006d000000" + "0000" ].pack("H*")} it 'should generate an lm_hash' do Net::NTLM::lm_hash(passwd).should == ["ff3750bcc2b22412c2265b23734e0dac"].pack("H*") end it 'should generate an ntlm_hash' do Net::NTLM::ntlm_hash(passwd).should == ["cd06ca7c7e10c99b1d33b7485a2ed808"].pack("H*") end it 'should generate an ntlmv2_hash' do Net::NTLM::ntlmv2_hash(user, passwd, domain).should == ["04b8e0ba74289cc540826bab1dee63ae"].pack("H*") end it 'should generate an lm_response' do Net::NTLM::lm_response( { :lm_hash => Net::NTLM::lm_hash(passwd), :challenge => challenge } ).should == ["c337cd5cbd44fc9782a667af6d427c6de67c20c2d3e77c56"].pack("H*") end it 'should generate an ntlm_response' do ntlm_hash = Net::NTLM::ntlm_hash(passwd) Net::NTLM::ntlm_response( { :ntlm_hash => ntlm_hash, :challenge => challenge } ).should == ["25a98c1c31e81847466b29b2df4680f39958fb8c213a9cc6"].pack("H*") end it 'should generate a lvm2_response' do Net::NTLM::lmv2_response( { :ntlmv2_hash => Net::NTLM::ntlmv2_hash(user, passwd, domain), :challenge => challenge }, { :client_challenge => client_ch } ).should == ["d6e6152ea25d03b7c6ba6629c2d6aaf0ffffff0011223344"].pack("H*") end it 'should generate a ntlmv2_response' do Net::NTLM::ntlmv2_response( { :ntlmv2_hash => Net::NTLM::ntlmv2_hash(user, passwd, domain), :challenge => challenge, :target_info => trgt_info }, { :timestamp => timestamp, :client_challenge => client_ch } ).should == [ "cbabbca713eb795d04c97abc01ee4983" + "01010000000000000090d336b734c301" + "ffffff00112233440000000002000c00" + "44004f004d00410049004e0001000c00" + "53004500520056004500520004001400" + "64006f006d00610069006e002e006300" + "6f006d00030022007300650072007600" + "650072002e0064006f006d0061006900" + "6e002e0063006f006d00000000000000" + "0000" ].pack("H*") end it 'should generate a ntlm2_session' do session = Net::NTLM::ntlm2_session( { :ntlm_hash => Net::NTLM::ntlm_hash(passwd), :challenge => challenge }, { :client_challenge => client_ch } ) session[0].should == ["ffffff001122334400000000000000000000000000000000"].pack("H*") session[1].should == ["10d550832d12b2ccb79d5ad1f4eed3df82aca4c3681dd455"].pack("H*") end end rubyntlm-0.3.4/checksums.yaml.gz0000444000004100000410000000041712204651732016714 0ustar www-datawww-data[Re;@ D9\`w32rNnD$h"NO&Jrz?~g;5X\V; fO;|[x16*;Pmw8/cSKngo chzn@⠁nYrV.i"3|ؖ@h!u qo{ƿsWme9ȂSK/t`msXr$tT.TXN=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' description: Ruby/NTLM provides message creator and parser for the NTLM authentication. email: - koheik@gmail.com - paul.e.morton@gmail.com executables: [] extensions: [] extra_rdoc_files: [] files: - .gitignore - .travis.yml - CHANGELOG.md - Gemfile - README.md - Rakefile - examples/http.rb - examples/imap.rb - examples/smtp.rb - lib/net/ntlm.rb - lib/rubyntlm.rb - rubyntlm.gemspec - spec/unit/ntlm_spec.rb homepage: https://github.com/winrb/rubyntlm licenses: [] metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: 1.8.7 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.0.3 signing_key: specification_version: 4 summary: Ruby/NTLM library. test_files: - spec/unit/ntlm_spec.rb rubyntlm-0.3.4/CHANGELOG.md0000644000004100000410000000056612204651732015244 0ustar www-datawww-data0.2.0 - Major changes to behavior!!!! - Bug - Type 1 packets do not include a domain and workstation by defauly. Packet capture software will see this type of packet as malformed. All packets now include this information - Bug - Type 3 packets do not include the calling workstation. This should be setup by default. 0.1.2 - Feature user can specify the target domain rubyntlm-0.3.4/Gemfile0000644000004100000410000000004712204651732014720 0ustar www-datawww-datasource 'https://rubygems.org' gemspec rubyntlm-0.3.4/.gitignore0000644000004100000410000000003212204651732015407 0ustar www-datawww-data.yardoc /doc Gemfile.lock rubyntlm-0.3.4/lib/0000755000004100000410000000000012204651732014172 5ustar www-datawww-datarubyntlm-0.3.4/lib/net/0000755000004100000410000000000012204651732014760 5ustar www-datawww-datarubyntlm-0.3.4/lib/net/ntlm.rb0000644000004100000410000006050512204651732016265 0ustar www-datawww-data# encoding: UTF-8 # # = net/ntlm.rb # # An NTLM Authentication Library for Ruby # # This code is a derivative of "dbf2.rb" written by yrock # and Minero Aoki. You can find original code here: # http://jp.rubyist.net/magazine/?0013-CodeReview # ------------------------------------------------------------- # Copyright (c) 2005,2006 yrock # # This program is free software. # You can distribute/modify this program under the terms of the # Ruby License. # # 2006-02-11 refactored by Minero Aoki # ------------------------------------------------------------- # # All protocol information used to write this code stems from # "The NTLM Authentication Protocol" by Eric Glass. The author # would thank to him for this tremendous work and making it # available on the net. # http://davenport.sourceforge.net/ntlm.html # ------------------------------------------------------------- # Copyright (c) 2003 Eric Glass # # Permission to use, copy, modify, and distribute this document # for any purpose and without any fee is hereby granted, # provided that the above copyright notice and this list of # conditions appear in all copies. # ------------------------------------------------------------- # # The author also looked Mozilla-Firefox-1.0.7 source code, # namely, security/manager/ssl/src/nsNTLMAuthModule.cpp and # Jonathan Bastien-Filiatrault's libntlm-ruby. # "http://x2a.org/websvn/filedetails.php? # repname=libntlm-ruby&path=%2Ftrunk%2Fntlm.rb&sc=1" # The latter has a minor bug in its separate_keys function. # The third key has to begin from the 14th character of the # input string instead of 13th:) #-- # $Id: ntlm.rb,v 1.1 2006/10/05 01:36:52 koheik Exp $ #++ require 'base64' require 'openssl' require 'openssl/digest' require 'socket' module Net module NTLM # @private module VERSION MAJOR = 0 MINOR = 3 TINY = 4 STRING = [MAJOR, MINOR, TINY].join('.') end SSP_SIGN = "NTLMSSP\0" BLOB_SIGN = 0x00000101 LM_MAGIC = "KGS!@\#$%" TIME_OFFSET = 11644473600 MAX64 = 0xffffffffffffffff FLAGS = { :UNICODE => 0x00000001, :OEM => 0x00000002, :REQUEST_TARGET => 0x00000004, :MBZ9 => 0x00000008, :SIGN => 0x00000010, :SEAL => 0x00000020, :NEG_DATAGRAM => 0x00000040, :NETWARE => 0x00000100, :NTLM => 0x00000200, :NEG_NT_ONLY => 0x00000400, :MBZ7 => 0x00000800, :DOMAIN_SUPPLIED => 0x00001000, :WORKSTATION_SUPPLIED => 0x00002000, :LOCAL_CALL => 0x00004000, :ALWAYS_SIGN => 0x00008000, :TARGET_TYPE_DOMAIN => 0x00010000, :TARGET_INFO => 0x00800000, :NTLM2_KEY => 0x00080000, :KEY128 => 0x20000000, :KEY56 => 0x80000000 }.freeze FLAG_KEYS = FLAGS.keys.sort{|a, b| FLAGS[a] <=> FLAGS[b] } DEFAULT_FLAGS = { :TYPE1 => FLAGS[:UNICODE] | FLAGS[:OEM] | FLAGS[:REQUEST_TARGET] | FLAGS[:NTLM] | FLAGS[:ALWAYS_SIGN] | FLAGS[:NTLM2_KEY], :TYPE2 => FLAGS[:UNICODE], :TYPE3 => FLAGS[:UNICODE] | FLAGS[:REQUEST_TARGET] | FLAGS[:NTLM] | FLAGS[:ALWAYS_SIGN] | FLAGS[:NTLM2_KEY] } class EncodeUtil if RUBY_VERSION == "1.8.7" require "kconv" # Decode a UTF16 string to a ASCII string # @param [String] str The string to convert def self.decode_utf16le(str) Kconv.kconv(swap16(str), Kconv::ASCII, Kconv::UTF16) end # Encodes a ASCII string to a UTF16 string # @param [String] str The string to convert def self.encode_utf16le(str) swap16(Kconv.kconv(str, Kconv::UTF16, Kconv::ASCII)) end # Taggle the strings endianness between big/little and little/big # @param [String] str The string to swap the endianness on def self.swap16(str) str.unpack("v*").pack("n*") end else # Use native 1.9 string encoding functions # Decode a UTF16 string to a ASCII string # @param [String] str The string to convert def self.decode_utf16le(str) str.encode(Encoding::UTF_8, Encoding::UTF_16LE).force_encoding('UTF-8') end # Encodes a ASCII string to a UTF16 string # @param [String] str The string to convert # @note This implementation may seem stupid but the problem is that UTF16-LE and UTF-8 are incompatiable # encodings. This library uses string contatination to build the packet bytes. The end result is that # you can either marshal the encodings elsewhere of simply know that each time you call encode_utf16le # the function will convert the string bytes to UTF-16LE and note the encoding as UTF-8 so that byte # concatination works seamlessly. def self.encode_utf16le(str) str = str.force_encoding('UTF-8') if [::Encoding::ASCII_8BIT,::Encoding::US_ASCII].include?(str.encoding) str.dup.force_encoding('UTF-8').encode(Encoding::UTF_16LE, Encoding::UTF_8).force_encoding('UTF-8') end end end class << self # Conver the value to a 64-Bit Little Endian Int # @param [String] val The string to convert def pack_int64le(val) [val & 0x00000000ffffffff, val >> 32].pack("V2") end # Builds an array of strings that are 7 characters long # @param [String] str The string to split # @api private def split7(str) s = str.dup until s.empty? (ret ||= []).push s.slice!(0, 7) end ret end # Not sure what this is doing # @param [String] str String to generate keys for # @api private def gen_keys(str) split7(str).map{ |str7| bits = split7(str7.unpack("B*")[0]).inject('')\ {|ret, tkn| ret += tkn + (tkn.gsub('1', '').size % 2).to_s } [bits].pack("B*") } end def apply_des(plain, keys) dec = OpenSSL::Cipher::DES.new keys.map {|k| dec.key = k dec.encrypt.update(plain) } end # Generates a Lan Manager Hash # @param [String] password The password to base the hash on def lm_hash(password) keys = gen_keys password.upcase.ljust(14, "\0") apply_des(LM_MAGIC, keys).join end # Generate a NTLM Hash # @param [String] password The password to base the hash on # @option opt :unicode (false) Unicode encode the password def ntlm_hash(password, opt = {}) pwd = password.dup unless opt[:unicode] pwd = EncodeUtil.encode_utf16le(pwd) end OpenSSL::Digest::MD4.digest pwd end # Generate a NTLMv2 Hash # @param [String] user The username # @param [String] password The password # @param [String] target The domain or workstaiton to authenticate to # @option opt :unicode (false) Unicode encode the domain def ntlmv2_hash(user, password, target, opt={}) ntlmhash = ntlm_hash(password, opt) userdomain = (user + target).upcase unless opt[:unicode] userdomain = EncodeUtil.encode_utf16le(userdomain) end OpenSSL::HMAC.digest(OpenSSL::Digest::MD5.new, ntlmhash, userdomain) end def lm_response(arg) begin hash = arg[:lm_hash] chal = arg[:challenge] rescue raise ArgumentError end chal = NTLM::pack_int64le(chal) if chal.is_a?(Integer) keys = gen_keys hash.ljust(21, "\0") apply_des(chal, keys).join end def ntlm_response(arg) hash = arg[:ntlm_hash] chal = arg[:challenge] chal = NTLM::pack_int64le(chal) if chal.is_a?(Integer) keys = gen_keys hash.ljust(21, "\0") apply_des(chal, keys).join end def ntlmv2_response(arg, opt = {}) begin key = arg[:ntlmv2_hash] chal = arg[:challenge] ti = arg[:target_info] rescue raise ArgumentError end chal = NTLM::pack_int64le(chal) if chal.is_a?(Integer) if opt[:client_challenge] cc = opt[:client_challenge] else cc = rand(MAX64) end cc = NTLM::pack_int64le(cc) if cc.is_a?(Integer) if opt[:timestamp] ts = opt[:timestamp] else ts = Time.now.to_i end # epoch -> milsec from Jan 1, 1601 ts = 10000000 * (ts + TIME_OFFSET) blob = Blob.new blob.timestamp = ts blob.challenge = cc blob.target_info = ti bb = blob.serialize OpenSSL::HMAC.digest(OpenSSL::Digest::MD5.new, key, chal + bb) + bb end def lmv2_response(arg, opt = {}) key = arg[:ntlmv2_hash] chal = arg[:challenge] chal = NTLM::pack_int64le(chal) if chal.is_a?(Integer) if opt[:client_challenge] cc = opt[:client_challenge] else cc = rand(MAX64) end cc = NTLM::pack_int64le(cc) if cc.is_a?(Integer) OpenSSL::HMAC.digest(OpenSSL::Digest::MD5.new, key, chal + cc) + cc end def ntlm2_session(arg, opt = {}) begin passwd_hash = arg[:ntlm_hash] chal = arg[:challenge] rescue raise ArgumentError end if opt[:client_challenge] cc = opt[:client_challenge] else cc = rand(MAX64) end cc = NTLM::pack_int64le(cc) if cc.is_a?(Integer) keys = gen_keys passwd_hash.ljust(21, "\0") session_hash = OpenSSL::Digest::MD5.digest(chal + cc).slice(0, 8) response = apply_des(session_hash, keys).join [cc.ljust(24, "\0"), response] end end # base classes for primitives # @private class Field attr_accessor :active, :value def initialize(opts) @value = opts[:value] @active = opts[:active].nil? ? true : opts[:active] end def size @active ? @size : 0 end end class String < Field def initialize(opts) super(opts) @size = opts[:size] end def parse(str, offset=0) if @active and str.size >= offset + @size @value = str[offset, @size] @size else 0 end end def serialize if @active @value else "" end end def value=(val) @value = val @size = @value.nil? ? 0 : @value.size @active = (@size > 0) end end class Int16LE < Field def initialize(opt) super(opt) @size = 2 end def parse(str, offset=0) if @active and str.size >= offset + @size @value = str[offset, @size].unpack("v")[0] @size else 0 end end def serialize [@value].pack("v") end end class Int32LE < Field def initialize(opt) super(opt) @size = 4 end def parse(str, offset=0) if @active and str.size >= offset + @size @value = str.slice(offset, @size).unpack("V")[0] @size else 0 end end def serialize [@value].pack("V") if @active end end class Int64LE < Field def initialize(opt) super(opt) @size = 8 end def parse(str, offset=0) if @active and str.size >= offset + @size d, u = str.slice(offset, @size).unpack("V2") @value = (u * 0x100000000 + d) @size else 0 end end def serialize [@value & 0x00000000ffffffff, @value >> 32].pack("V2") if @active end end # base class of data structure class FieldSet class << FieldSet # @macro string_security_buffer # @method $1 # @method $1= # @return [String] def string(name, opts) add_field(name, String, opts) end # @macro int16le_security_buffer # @method $1 # @method $1= # @return [Int16LE] def int16LE(name, opts) add_field(name, Int16LE, opts) end # @macro int32le_security_buffer # @method $1 # @method $1= # @return [Int32LE] def int32LE(name, opts) add_field(name, Int32LE, opts) end # @macro int64le_security_buffer # @method $1 # @method $1= # @return [Int64] def int64LE(name, opts) add_field(name, Int64LE, opts) end # @macro security_buffer # @method $1 # @method $1= # @return [SecurityBuffer] def security_buffer(name, opts) add_field(name, SecurityBuffer, opts) end def prototypes @proto end def names @proto.map{|n, t, o| n} end def types @proto.map{|n, t, o| t} end def opts @proto.map{|n, t, o| o} end private def add_field(name, type, opts) (@proto ||= []).push [name, type, opts] define_accessor name end def define_accessor(name) module_eval(<<-End, __FILE__, __LINE__ + 1) def #{name} self['#{name}'].value end def #{name}=(val) self['#{name}'].value = val end End end end def initialize @alist = self.class.prototypes.map{ |n, t, o| [n, t.new(o)] } end def serialize @alist.map{|n, f| f.serialize }.join end def parse(str, offset=0) @alist.inject(offset){|cur, a| cur += a[1].parse(str, cur)} end def size @alist.inject(0){|sum, a| sum += a[1].size} end def [](name) a = @alist.assoc(name.to_s.intern) raise ArgumentError, "no such field: #{name}" unless a a[1] end def []=(name, val) a = @alist.assoc(name.to_s.intern) raise ArgumentError, "no such field: #{name}" unless a a[1] = val end def enable(name) self[name].active = true end def disable(name) self[name].active = false end end class Blob < FieldSet int32LE :blob_signature, {:value => BLOB_SIGN} int32LE :reserved, {:value => 0} int64LE :timestamp, {:value => 0} string :challenge, {:value => "", :size => 8} int32LE :unknown1, {:value => 0} string :target_info, {:value => "", :size => 0} int32LE :unknown2, {:value => 0} end class SecurityBuffer < FieldSet int16LE :length, {:value => 0} int16LE :allocated, {:value => 0} int32LE :offset, {:value => 0} attr_accessor :active def initialize(opts) super() @value = opts[:value] @active = opts[:active].nil? ? true : opts[:active] @size = 8 end def parse(str, offset=0) if @active and str.size >= offset + @size super(str, offset) @value = str[self.offset, self.length] @size else 0 end end def serialize super if @active end def value @value end def value=(val) @value = val self.length = self.allocated = val.size end def data_size @active ? @value.size : 0 end end # @private false class Message < FieldSet class << Message def parse(str) m = Type0.new m.parse(str) case m.type when 1 t = Type1.parse(str) when 2 t = Type2.parse(str) when 3 t = Type3.parse(str) else raise ArgumentError, "unknown type: #{m.type}" end t end def decode64(str) parse(Base64.decode64(str)) end end def has_flag?(flag) (self[:flag].value & FLAGS[flag]) == FLAGS[flag] end def set_flag(flag) self[:flag].value |= FLAGS[flag] end def dump_flags FLAG_KEYS.each{ |k| print(k, "=", flag?(k), "\n") } end def serialize deflag super + security_buffers.map{|n, f| f.value}.join end def encode64 Base64.encode64(serialize).gsub(/\n/, '') end def decode64(str) parse(Base64.decode64(str)) end alias head_size size def data_size security_buffers.inject(0){|sum, a| sum += a[1].data_size} end def size head_size + data_size end def security_buffers @alist.find_all{|n, f| f.instance_of?(SecurityBuffer)} end def deflag security_buffers.inject(head_size){|cur, a| a[1].offset = cur cur += a[1].data_size } end def data_edge security_buffers.map{ |n, f| f.active ? f.offset : size}.min end # sub class definitions class Type0 < Message string :sign, {:size => 8, :value => SSP_SIGN} int32LE :type, {:value => 0} end # @private false class Type1 < Message string :sign, {:size => 8, :value => SSP_SIGN} int32LE :type, {:value => 1} int32LE :flag, {:value => DEFAULT_FLAGS[:TYPE1] } security_buffer :domain, {:value => ""} security_buffer :workstation, {:value => Socket.gethostname } string :padding, {:size => 0, :value => "", :active => false } class << Type1 # Parses a Type 1 Message # @param [String] str A string containing Type 1 data # @return [Type1] The parsed Type 1 message def parse(str) t = new t.parse(str) t end end # @!visibility private def parse(str) super(str) enable(:domain) if has_flag?(:DOMAIN_SUPPLIED) enable(:workstation) if has_flag?(:WORKSTATION_SUPPLIED) super(str) if ( (len = data_edge - head_size) > 0) self.padding = "\0" * len super(str) end end end # @private false class Type2 < Message string :sign, {:size => 8, :value => SSP_SIGN} int32LE :type, {:value => 2} security_buffer :target_name, {:size => 0, :value => ""} int32LE :flag, {:value => DEFAULT_FLAGS[:TYPE2]} int64LE :challenge, {:value => 0} int64LE :context, {:value => 0, :active => false} security_buffer :target_info, {:value => "", :active => false} string :padding, {:size => 0, :value => "", :active => false } class << Type2 # Parse a Type 2 packet # @param [String] str A string containing Type 2 data # @return [Type2] def parse(str) t = new t.parse(str) t end end # @!visibility private def parse(str) super(str) if has_flag?(:TARGET_INFO) enable(:context) enable(:target_info) super(str) end if ( (len = data_edge - head_size) > 0) self.padding = "\0" * len super(str) end end # Generates a Type 3 response based on the Type 2 Information # @return [Type3] # @option arg [String] :username The username to authenticate with # @option arg [String] :password The user's password # @option arg [String] :domain ('') The domain to authenticate to # @option opt [String] :workstation (Socket.gethostname) The name of the calling workstation # @option opt [Boolean] :use_default_target (False) Use the domain supplied by the server in the Type 2 packet # @note An empty :domain option authenticates to the local machine. # @note The :use_default_target has presidence over the :domain option def response(arg, opt = {}) usr = arg[:user] pwd = arg[:password] domain = arg[:domain] ? arg[:domain] : "" if usr.nil? or pwd.nil? raise ArgumentError, "user and password have to be supplied" end if opt[:workstation] ws = opt[:workstation] else ws = Socket.gethostname end if opt[:client_challenge] cc = opt[:client_challenge] else cc = rand(MAX64) end cc = NTLM::pack_int64le(cc) if cc.is_a?(Integer) opt[:client_challenge] = cc if has_flag?(:OEM) and opt[:unicode] usr = NTLM::EncodeUtil.decode_utf16le(usr) pwd = NTLM::EncodeUtil.decode_utf16le(pwd) ws = NTLM::EncodeUtil.decode_utf16le(ws) domain = NTLM::EncodeUtil.decode_utf16le(domain) opt[:unicode] = false end if has_flag?(:UNICODE) and !opt[:unicode] usr = NTLM::EncodeUtil.encode_utf16le(usr) pwd = NTLM::EncodeUtil.encode_utf16le(pwd) ws = NTLM::EncodeUtil.encode_utf16le(ws) domain = NTLM::EncodeUtil.encode_utf16le(domain) opt[:unicode] = true end if opt[:use_default_target] domain = self.target_name end ti = self.target_info chal = self[:challenge].serialize if opt[:ntlmv2] ar = {:ntlmv2_hash => NTLM::ntlmv2_hash(usr, pwd, domain, opt), :challenge => chal, :target_info => ti} lm_res = NTLM::lmv2_response(ar, opt) ntlm_res = NTLM::ntlmv2_response(ar, opt) elsif has_flag?(:NTLM2_KEY) ar = {:ntlm_hash => NTLM::ntlm_hash(pwd, opt), :challenge => chal} lm_res, ntlm_res = NTLM::ntlm2_session(ar, opt) else lm_res = NTLM::lm_response(pwd, chal) ntlm_res = NTLM::ntlm_response(pwd, chal) end Type3.create({ :lm_response => lm_res, :ntlm_response => ntlm_res, :domain => domain, :user => usr, :workstation => ws, :flag => self.flag }) end end # @private false class Type3 < Message string :sign, {:size => 8, :value => SSP_SIGN} int32LE :type, {:value => 3} security_buffer :lm_response, {:value => ""} security_buffer :ntlm_response, {:value => ""} security_buffer :domain, {:value => ""} security_buffer :user, {:value => ""} security_buffer :workstation, {:value => ""} security_buffer :session_key, {:value => "", :active => false } int64LE :flag, {:value => 0, :active => false } class << Type3 # Parse a Type 3 packet # @param [String] str A string containing Type 3 data # @return [Type2] def parse(str) t = new t.parse(str) t end # Builds a Type 3 packet # @note All options must be properly encoded with either unicode or oem encoding # @return [Type3] # @option arg [String] :lm_response The LM hash # @option arg [String] :ntlm_response The NTLM hash # @option arg [String] :domain The domain to authenticate to # @option arg [String] :workstation The name of the calling workstation # @option arg [String] :session_key The session key # @option arg [Integer] :flag Flags for the packet def create(arg, opt ={}) t = new t.lm_response = arg[:lm_response] t.ntlm_response = arg[:ntlm_response] t.domain = arg[:domain] t.user = arg[:user] if arg[:workstation] t.workstation = arg[:workstation] end if arg[:session_key] t.enable(:session_key) t.session_key = arg[session_key] end if arg[:flag] t.enable(:session_key) t.enable(:flag) t.flag = arg[:flag] end t end end end end end end rubyntlm-0.3.4/lib/rubyntlm.rb0000644000004100000410000000002212204651732016365 0ustar www-datawww-datarequire 'net/ntlm'rubyntlm-0.3.4/rubyntlm.gemspec0000644000004100000410000000145012204651732016645 0ustar www-datawww-datarequire File.join(File.dirname(__FILE__), 'lib', 'net', 'ntlm') Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'rubyntlm' s.version = Net::NTLM::VERSION::STRING s.summary = 'Ruby/NTLM library.' s.description = 'Ruby/NTLM provides message creator and parser for the NTLM authentication.' s.authors = ['Kohei Kajimoto','Paul Morton'] s.email = ['koheik@gmail.com','paul.e.morton@gmail.com'] s.homepage = 'https://github.com/winrb/rubyntlm' s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.required_ruby_version = '>= 1.8.7' s.add_development_dependency "rake" s.add_development_dependency "rspec" end