def authenticate(username, password)
require 'net-ldap'
ldap = Net::LDAP.new
ldap.host = 'server.local'
ldap.port = 389
ldap.base = 'cn=users, dc=server, dc=local'
ldap.auth username, password
if ldap.bind
puts "authentication succeeded"
else
puts "authentication failed"
end
The above is the code i use in my method and i am not sure why my attempts fail. I am trying to authenticate user. I could not find where i am going wrong? It puts authentication failed every time. why? please help me.
First up see if the computer you are using can talk to the LDAP server
telnet server.local 389
Obviously you want to be replacing server.local with your actual server details. If you can't log into the server this way then port 389 isn't open and you may need to be running on the SSL port 636. Try the previous command with 636 rather than 389 to see if that is the case.
If you are unable to telnet into the server on either of those ports you've either got a firewall rule blocking you from talking to it, LDAP is configured on a non standard port or something else is seriously wrong.
A working port 636 will probably mean you need to run something like the following.
require "net-ldap"
ldap = Net::LDAP.new(
host: "server.local"
port: 636
encryption: :simple_tls
)
ldap.auth username, password
Failing all of that an error message is going to be pretty useful so try running
if ldap.bind
# Yay!
else
puts ldap.get_operation_result
end
With some results from this maybe we can help you a bit more.
Related
My Ruby on Rails application remotely starts some scripts on a distant SuSe server (SUSE Linux Enterprise Server 15 SP2). It relies on the net-ssh gem which is declared in the Gemfile: gem 'net-ssh'.
The script is triggerd remotely through the following block:
Net::SSH.start(remote_host, remote_user, password: remote_password) do |ssh|
feed_back = ssh.exec!("#{event.statement}")
end
This works as expected as long as long as the Rails server runs on Windows Server 2016, which is my DEV environment. But when I deploy to the Validation environment, which is SUSE Linux Enterprise Server 15 SP2, I get this error message:
Errno::ENOTTY in myController#myMethod
Inappropriate ioctl for device
On another hand, issuing the SSH request through the command line - from SUSE to SUSE - works as expected too. Reading around I did not find a relevant parameter for the Net::SSH module to solve this.
Your suggestions are welcome!
I finally found out that the message refers to the operating mode of SSH: it requires a sort of terminal emulation - so called pty - wrapped into a SSH chanel.
So I implemented it this way:
Net::SSH.start(remote_host, remote_user, password: remote_password) do |session|
session.open_channel do |channel|
channel.request_pty do |ch, success|
raise "Error requesting pty" unless success
puts "------------ pty successfully obtained"
end
channel.exec "#{#task.statement}" do |ch, success|
abort "could not execute command" unless success
channel.on_data do |ch, data|
puts "------------ got stdout: #{data}"
#task.update_attribute(:return_value, data)
end
channel.on_extended_data do |ch, type, data|
puts "------------ got stderr: #{data}"
end
channel.on_close do |ch|
puts "------------ channel is closing!"
end
end
end
### Wait until the session closes
session.loop
end
This solved my issue.
Note:
The answer proposed above was only a part of the solution. The same error occured again with this source code when deploying to the production server.
The issue appears to be the password to the SSH target: I retyped it by hand instead of doing the usual copy/paste from MS Excel, and the SSH connection is now successful!
As the error raised is not a simple "connection refused", I suspect that the password string had a specific character encoding, or an unexpected ending character.
As the first proposed solution provides a working example, I leave it there.
I am writing a web interface for a hardware device and am currently doing the network configuration wizard. I want to have the user choose the SSID and if it is secured, then enter a password. I want to check then and there that the password is correct without going any further in the wizard.
Is there any easier way to do this than throwing the details at wpa_supplicant and parsing log output?
Well, could find much, maybe my Google fu sucks. I ended up making this script to do it for me. It uses wpa_supplicant to try to connect and then parses the logs to look for certain strings that indicate auth failure or success. It is only tested with v2.3, if the log output is different in other versions it may not work properly.
It will always cause a current connection on the wireless interface you are testing from to drop momentarily but will come back as soon as the wpa_supplicant started by this script is killed by the script exiting.
#!/usr/bin env ruby
# This script will run WPA to check authentication to a Wifi AP. It will return status 0 for success
# or status 1 for failure, as well as logging some information about what the script is doing.
#
# It has a built in timeout (default 15sec) in case something holds the script up, on a BeagleboneBlack
# this typically took ~10s for a failed auth, and ~2s for a successful auth. In most cases the WPA
# supplicant was killed before DHCP could configure the interface.
#
# In the case where the interface is already connected to an AP and configured via WPA/DHCP, this script
# will cause that connection to drop, regardless of AP auth success or failure. With the latter the
# connection is promptly restored after the script is finished, however with the former the connection
# may be momentarily reconfigured via DHCP to the new APs details, before control is given back to the
# original WPA process. It is unclear if this disconnection can be avoided.
#
# This has only been tested with wpa_supplicant v2.3
require 'logger'
require 'fileutils'
LOG_FILE = "/tmp/wpalog"
PIDFILE = "/tmp/wpapid"
LOG = Logger.new(STDOUT)
ssid = ARGV[0]
pass = ARGV[1]
timeout = 15
dev = "wlan0"
abort "Usage: #{$0} <ssid> <pass>" if ssid.nil? or pass.nil?
File.write(LOG_FILE, "")
# make sure we don't leave wpa running
at_exit do
kill_wpa!
end
# kill the auth process if it's pidfile exists
def kill_wpa!
if File.exist?(PIDFILE)
pid = File.read(PIDFILE).strip
LOG.info "Killing WPA on PID #{pid}"
Process.kill 9, pid.to_i
FileUtils.rm PIDFILE
end
end
# parse the log for indications of auth success/failure
def parse_log
log = File.read(LOG_FILE)
if log.include? "WPA: Key negotiation completed"
return true
end
if log.include?("pre-shared key may be incorrect") || log.include?("auth_failures=1")
return false
end
nil
end
# timeout so we don't keep going forever if theres some issue
Thread.new do
sleep timeout
LOG.fatal "Operation timed out"
exit
end
# run the process to try to auth to the AP
s = Time.now
LOG.info "Starting WPA Supplicant"
system "bash -c 'wpa_supplicant -Dwext -c <(wpa_passphrase \"#{ssid}\" \"#{pass}\") -B -P #{PIDFILE} -f #{LOG_FILE} -i #{dev} 2>/dev/null'"
result = nil
# loop until the parse_log gives us a non nil result indicating auth success or failure
LOG.info "Searching WPA log for authentication state"
loop do
result = parse_log
sleep 0.2 and next if result.nil?
break
end
f = Time.now
duration = (f - s).to_f.round(2)
LOG.info "Found authentication state in #{duration} seconds"
# kill WPA ASAP before DHCP takes over and changes the interface config
kill_wpa!
if result
LOG.info "Authentication successful"
else
LOG.error "Authentication failed"
end
# empty the log in case there are creds in it
File.write(LOG_FILE, "")
# use return values to signal auth failure or success
exit result ? 0 : 1
I am using GitLab Omnibus 7.10.0 on RHEL 6.6. I have enabled LDAP using the following configuration:
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # remember to close this block with 'EOS' below
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'FOO COM Active Directory (LDAP)'
host: 'ad.server.foo.com'
port: 3268
uid: 'someuser'
method: 'plain' # "tls" or "ssl" or "plain"
bind_dn: 'CN=My Whole. Name,OU=Some Users,DC=ad,DC=server,DC=foo,DC=com'
password: 'thepassword'
active_directory: true
allow_username_or_email_login: false
block_auto_created_users: false
base: 'DC=ad,DC=server,DC=foo,DC=com'
user_filter: ''
# ## EE only
# group_base: ''
# admin_group: ''
# sync_ssh_keys: false
#
# secondary: # NOT FILLED OUT
EOS
My problem is that I can't get users to authenticate via LDAP. I'm not sure if the configuration is wrong, or I need to do something on the server side (which I have no direct access to). When I run
gitlab-rake gitlab:ldap:check RAILS_ENV=production
I get this
Checking LDAP ...
LDAP users with access to your GitLab server (only showing the first 100 results)
Server: ldapmain
Checking LDAP ... Finished
I can search for individual users using java with this account (my personal account) or another account for a different application, but can't get AD working with gitlab. I got the bind_dn "My Whole. Name" by running this command on a Windows box.
gpresult -r
I have also tried a bind_dn of:
uid=myADaccountname,OU=Some Users,DC=ad,DC=server,DC=foo,DC=com
and
myADaccountname#ad.server.foo.com
but I still have the same problem.
For Active Directory, the uid should be:
uid: 'sAMAccountName'
Gitlab should connect using the user specified in the bind_dn, with the given password.
Since GitLab 9.5.1 the uid now requires [ ]
See this issue: https://gitlab.com/gitlab-org/gitlab-ce/issues/37120
This might just be a bug which will be fixed.
I had to update the value for Active Directory from the answer above to:
uid: ['sAMAccountName']
I am trying to connect to the XMLRPC API of a dokuwiki website.
I am successfully doing that from my own laptop, with a SSL connection, however, when I try to do it from my production server (which hosts both the wiki and the rails app from which the ruby code is executed), I run into a
Runtime Error
Wrong size. Was 163, should be 113
Here's how I initialize the connection :
#wiki = ::XMLRPC::Client.new3(
host: "wiki.example.com",
path: "/lib/exe/xmlrpc.php",
use_ssl: true)
# Temp Hack because SSL Fails
#wiki.instance_variable_get(:#http).instance_variable_set(:#verify_mode, OpenSSL::SSL::VERIFY_NONE)
end
#authenticated = false
authenticate!
end
def authenticate!
# Fails at below line :
#authenticated = #wiki.call("dokuwiki.login", ENV['WIKI_USER'], ENV['WIKI_PASSWORD'])
Rails.logger.info (#authenticated ? "Authenticated on Wiki !" : "Authentication failed on wiki !")
end
I've read many posts saying that there is a bug in the XMLRPC lib of Ruby. I was running ruby 2.1.5pxx on my laptop and ruby 1.9.xx at my server so I did a rvm install 2.1.5, yet the problem is still here
(btw, I assumed it was enough to do a rvm use 2.1.5 and then touch restart to restart my rails server, but how can I check which version of ruby it's using ?)
What is wrong ?
EDIT
On my laptop, I am running ruby 2.1.5p273 (2014-11-13 revision 48405) [x64-mingw32]
On my production server, I am running ruby-2.1.5 [ i686 ]
I tried another library, libxml-xmlrpc, and I get the following error when running the same command:
Net::HTTPBadResponse: wrong status line: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"
But again, the same code is running fine with the default ruby xmlrpc client on my Windows + rubyx64 2.1.5, so I really don't get it!
Edit2 : I tried adding
#wiki.http_header_extra = { "accept-encoding" => "identity" }
But then I get a
Authorization failed. HTTP-Error: 401 Unauthorized
The first call #wiki.call("dokuwiki.login", "myUsr", "myPwd") worked, but apparently it failed to authenticate me (Of course I am still using the same login information that should work)
EDIT 3
After investigation, a successful login from any other computer than localhost will set a cookie like
#cookie="DokuWiki=[small string] ; [very big string]
Whereas if I do it on localhost :
I will write [...] for random strings
#cookie="[small string 2]=deleted; DokuWiki=[small string]; [very big string]"
So I have an extra variable info stored in my cookie, which is "[small string 2]=deleted;
I believe this is what makes my authentication fails. Anyone knows what this is ???
So this localhost connection was messing up with the cookie. Apparently, even the ruby library doesn't know why, and the "Wrong size" comes from this unexpected string [random string]=deleted added at the beginning of the cookie.
Unless someone can explain WHY such a string is added, I will accept my solution of simply adding
#wiki.http_header_extra = { "accept-encoding" => "identity" }
which removes the "Wrong size" error, then
if /deleted/.match(#wiki.cookie)
#wiki.cookie = #wiki.cookie.gsub(/.*deleted; /, '')
end
To remove the beginning of the cookie
I'm trying to login to Roundcube only the program won't let me.
I can login to the said account from the shell and mail is setup and working correctly on my server for user 'admin'. It's RC that is the problem. If I check my logs:
/usr/local/www/roundcube/logs/errors
they show:
[21-Sep-2013 17:19:02 +0100]: IMAP Error: Login failed for admin from ip.ip.ip.ip. Could not connect to ip.ip.ip.ip:143:
Connection refused in /usr/local/www/roundcube/program/lib/Roundcube/rcube_imap.php on line 184
(POST /roundcube/?_task=login&_action=login)
which doesn't give me many clues really, just leads me to:
public function connect($host, $user, $pass, $port=143, $use_ssl=null) {}
from
rcube_imap.php
Stuff I've tried, editing:
/usr/local/www/roundcube/config/main.inc.php
with:
// IMAP AUTH type (DIGEST-MD5, CRAM-MD5, LOGIN, PLAIN or null to use
// best server supported one)
//$rcmail_config['imap_auth_type'] = LOGIN;
$rcmail_config['imap_auth_type'] = null;
// Log IMAP conversation to <log_dir>/imap or to syslog
$rcmail_config['imap_debug'] = /var/log/imap;
With a failed login attempt
/var/log/imap
doesn't even get written to, leaving me no clues. I'm using dovecot and Sendmail on a FreeBSD box with full root access. It's not an incorrect username password combination for sure.
Several Googles on the string 'Roundcube: Connection to storage server failed' are fruitless.
EDIT:
I needed an entry in
/etc/rc.conf
dovecot_enable="YES"
Schoolboy error.
I had the same problem with a letsencrypt certificate and resolve it by disabling peer authentication:
$config['imap_conn_options'] = array(
'ssl' => array('verify_peer' => true, 'verfify_peer_name' => false),
'tls' => array('verify_peer' => true, 'verfify_peer_name' => false),
);
Afterwards you can set the connection string like this (starttls):
$config['default_host'] = 'tls://your-host.tld';
$config['default_port'] = '143';
$config['smtp_server'] = 'tls://your-host.tld';
$config['smtp_port'] = '25';
Or like this (ssl approach):
$config['default_host'] = 'ssl://your-host.tld';
$config['default_port'] = '993';
$config['smtp_server'] = 'ssl://your-host.tld';
$config['smtp_port'] = '587';
Make sure you use the fully qualified hostname of the certificate in the connection string (like your-host.tld) and not an internal hostname (like localhost).
Hope that helps someone else.
Change the maildir to whatever your system uses.
Change Dovecot mail_location setting to
mail_location = maildir:~/Mail
Change Postfix home_mailbox setting to
home_mailbox = Mail/
Restart services and away you go
Taken from this fedoraforum post
If you run fail2ban, then dovecot might get banned following failed Roundcube login attempts. This has happened to me twice already...
First, check if this is indeed the case:
sudo fail2ban-client status dovecot
If you get an output similar to this:
Status for the jail: dovecot
|- Filter
| |- Currently failed: 1
| |- Total failed: 8
| `- File list: /var/log/mail.log
`- Actions
|- Currently banned: 1
|- Total banned: 2
`- Banned IP list: X.X.X.X
i.e. the Currently banned number is higher than 0, then fail2ban was a bit overeager and you have to "unban" dovecot.
Run the fail2ban client in interactive mode:
sudo fail2ban-client -i
and at the fail2ban> prompt enter the following:
set dovecot unbanip X.X.X.X
where X.X.X.X is the IP address of your Dovecot server.
Exit from the interactive client and run sudo fail2ban-client status dovecot again. The Currently banned: field now should have a value of 0. What's more important, RoundCube should work again :-)
The issue is in your mail server.
Check your ports in your mail server and reset it (if necessary):
Port 25 (and 587) must be open for SMTP
Port 143 (and 993) must be open for IMAP
Port 110 must be open for POP3
Also open those ports in your firewall settings.
sudo dovecot should solve the problem.
If not restart dovecot
sudo service dovecot restart