Outils pour utilisateurs

Outils du site


blog

Changer le umask pour un groupe ou plusieurs groupe en SFTP

Voir http://serverfault.com/questions/257711/openssh-5-3-setting-umask-for-sftp-chroot-env-dosent-work-at-all

En général la bonne méthode et d'utiliser les droits GNU/Linux avec les ACL Voir partage_dossier_acl_umask

Voici les étapes :

  • On crée un petit script /usr/local/bin/sftpwrapper.sh
  • On modifie le fichier sshd_config pour appeler notre script à la place de sftp-server
  • On ajoute notre ou nos groupe(s) dans la variable GROUP_007
  • On adapte le script en remplacant tous les 007 par le umask désiré.
  • On positionne les bons droits au script.
  • On redémarre le serveur SSH.

NB : Le changement du umask peut aussi se faire coté client SFTP. Par exemple pour WinSCP http://winscp.net/eng/docs/ui_transfer_custom#upload_options

NB : Sur une debian le changement du umask par défaut coté serveur peut-être définie globalement dans /etc/login.defs champs UMASK Voir également man pam_umask

NB : Si l'accès à un shell n'est pas souhaité, alors l'outil idéal est rssh (Restricted Shell for scp, sftp, rsync, svn…). Il gère également l'umask personnalisé.

NB : Si votre préoccupation est uniquement la sécurité, il est plus plus propre de monter un serveur SFTP qui ecoute sur un port dédié et de garder l'accès SSH que en interne pour l'administration. Voir notre tuto monter-un-serveur-sftp-ssh qui se base sur proftpd pour faire du SFTP.

/usr/local/bin/sftpwrapper.sh

#! /bin/bash
 
# Modifier votre sshd_config de la manière suivante : 
#'Subsystem sftp /usr/lib/openssh/sftp-server' => 'Subsystem sftp /usr/local/bin/sftpwrapper.sh'
 
# TODO : Lecture seul avec sftp-server -R et un groupe sftp_ro
 
 
# Groupe d'utilisateur qui aurons un "UMASK 007". Les fichiers crées auront les droits :
# -rw-rw----
GROUP_007='groupe1 groupe2'
 
REGEX_007=$(echo ${GROUP_007:-nobody}  | tr ' ' '|' | sed -e 's/^/\\b/' -e 's/$/\\b/' -e 's/|/\\b|\\b/')
groups  | tr "\n" " " | grep "$REGEX_007" > /dev/null && umask 007
 
/usr/lib/openssh/sftp-server $*

/etc/ssh/sshd_config

#'Subsystem sftp /usr/lib/openssh/sftp-server'
'Subsystem sftp /usr/local/bin/sftpwrapper.sh'
chown root:root /usr/local/bin/sftpwrapper.sh
chmod 755 /usr/local/bin/sftpwrapper.sh
2025/03/24 15:06

Access SFTP sans shell

Voir :

Voir également :

  • rssh
  • mysecureshell

Ou pour un acces exclusif en SFTP :

#usermod -s /usr/lib/openssh/sftp-server username
echo "/usr/lib/openssh/sftp-server" >> /etc/shells

Source : http://www.debian-administration.org/article/94/How_to_restrict_users_to_SFTP_only_instead_of_SSH


Comme bash figure dans /etc/shells, c'est ok

/usr/local/bin/sftp.sh

#! /bin/bash
/usr/lib/openssh/sftp-server -l INFO
chmod +x /usr/local/bin/sftp.sh

Tout est log dans /var/log/auth.log

/etc/passwd

test:x:1003:1003:,,,:/home/test:/usr/local/bin/sftp.sh

Notes MySecureShell

/etc/ssh/sftp_config

<Default>
        #Home                   /home/$USER     #overrite home of the user but if you want you can use
                                        #  environment variable (ie: Home /home/$USER)
        #LimitConnection         10      #max connection for the server sftp
        #LimitConnectionByUser   1       #max connection for the account
        #LimitConnectionByIP     2       #max connection by ip for the account
        LimitConnection         10      #max connection for the server sftp
        LimitConnectionByUser   5       #max connection for the account
        LimitConnectionByIP     10       #max connection by ip for the account
 
</Default>

/etc/shells

/usr/bin/mysecureshell
/etc/init.d/mysecureshell restart
usermod -s /usr/bin/mysecureshell sftpuser
# sftp-verif

Verifing file rights of /usr/bin/mysecureshell                       [ FAILED ]
Rights problems have been detected 0755 and should be 4755
Do you want to repair /usr/bin/mysecureshell file rights ? (Y/n)
Debug

Voir : /var/log/sftp-server.log

Autres

useradd sftp_download -s /sbin/nologin -
passwd sftp_download
mkdir /download
# override default of no subsystems
#Subsystem      sftp    /usr/lib/openssh/sftp-server
Subsystem       sftp    internal-sftp

Match group sftponly
     ChrootDirectory /upload
     X11Forwarding no
     AllowTcpForwarding no
     AllowAgentForwarding no
     ForceCommand internal-sftp -d /%u
	 

PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
# PasswordAuthentication no
2025/03/24 15:06

Serveur web partage de fichier en une ligne avec Python

Voir aussi :

Python2 :

python -m SimpleHTTPServer 9000

Python3 :

python3 -m http.server --bind 127.0.0.1 9000
2025/03/24 15:06

Zabbix script python monitor unmonitor autoadd host

Ce script permet :

  • l'ajout automatique d'un nouveau hôte à superviser
  • La désactivation automatique de la supervision d'un hôte

Il prend comme paramètre le nom de l'hôte ou l'adresse IP.

Il servait au “cloud”, dans un contexte de création automatique de VM et destruction automatique après traitement.

zbxunmon.py

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# License: GNU GPL
 
""" Switch Zabbix status to 'Monitored' or 'Not monitored'
zbxunmon.ini
[SERVER]
URL=https://acme.fr/zabbix
USER=api
PWD=P@ssw0rd
"""
 
import socket
import argparse
import configparser
from sys import argv, exit, stderr
from os import environ, path
 
import zabbix_client
 
ficconf=argv[0]
ficconf=ficconf.replace('.py', '')
ficconf=ficconf + '.ini' # Work even if this script's name isn't ended by ".py"
 
config = configparser.ConfigParser()
config.read(ficconf)
zbxconf     = config['SERVER']
zabbix_url  = config['SERVER']['URL']
zabbix_user = zbxconf.get('USER')
zabbix_pwd  = zbxconf.get('PWD')
try:
    environ['http_proxy']=environ['https_proxy']=zbxconf.get('HTTP_PROXY')
except TypeError:
    pass
 
 
# Zabbix 'status' code
MONITORED='0'
NOT_MONITORED='1'
 
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--enable',  action='store_true', help='Enable')
parser.add_argument('-d', '--disable', action='store_true', help='Disable')
parser.add_argument('-i', '--ip',   help='IP Address')
parser.add_argument('-n', '--name', help='Hostname')
args = parser.parse_args()
 
def die(exitcode, *objs):
    """ print on STDERR
    """
    print(*objs, file=stderr)
    try:
        s
    except NameError:
        pass
    else: # If no exception occured, do :
        s.user.logout()
    exit(exitcode)
 
 
 
if (not args.ip and not args.name) and (not args.enable and not args.disable):
    die(1, "{0}: missing arguments\nTry '{0} -h' for more information.".format(argv[0]))
 
ip = args.ip
hostname=args.name
 
def zbx_ip2hostid(s, ip):
    hostinterface=s.hostinterface.get(filter={'ip':ip}, output=['hostid'])
    if len(hostinterface) == 1:
        hostinterface=hostinterface[0]
        return(hostinterface['hostid'])
    else:
        die(7, 'IP not found')
 
def zbx_host2hostid(s, host):
    host=s.host.get(filter={'host':host}, output=['hostid'])
    if len(host) == 1:
        host=host[0]
        return(host['hostid'])
    else:
        die(6, 'Host not found')
 
def zbx_getstatus(hostid):
    host=s.host.get(hostids=hostid, output=['status'])
    if len(host) == 1:
        host=host[0]
        return(host['status'])
    else:
        die(8, "Can't get status")
 
 
s = zabbix_client.ZabbixServerProxy(zabbix_url)
s.user.login(user=zabbix_user, password=zabbix_pwd)
 
if ip:
    hostid=zbx_ip2hostid(s, ip)
elif hostname:
    hostid=zbx_host2hostid(s, hostname)
else:
    die(2, 'Fatal error, ip or hostname need to be provide !')
 
 
# Change Monitor status
if args.disable :
    s.host.update({'hostid': hostid, 'status': NOT_MONITORED})
    if zbx_getstatus(hostid) != NOT_MONITORED:
        die(4, 'Fail to change status to NOT_MONITORED')
elif args.enable :
    s.host.update({'hostid': hostid, 'status': MONITORED})
    if zbx_getstatus(hostid) != MONITORED:
        die(4, 'Fail to change status to MONITORED')
else:
    die(5, 'Fatal error, autodestruction')
 
 
s.user.logout()

zbxunmon.ini

[SERVER]
# If HTTP is used instead of HTTPS password will be sent in clear !
URL=https://acme.fr/zabbix
USER=api
PWD=P@ssw0rd
 
# For GNU/Linux : Empty value for no proxy. Comment this line for default value (env http_proxy or https_proxy)
HTTP_PROXY=

requirements.txt

zabbix-client>=0.1.1
2025/03/24 15:06

Zabbix External Check - Script lancés coté serveur

Exemple supervision date expiration certificat

NB : pour que les modif soient prises en compte il fait attendre. Le fait de redémarer le service zabbix-server n'est pas suffisant

/etc/zabbix/zabbix_server.conf

ExternalScripts=/etc/zabbix/externalscripts
usermod -s bash zabbix
mkdir /etc/zabbix/externalscripts
service zabbix-server restart

/etc/zabbix/externalscripts/ssl-cert-check-zabbixwrap.sh

#! /bin/bash
 
ssl-cert-check $* |sed -e 's/^.*days=//

Create item with key field : ssl-cert-check-zabbixwrap.sh[“-s 171.33.77.65 -p 443”]

En cas de pb

Configuration / Hosts / Items Colone “Error”, Survol de la souris pour afficher l'erreur.

et

tail -F /var/log/zabbix-server/zabbix_server.log
2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki