ProFTPd MySQL setup - linux

I'm trying to install ProFTPd with MySQL on Ubuntu server 11.10 64-bit. But I cannot login, always showing 'Login Incorrect'
This is my sql.conf file:
# add the following lines to the file (don't need to remove comments from it)
DefaultRoot ~
# The passwords in MySQL are encrypted using CRYPT
SQLBackend mysql
SQLEngine on
SQLAuthTypes Plaintext Crypt
SQLAuthenticate users* groups*
# used to connect to the database
# databasename#host database_user user_password
SQLConnectInfo ftp#localhost proftpd password
# Here we tell ProFTPd the names of the database columns in the "usertable"
# we want it to interact with. Match the names with those in the db
SQLUserInfo ftpuser userid passwd uid gid homedir shell
# Here we tell ProFTPd the names of the database columns in the "grouptable"
# we want it to interact with. Again the names match with those in the db
SQLGroupInfo ftpgroup groupname gid members
# set min UID and GID - otherwise these are 999 each
SQLMinID 500
# create a user's home directory on demand if it doesn't exist
SQLHomedirOnDemand on
# Update count every time user logs in
SQLLog PASS updatecount
SQLNamedQuery updatecount UPDATE "count=count+1, accessed=now() WHERE userid='%u'" ftpuser
# Update modified everytime user uploads or deletes a file
SQLLog STOR,DELE modified
SQLNamedQuery modified UPDATE "modified=now() WHERE userid='%u'" ftpuser
# User quotas
# ===========
QuotaEngine on
QuotaDirectoryTally on
QuotaDisplayUnits Mb
QuotaShowQuotas on
SQLNamedQuery get-quota-limit SELECT "name, quota_type, per_session, limit_type, bytes_in_avail, bytes_out_avail, bytes_xfer_avail, files_in_avail, files_out_avail, files_xfer_avail FROM ftpquotalimits WHERE name = '%{0}' AND quota_type = '%{1}'"
SQLNamedQuery get-quota-tally SELECT "name, quota_type, bytes_in_used, bytes_out_used, bytes_xfer_used, files_in_used, files_out_used, files_xfer_used FROM ftpquotatallies WHERE name = '%{0}' AND quota_type = '%{1}'"
SQLNamedQuery update-quota-tally UPDATE "bytes_in_used = bytes_in_used + %{0}, bytes_out_used = bytes_out_used + %{1}, bytes_xfer_used = bytes_xfer_used + %{2}, files_in_used = files_in_used + %{3}, files_out_used = files_out_used + %{4}, files_xfer_used = files_xfer_used + %{5} WHERE name = '%{6}' AND quota_type = '%{7}'" ftpquotatallies
SQLNamedQuery insert-quota-tally INSERT "%{0}, %{1}, %{2}, %{3}, %{4}, %{5}, %{6}, %{7}" ftpquotatallies
QuotaLimitTable sql:/get-quota-limit
QuotaTallyTable sql:/get-quota-tally/update-quota-tally/insert-quota-tally
RootLogin off
RequireValidShell off
SQLNamedQuery userquota SELECT "IF ((SELECT (#availmbytes:=ROUND((`bytes_in_avail`/1048576),2)) FROM `ftpquotalimits` WHERE `name`='%u') = 0, \"No user quota applies.\", CONCAT(\"User quota: Used \", (SELECT (#usedmbytes:=ROUND((`bytes_in_used`/1048576),2)) FROM `ftpquotatallies` WHERE `name`='%u'), \"MB from \", #availmbytes, \"MB. You have \", ROUND(#availmbytes-#usedmbytes,2), \"MB available space.\"))"
SQLShowInfo LIST "226" "%{userquota}"
PassivePorts 60000 65000
is there anything wrong with those codes??
Does SQLConnectInfo username and password need quote??

maybe if you try to follow this manual.
Ubuntu 12:
https://www.digitalocean.com/community/tutorials/how-to-set-up-proftpd-with-a-mysql-backend-on-ubuntu-12-10
Ubuntu 14:
https://www.howtoforge.com/virtual-hosting-with-proftpd-and-mysql-incl-quota-on-ubuntu-14.04-lts-p2

Related

samba - check_account: Failed to convert SID S-1-5-21-1474423456-1456789349-1731688626-1665484 to a UID ([INET\jean])

My samba server was working fine until last week. I did a search all over the internet and tried the below and still no go.
My smb.conf:
[global]
workgroup = INET
server string = File on-Line
security = ADS
passdb backend = tdbsam
log level = 3
realm = inet.xyz.com
encrypt passwords = yes
unix extensions = no
wins server = 10.X.X.X 10.X.X.X
netbios name = sharefiles
template shell = /bin/bash
strict locking = no
min protocol = NT1
max protocol = SMB3_11
server signing = mandatory
client signing = mandatory
# I added the below after some Google search
idmap config INET : backend = rid
idmap config INET : base_rid = 0
idmap config INET : range = 10000-20000
================================================
On my windows machine - I do a //sharefiles
It asks me for my login and my login is not accepted.
In /var/log/messages - I get this error:
../../source3/auth/auth_util.c:1889(check_account)
Feb 15 16:31:55 sambaserver smbd[9354]: check_account: Failed to convert SID S-1-5-21-1474414563-1125766349-1731688626-161484 to a UID (dom_user[INET\jean])
Feb 15 16:31:55 sambaserver smbd[9356]: [2022/02/15 16:31:55.498012, 0] ../../source3/auth/auth_util.c:1889(check_account)
Feb 15 16:31:55 sambaserver smbd[9356]: check_account: Failed to convert SID S-1-5-21-1474414563-1125766349-1731688626-161484 to a UID (dom_user[INET\jean])
**SAMBA version:**
Samba version 4.10.16
Anyone seen this before? Thank you in advance!
Your range is too small, 161484 is larger than 20000, add a couple of zeros to 20000. You also need another line:
idmap config * : range = 3000-7999

authenticate a user from local linux host using python script

I want to authenticate a user from a local linux host using subprocess. I have used this code and i doubt login is the perfect command to do because login command prompts for password and I want to provide the password upfront. login man
If not login then is there any other linux command through which I can authenticate a local user ?
#!/usr/bin/python3
import subprocess
import cgi
print()
cred = cgi.FieldStorage()
username = cred.getvalue("user")
password = cred.getvalue("password")
# print(username)
# print(password)
cmd = f"echo {password} | sudo /usr/bin/login {username}"
# cmd = "ls -la"
print(cmd)
output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
print(output)
This is the output I am getting as of now.
CompletedProcess(args='echo ashu234 | sudo /usr/bin/login ashu', returncode=1, stdout='')
You can use pexpect. Unless you are running your script as root you will need to supply a password to sudo (as you will have to for any answer that uses sudo). To make the script more portable also supply a sudo user name but you could hard code this if using root. This code was written for Ubuntu 21.10 and may need the strings updating for other distributions. I think the code is self-explanatory, you spawn a process, interact with it and expect certain responses during exection.
import pexpect
sudo_user = 'whatever your sudo user name is'
sudo_password = "whatever your sudo user password is"
user_name = "whatever local user name is"
password = "whatever local user password is"
child = pexpect.spawn(f'/usr/bin/sudo /usr/bin/login {user_name}', encoding='utf-8')
child.expect_exact(f'[sudo] password for {sudo_user}: ')
child.sendline(sudo_password)
return_code = child.expect(['Sorry, try again', 'Password: '])
if return_code == 0:
print('Can\'t sudo')
print(child.after) # debug
child.kill(0)
else:
child.sendline(password)
return_code = child.expect(['Login incorrect', '[#\\$] '])
if return_code == 0:
print('Can\'t login')
print(child.after) # debug
child.kill(0)
elif return_code == 1:
print('Login OK.')
print('Shell command prompt', child.after)
For more detail see the docs https://pexpect.readthedocs.io/en/stable/overview.html

Run Python Script within Python & check if value is outputted - If statement

I have a Python3 script which basically runs through a list of Amazon AWS Account numbers (Uses Boto3), checks to see if their access keys are older than x number of days and report on it.
I'd like to make my report nice by checking to see if the output has a user(s) or not and output this into a file for SNS to email to me.
Here is the code I've already tried:
if not os.system("python3 ListUsersWithAccessKeysOlderThan90Days.py " + accountNumber):
print("No Content", file=reportName)
else:
print("Content", file=reportName)
I've already tried this too:
if os.system("python3 ListUsersWithAccessKeysOlderThan90Days.py " + accountNumber) == " ":
print("No Content", file=reportName)
else:
print("Content", file=reportName)
But I only seem to get this in my output file:
Running on account accountNumber - accountLabel - accountEnvironment
No Content
Running on account accountNumber - accountLabel - accountEnvironment
No Content
Running on account accountNumber - accountLabel - accountEnvironment
No Content
Ideally, I'd like it to look like this:
Running on account accountNumber - accountLabel - accountEnvironment
No Content
Running on account accountNumber - accountLabel - accountEnvironment
Content
Running on account accountNumber - accountLabel - accountEnvironment
No Content
No Content = No access keys need rotating.
Content = User needs their key rotating.
I can achieve this in Bash, but I wouldn't mind trying to get it working in Python3.
Here is my Bash example:
if [[ -z "$(python3 ListUsersWithAccessKeysOlderThan90Days.py ${ACCOUNT})" ]]; then
echo -e "$ACCOUNT ($LABEL) is up to date no need to report\n" >> $REPORT
else
echo -e "$ACCOUNT Need keys rotating" >> $REPORT
fi
Any help would be most appreciated.
Thanks,
You can get the status of IAM users and credentials from the AWS Credentials Report. That would probably satisfy most needs.
If you prefer Python, then I've written a basic script that can be used to print out all IAM users in an account whose access keys are over 90 days old (regardless of when they last used these keys).
import sys
import boto3
from datetime import datetime, timedelta, timezone
DAYS = 90
iam = boto3.client('iam')
sts = boto3.client('sts')
identity = sts.get_caller_identity()
account = identity['Account']
header_printed = False
count = 0
today = datetime.now(timezone.utc)
# Get all IAM users in this AWS account
for user in iam.list_users()['Users']:
arn = user['Arn']
username = user['UserName']
# Get all access keys for this IAM user
keys = iam.list_access_keys(UserName=username)
# Test each key's age and print those that are too old
for key in keys['AccessKeyMetadata']:
akid = key['AccessKeyId']
created = key['CreateDate']
created_delta = today - created
# if this access key is older than DAYS
if created + timedelta(days=DAYS) < today:
count += 1
response = iam.get_access_key_last_used(AccessKeyId=akid)
akid_last_used = response['AccessKeyLastUsed']
if not header_printed:
header_printed = True
print(f'Account, Username, Access Key, Age, Last Used')
print(f'{account}, {username}, {akid}, {created_delta.days} ', end = '')
# Only keys that have actually been used will have last used date
if 'LastUsedDate' in akid_last_used:
last_used = akid_last_used['LastUsedDate']
last_used_delta = today - last_used
print(flast_used_delta.days)
else:
print('none')
sys.exit(count)
This will print out a list of access keys over 90 days, in a CSV format. For example:
Account, Username, Access Key, Age, Last Used
123456784321, james, AKIAJ7PL4POLWNEXAMPLE, 91, 1
123456784321, frank, AKIAL2CV9LKWEXAMPLE, 200, 100
123456784321, mary, AKIAYTWHD3BNMLEXAMPLE, 97, none
The Age is how many days old the access key is. The Last Used is how many days it has been since the credential was last used. Hope this proves to be helpful.
The script's exit code is the count of keys older than 90 days, so you can use this exit code in a shell script to decide what to do next. For example:
#!/bin/bash
python3 scripts_older_than_90days.py > oldkeys.csv
count=$?
if [ $count -eq 0 ]
then
echo "All access keys good"
else
echo "Count of old keys" $count
fi

How to authenticate LDAP properly?

I am working on a project that must use LDAP authentication. I am using the server at ldap.forumsys.com after finding the link on Stack Overflow to practice before adding to my Flask application.
If I run the ldapsearch bash command inside of my python code I get a whole bunch of usernames (Tesla etc...) and their associated data (there are no password hashes though). I am able to extract the usernames/user-data as shown here:
username = request.form['username']
password = request.form['password']
cmd = "ldapsearch -h ldap.forumsys.com -D cn=read-only-admin,dc=example,dc=com -w" + os.environ['LDAP_PWD'] + " -b dc=example,dc=com"
ldap_query = os.popen(cmd).read()
user_str = re.sub("\n", "", ldap_query)
users = user_str.split("#")
user_data = ""
for line in users:
if username in line:
user_data = line
break
But then I realized that I LDAP is not the same as a database. I was hoping to find password hashes that I could use to authenticate a user's login information.
So then I tried the python-ldap3 module:
>>> conn = Connection(server, 'uid=tesla,dc=example,dc=com', 'password', auto_bind=True)
>>> conn.bound
True
>>> conn.entries
[]
Unfortunately I can't seem to get any data returned in the list after calling conn.entries.
I can see that the ldap3 module binded the connection. Does the ldapsearch command bind as well? If there are no password hashes, how should I authenticate the username/password entered by the user on the client side?
Thank you all very much.
If the statement...
conn.bound == True
Then the connection has been authenticated via LDAP

How to disable Create Project permission for users by default in GitLab?

I am using the Omnibus GitLab CE system with LDAP authentication.
Because of LDAP authentication, anyone in my company can sign in to GitLab and a new GitLab user account associated with this user is created (according to my understanding).
I want to modify it so that by default this new user (who can automatically sign in based on his LDAP credentials) cannot create new projects.
Then, I as the admin, will probably handle most new project creation.
I might give the Create Project permission to a few special users.
In newer versions of GitLab >= v7.8 …
This is not a setting in config/gitlab.yml but rather in the GUI for admins.
Simply navigate to https://___[your GitLab URL]___/admin/application_settings/general#js-account-settings, and set Default projects limit to 0.
You can then access individual users's project limit at https://___[your GitLab URL]___/admin/users.
See GitLab's update docs for more settings changed between v7.7 and v7.8.
git diff origin/7-7-stable:config/gitlab.yml.example origin/7-8-stable:config/gitlab.yml.example
For all new users:
Refer to Nick Merrill answer.
For all existing users:
This is the best and quick method to make changes to projects limits:
$ gitlab-rails runner "User.where(projects_limit: 10).each { |u| u.projects_limit = 0; u.save }"
( Update: This applies to versions <= 7.7:)
The default permissions are set in gitlab.yml
In omnibus, that is /opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
Look for
## User settings
default_projects_limit: 10
# default_can_create_group: false # default: true
Setting default_projects_limit to zero, and default_can_create_group to false may be what you want.
Then an admin can change the limits for individual users.
Update:
This setting was included in the admin GUI in version 7.8 (see answer by #Nick M). At least with Omnibus on Centos7 an upgrade retains the setting.
Note that the setting default_can_create_group is still in gitlab.yml.
Here's my quick-and-dirty Python script which you can use in case you already have some users created and want to change all your existing users to make them unable to create projects on their own:
#!/usr/bin/env python
import requests
import json
gitlab_url = "https://<your_gitlab_host_and_domain>/api/v3"
headers = {'PRIVATE-TOKEN': '<private_token_of_a_user_with_admin_rights>'}
def set_user_projects_limit_to_zero (user):
user_id = str(user['id'])
put = requests.put(gitlab_url + "/users/" + user_id + "?projects_limit=0", headers=headers)
if put.status_code != 200:
print "!!! change failed with user id=%s, status code=%s" % (user_id, put.status_code)
exit(1)
else:
print "user with id=%s changed!" % user_id
users_processed = 0
page_no = 1
total_pages = 1
print "processing 1st page of users..."
while page_no <= total_pages:
users = requests.get(gitlab_url + "/users?page=" + str(page_no), headers=headers)
total_pages = int(users.headers['X-Total-Pages'])
for user in users.json():
set_user_projects_limit_to_zero(user)
users_processed = users_processed + 1
print "processed page %s/%s..." % (page_no, total_pages)
page_no = page_no + 1
print "no of processed users=%s" % users_processed
Tested & working with GitLab CE 8.4.1 052b38d, YMMV.

Resources