def get_keychain(): proc = shLaunch('uname -n') p1 = re.compile('\n') out = p1.split(proc.out) if os.path.exists('/root/.keychain/' + out[0] + '-sh'): f = open('/root/.keychain/' + out[0] + '-sh', 'r') file = f.read() lines = p1.split(file) proc = shLaunch('env ' + lines[0]) return proc.out return ''
def setAnonPath(self,pth,maxuser): if(pth != 'remove'): rt = shLaunch('[ -d '+ pth + ' ]') if rt.exitCode != 0: return 1 rt = shLaunch("cat /etc/proftpd.conf | grep -E '^<Anonymous '") if(rt.exitCode != 0): #if <Anonymous conf do not exists in file create it fh = open('/etc/proftpd.conf','a') fh.write('<Anonymous ' + pth +' >\n') fh.write('\t# Allow logins if they are disabled above.\n') fh.write('\t<Limit LOGIN>\n') fh.write('\t\tAllowAll\n') fh.write('\t</Limit>\n') fh.write('\n') fh.write('\t# Maximum clients with message\n') fh.write('\tMaxClients\t\t\t'+ maxuser +' "Sorry, max %m users -- try again later"\n') fh.write('\n') fh.write('\tUser\t\t\tftp\n') fh.write('\tGroup\t\t\tftp\n') fh.write('\t# We want clients to be able to login with "anonymous" as well as "ftp"\n') fh.write('\tUserAlias\t\t\tanonymous\tftp\n') fh.write('\tRequireValidShell\t\t\toff\n') fh.write('\n') fh.write('\t# Limit WRITE everywhere in the anonymous chroot\n') fh.write('\t<Limit WRITE>\n') fh.write('\t\tDenyAll\n') fh.write('\t</Limit>\n') fh.write('</Anonymous>\n') fh.close() else: #if exists just change the path self.replaceConf('/etc/proftpd.conf','^<Anonymous',' ' + pth +' >\n') self.replaceConf('/etc/proftpd.conf','\tMaxClients', ' ' + maxuser + ' "Sorry, max %m users -- try again later"\n') # remove anonymous lines bellow <Anonymous.. until </Anonymous> else: aux = 0 #control variable to write or not in file r = open("/etc/proftpd.conf") lines = r.readlines() r.close() w = open("/etc/proftpd.conf",'w') w.writelines(''); #clean up .conf file before write for word in lines: if(re.match('^\<Anonymous*', word) is not None):#if true do not write aux=1 if(aux == 0): w.write(word) if(re.match('^\</Anonymous*', word) is not None): # if true write to file aux=0 w.close() shLaunch('service proftpd restart') return 0
def get_keychain(): proc = shLaunch('uname -n') p1 = re.compile('\n') out = p1.split(proc.out) if os.path.exists('/root/.keychain/'+out[0]+'-sh'): f=open('/root/.keychain/'+out[0]+'-sh', 'r') file = f.read() lines = p1.split(file) proc = shLaunch('env '+lines[0]) return proc.out return ''
def msc_exec(command): proc = shLaunch(command) return_var = proc.exitCode stdout = proc.out stderr = proc.err output = re.compile('\n').split(stdout) return [output, return_var, stdout, stderr]
def msc_exec(command): proc = shLaunch(command) return_var = proc.exitCode stdout = proc.out stderr = proc.err output = re.compile("\n").split(stdout) return [output, return_var, stdout, stderr]
def ftpGetUsers(self): ret = shLaunch("find /home -maxdepth 2 -name 'share_ftp' -type d | cut -d / -f 3") users = ret.out users = users.split('\n') users = [x for x in users if x] if len(users) == 0: return 0 else: return users
def makeSambaGroupBlocking(self, group): """ Transform a POSIX group as a SAMBA group. It adds in the LDAP the necessary attributes to the group. This code blocks the twisted reactor until the command terminates. @param group: the group name @type group: str @return: the SAMBA net process exit code """ return shLaunch(self._getMakeSambaGroupCommand(group)).exitCode
def msc_ssh(user, ip_addr, command): # TODO better path for annotate_output # -tt forces tty allocation so that signals like SIGINT will be properly sent to the remote host opts = "-T -R30080:127.0.0.1:80 -o StrictHostKeyChecking=no -o Batchmode=yes -o PasswordAuthentication=no" ssh_command = "%s %s ssh %s %s@%s \"%s\"" % (mmc.plugins.msc.MscConfig("msc").annotatepath, mmc.plugins.msc.config.get_keychain(), opts, user, ip_addr, command) logging.getLogger().debug("executing |%s|" % ssh_command) proc = shLaunch(ssh_command) return_var = proc.exitCode stdout = proc.out stderr = proc.err # Disabled (FIXME: MAX_LOG_SIZE should be set in msc.ini) # if len(stdout) > MAX_LOG_SIZE: # stdout = stdout[0:MAX_LOG_SIZE] # stdout += "=== LOG MEMORY LIMIT ===\n" return [ssh_command, stdout, return_var, stdout, stderr, -1]
def msc_ssh(user, ip_addr, command): # TODO better path for annotate_output # -tt forces tty allocation so that signals like SIGINT will be properly sent to the remote host opts = "-T -R30080:127.0.0.1:80 -o StrictHostKeyChecking=no -o Batchmode=yes -o PasswordAuthentication=no" ssh_command = "%s %s ssh %s %s@%s \"%s\"" % ( mmc.plugins.msc.MscConfig("msc").annotatepath, mmc.plugins.msc.config.get_keychain(), opts, user, ip_addr, command) logging.getLogger().debug("executing |%s|" % ssh_command) proc = shLaunch(ssh_command) return_var = proc.exitCode stdout = proc.out stderr = proc.err # Disabled (FIXME: MAX_LOG_SIZE should be set in msc.ini) # if len(stdout) > MAX_LOG_SIZE: # stdout = stdout[0:MAX_LOG_SIZE] # stdout += "=== LOG MEMORY LIMIT ===\n" return [ssh_command, stdout, return_var, stdout, stderr, -1]
def msc_scp(user, ip_addr, source, destination): opts = "-o Batchmode=yes -o StrictHostKeyChecking=no -r" destination = re.compile(' ').sub('\\ ', destination) scp_command = "%s %s scp %s '%s' %s@%s:%s 2>&1" % (\ mmc.plugins.msc.MscConfig("msc").annotatepath, mmc.plugins.msc.config.get_keychain(), opts, source, user, ip_addr, destination ) logging.getLogger().debug("executing |%s|" % scp_command) proc = shLaunch(scp_command) return_var = proc.exitCode stdout = proc.out stderr = proc.err output = stdout return [scp_command, output, return_var, stdout, stderr, -1]
def msc_scp(user, ip_addr, source, destination): opts = "-o Batchmode=yes -o StrictHostKeyChecking=no -r" destination = re.compile(" ").sub("\\ ", destination) scp_command = "%s %s scp %s '%s' %s@%s:%s 2>&1" % ( mmc.plugins.msc.MscConfig("msc").annotatepath, mmc.plugins.msc.config.get_keychain(), opts, source, user, ip_addr, destination, ) logging.getLogger().debug("executing |%s|" % scp_command) proc = shLaunch(scp_command) return_var = proc.exitCode stdout = proc.out stderr = proc.err output = stdout return [scp_command, output, return_var, stdout, stderr, -1]
def validate(self, conffile = "/etc/samba/smb.conf"): """ Validate SAMBA configuration file with testparm. Try also to parse the configuration with configObj @return: Return True if smb.conf has been validated, else return False """ cmd = shLaunch("/usr/bin/testparm -s %s" % conffile) if cmd.exitCode: ret = False elif "Unknown" in cmd.err or "ERROR:" in cmd.err or "Ignoring badly formed line" in cmd.err: ret = False else: ret = True try: ConfigObj(conffile, interpolation=False, list_values=False) except ParseError: ret = False return ret
def validate(self, conffile="/etc/samba/smb.conf"): """ Validate SAMBA configuration file with testparm. Try also to parse the configuration with configObj @return: Return True if smb.conf has been validated, else return False """ cmd = shLaunch("/usr/bin/testparm -s %s" % conffile) if cmd.exitCode: ret = False elif "Unknown" in cmd.err or "ERROR:" in cmd.err or "Ignoring badly formed line" in cmd.err: ret = False else: ret = True try: ConfigObj(conffile, interpolation=False, list_values=False) except ParseError: ret = False return ret
def validate(self, conf_file): """ Validate SAMBA configuration file with testparm. Try also to parse the configuration with ConfigObj. @return: Whether smb.conf has been validated or not @rtype: boolean """ cmd = shLaunch("%s/bin/testparm -s %s" % (self.prefix, shellquote(conf_file))) if cmd.exitCode: ret = False elif ("Unknown" in cmd.err or "ERROR:" in cmd.err or "Ignoring badly formed line" in cmd.err): ret = False else: ret = True try: ConfigObj(conf_file, interpolation=False, list_values=False) except ParseError: ret = False return ret
def activate(): config = FtpConfig("ftp") ldapconf = LdapConfig("base") logger = logging.getLogger() if config.disabled: ret = shLaunch("service proftpd status") if ret.exitCode == 0: shLaunch("service proftpd stop") logger.warning("Plugin ftp: disabled by configuration.") return False ret = shLaunch("rpm -qa | grep -E '^proftpd-([0-9]\.)+.*'") if ret.exitCode != 0: logger.warning("Plugin ftp: proftpd package not installed, trying to install now...") ret = shLaunch("urpmi proftp --auto --force") if ret.exitCode != 0: logger.error("Plugin ftp: could not install proftp package as requirement for this module") return False ret = shLaunch("rpm -qa | grep '^proftpd-mod_ldap'") if ret.exitCode != 0: logger.warning("Plugin ftp: proftpd-mod_ldap package not installed, trying to install now...") ret = shLaunch("urpmi proftpd-mod_ldap --auto --force") if ret.exitCode != 0: logger.error("Plugin ftp: could not install proftpd-mod_ldap package as requirement for this module") return False #open port for FTP in shorewall plugin ret = shLaunch("service shorewall status") if ret.exitCode != 1:#shorewall service exists then... ret = shLaunch("cat /etc/shorewall/rules | grep -P 'FTP/ACCEPT\tlan[0-9]+\tfw'") if ret.exitCode != 0:#add rule for all vlans and lans if it not exists already logger.warning("Plugin ftp: Unblocking port 21 in shorewall rules...") shLaunch("mss-add-shorewall-rule -a FTP/ACCEPT -t lan") shLaunch("service shorewall restart") #test if ldap module config exists, if not create one if (not exists("/etc/proftpd.d")): mkdir("/etc/proftpd.d") ret = shLaunch("ls /etc/proftpd.d/*ldap*") if (ret.exitCode != 0): fh = open("/etc/proftpd.d/13_mod_ldap.conf", "w") fh.write("LoadModule mod_ldap.c\n") fh.close() #test if config file exists, if not create a default one if (not exists("/etc/proftpd.conf")): logger.warning("Plugin ftp: could not find configuration file to ftp in /etc/proftpd.conf, creating it..") fh = open("/etc/proftpd.conf", "w") fh.write('#\n') fh.write('# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file.\n') fh.write('# To really apply changes reload proftpd after modifications.\n') fh.write('# \n') fh.write('\n') fh.write('# Includes DSO modules\n') fh.write('Include /etc/proftpd.d/*.conf\n') fh.write('\n') fh.write('# This is the directory where DSO modules resides\n') fh.write('\n') fh.write('ModulePath /usr/lib64/proftpd\n') fh.write('\n') fh.write('# Allow only user root to load and unload modules, but allow everyone\n') fh.write('# to see which modules have been loaded\n') fh.write('\n') fh.write('ModuleControlsACLs insmod,rmmod allow user root\n') fh.write('ModuleControlsACLs lsmod allow user *\n') fh.write('\n') fh.write('ServerName "Default MBS-FTP Installation"\n') fh.write('ServerType standalone\n') fh.write('DeferWelcome off\n') fh.write('\n') fh.write('MultilineRFC2228 on\n') fh.write('DefaultServer on\n') fh.write('ShowSymlinks on\n') fh.write('\n') fh.write('TimeoutNoTransfer 600\n') fh.write('TimeoutStalled 600\n') fh.write('TimeoutIdle 1200\n') fh.write('\n') fh.write('DisplayLogin welcome.msg\n') fh.write('DisplayChdir .message\n') fh.write('ListOptions "-l"\n') fh.write('DenyFilter \*.*/\n') fh.write('UseIPv6 Off\n') fh.write('\n') fh.write('# Allow FTP resuming.\n') fh.write('# Remember to set to off if you have an incoming ftp for upload.\n') fh.write('AllowStoreRestart on\n') fh.write('\n') fh.write('# Port 21 is the standard FTP port.\n') fh.write('Port 21\n') fh.write('\n') fh.write('# In some cases you have to specify passive ports range to by-pass\n') fh.write('# firewall limitations. Ephemeral ports can be used for that, but\n') fh.write('# feel free to use a more narrow range.\n') fh.write('#PassivePorts 49152 65534\n') fh.write('\n') fh.write('# To prevent DoS attacks, set the maximum number of child processes\n') fh.write('# to 30. If you need to allow more than 30 concurrent connections\n') fh.write('# at once, simply increase this value. Note that this ONLY works\n') fh.write('# in standalone mode, in inetd mode you should use an inetd server\n') fh.write('# that allows you to limit maximum number of processes per service\n') fh.write('# (such as xinetd)\n') fh.write('MaxInstances 30\n') fh.write('\n') fh.write('# Set the user and group under which the server will run.\n') fh.write('User nobody\n') fh.write('Group nogroup\n') fh.write('\n') fh.write('# Umask 022 is a good standard umask to prevent new files and dirs\n') fh.write('# (second parm) from being group and world writable.\n') fh.write('Umask 022 022\n') fh.write('\n') fh.write('# To cause every FTP user to be "jailed" (chrooted) into their home\n') fh.write('# directory, uncomment this line.\n') fh.write('DefaultRoot ~/share_ftp/\n') fh.write('\n') fh.write('# Normally, we want files to be overwriteable.\n') fh.write('AllowOverwrite on\n') fh.write('\n') fh.write('# Uncomment this if you are using NIS or LDAP to retrieve passwords:\n') fh.write('PersistentPasswd off\n') fh.write('\n') fh.write('# Be warned: use of this directive impacts CPU average load!\n') fh.write('#\n') fh.write('# Uncomment this if you like to see progress and transfer rate with ftpwho\n') fh.write('# in downloads. That is not needed for uploads rates.\n') fh.write('#UseSendFile off\n') fh.write('\n') fh.write('TransferLog /var/log/proftpd/proftpd.log\n') fh.write('SystemLog /var/log/proftpd/proftpd.log\n') fh.write('\n') fh.write('<IfModule mod_tls.c>\n') fh.write(' TLSEngine off\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('<IfModule mod_quota.c>\n') fh.write(' QuotaEngine on\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('<IfModule mod_ratio.c>\n') fh.write(' Ratios on\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('# Delay engine reduces impact of the so-called Timing Attack described in\n') fh.write('# http://security.lss.hr/index.php?page=details&ID=LSS-2004-10-02\n') fh.write('# It is on by default. \n') fh.write('<IfModule mod_delay.c>\n') fh.write(' DelayEngine on\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('<IfModule mod_ctrls.c>\n') fh.write(' ControlsEngine on\n') fh.write(' ControlsMaxClients 2\n') fh.write(' ControlsLog /var/log/proftpd/controls.log\n') fh.write(' ControlsInterval 5\n') fh.write(' ControlsSocket /var/run/proftpd/proftpd.sock\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('<IfModule mod_ctrls_admin.c>\n') fh.write(' AdminControlsEngine on\n') fh.write('</IfModule>\n') fh.write('\n') fh.write('# Bar use of SITE CHMOD by default\n') fh.write('<Limit SITE_CHMOD>\n') fh.write(' DenyAll\n') fh.write('</Limit>\n') fh.write('\n') fh.close() #jail all users to their home as default ret = shLaunch("grep '^#DefaultRoot.*' /etc/proftpd.conf") if ret.exitCode == 0: Ftp().setConf('#DefaultRoot','~/share_ftp/') else: ret = shLaunch("grep '^DefaultRoot.*' /etc/proftpd.conf") if ret.exitCode != 0: Ftp().setConf('#DefaultRoot','~/share_ftp/') else:# check if the paramters is ~/share_ftp and not ~ ret = shLaunch("grep '~/share_ftp/' /etc/proftpd.conf") if ret.exitCode != 0: Ftp().setConf('DefaultRoot','~/share_ftp/') #set-up ldap authentication for user in FTP ret = shLaunch("grep '^<IfModule mod_ldap.c>' /etc/proftpd.conf") if(ret.exitCode != 0): fh = open("/etc/proftpd.conf", "a") fh.write("<IfModule mod_ldap.c>\n") fh.write("\tLDAPServer ldap://"+ ldapconf.host +"/??sub\n") fh.write('\tLDAPDNInfo "'+ ldapconf.root +'" "' + ldapconf.passw +'"\n') fh.write('\tLDAPDoAuth on "' + ldapconf.userdn +'" (&(uid=%v)(objectclass=posixAccount))\n') fh.write('\tLDAPDoUIDLookups on "' + ldapconf.userdn +'"\n') fh.write('\tLDAPDoGIDLookups on "'+ ldapconf.groupdn +'"\n') fh.write("</IfModule>\n") fh.close() ret = shLaunch("service proftpd restart") return True
def isEnabled(self,pattern): ret = shLaunch("grep -E '"+ pattern +"' /etc/proftpd.conf") if(ret.exitCode == 0): #its enabled return 1 else:# its not return 0
def getConf(self, param): param = param.translate(None, '^$?*') ret = shLaunch("grep '" + param + "' /etc/proftpd.conf | sed 's/"+ param +"[\\t| |\\n]*//g'") ret.out = ret.out.replace('\n', '') ret.out = ret.out.replace('"', '') return ret.out
def setConf(self, param, key): #php can pass or not some key values, if not do nothing if key: if(param.startswith("#")):#to enable/disable this kind of parameter has to uncomment or comment then do this param = param[1:] #remove flag '#' rt1 = shLaunch("grep '^#"+ param +"' /etc/proftpd.conf") rt2 = shLaunch("grep '^"+ param +"' /etc/proftpd.conf") if(rt1.exitCode == 0): shLaunch("sed -i 's,^#" + param +".*,"+ param +" "+ key +",g' /etc/proftpd.conf") elif(rt2.exitCode == 0): shLaunch("sed -i 's,^" + param +".*,#"+ param +" "+ key +",g' /etc/proftpd.conf") else: #do not exists, create it self.insertConf("/etc/proftpd.conf",'^' + param, ' ' + key + '\n') shLaunch("service proftpd restart") return 0 rt = shLaunch("cat /etc/proftpd.conf | grep '" + param + "' ") if(rt.exitCode != 0): self.insertConf("/etc/proftpd.conf", '^' + param, '\t\t\t' + key + '\n') else: self.replaceConf("/etc/proftpd.conf", '^' + param, '\t\t\t' + key + '\n') shLaunch("service proftpd restart") return 0