Exemplo n.º 1
0
def build(args):
    context = {
        'dbsnp_build': args.dbsnp_build,
        'genome_build': args.genome_build,
        'prefix': args.prefix,
        'target': args.target,
    }
    context['db_name'] = '{prefix}_{dbsnp_build}_{genome_build}'.format(**context)
    context['db_user'] = '******'
    log.info(colored(pformat(context), 'blue'))

    with cd(DBSNP_HOME):
        force('createuser {db_user}'.format(**context))
        force('createdb --owner={db_user} {db_name}'.format(**context))

        target = [DBSNP_HOME] if 'core' in args.target else []
        target += [os.path.join(DBSNP_HOME, 'contrib', x) for x in set(args.target) if x != 'core']

        for src in target:
            with cd(src):
                run('pwd')
                if glob.glob('02_drop_create_table.*'):
                    context.update(src=src)
                    run('./01_fetch_data.sh        -d {dbsnp_build} -r {genome_build} {src}/data'.format(**context))
                    run('./02_drop_create_table.sh {db_name} {db_user} {src}'.format(**context))
                    run('./03_import_data.sh       {db_name} {db_user} {src} {src}/data'.format(**context))

    log.info('Done')
    log.info('To connect via psql, run:')
    log.info('')
    log.info(colored('$ psql {db_name} -U {db_user}'.format(**context), 'blue', attrs=['bold']))
    log.info('')
Exemplo n.º 2
0
 def createRobots(self):
     fpath = self.directory + "/robots.txt"
     f = open(fpath, "w")
     f.writelines(self.getRobots())
     f.close()
     logging.info("Create file robots.txt in " + self.directory)
     print colored('\tCreate:\tCreate robots.txt file ' + fpath, 'green')
Exemplo n.º 3
0
 def existsFiles(self):
     """
     :return: Number of files found
     """
     foundFile = 0
     for f in self.fileWordPress:
         if os.path.exists(
             os.path.abspath(self.directory + "/" + f.split("\n")[0])
         ):
             if self.mode_verbose:
                 print colored(
                     "\t[OK]\t" + self.directory + "/" + f.split("\n")[0],
                     'green',
                 )
                 logging.info(
                     self.directory + "/" + f.split("\n")[0]
                 )
             foundFile += 1
         elif self.mode_verbose:
             print colored(
                 "\t[FAIL]\t" + self.directory + "/" + f.split("\n")[0],
                 'red',
             )
             logging.error(
                 self.directory + "/" + f.split("\n")[0]
             )
     return foundFile
Exemplo n.º 4
0
 def delete(self):
     f = open(self.filters, "w")
     f.writelines(self.getFilters() + self.getFunction())
     f.close()
     print colored("\nDeleted WordPress versions", "yellow")
     logging.info("modified: wp-includes/default-filters.php")
     print colored("\tmodified:\twp-includes/default-filters.php", "red")
Exemplo n.º 5
0
 def resumen(self, number):
     """
     :param number: Number of files found
     :return: None
     """
     print colored(
         "\t%s of the %s files are WordPress Project."
     ) % (str(number), str(len(self.fileWordPress)))
Exemplo n.º 6
0
 def __init__(self, directory):
     """
     :param directory: Absolute path of the directory to check.
     """
     self.directory = os.path.abspath(directory)
     print colored('\nCreated file robots.txt', 'yellow')
     self.setUrl()
     self.setRobots()
Exemplo n.º 7
0
 def delete(self):
     """
     :return: None
     """
     print colored('\nRemove files by defaults', 'yellow')
     self.deleteReadme()
     self.deleteLicense()
     self.deleteThemes()
Exemplo n.º 8
0
 def deleteReadme(self):
     """
     :return: None
     """
     if os.path.exists(self.directory + self.readme):
         os.remove(self.directory + self.readme)
         logging.info("Delete: file readmes.")
         print colored('\tdelete:\tfile /readme.html', 'red')
Exemplo n.º 9
0
 def decoratorOutput(self, foundFile):
     """
     :param foundFile: Number of found files
     :return: None
     """
     if foundFile == 0:
         print colored(
             "\nNot Found file library Timthumb in " + self.directory + "/",
             'green')
Exemplo n.º 10
0
 def deletePlugins(self):
     """
     :return: None
     """
     for pathPlugins in self.plugins:
         if os.path.exists(self.directory + pathPlugins):
             os.remove(self.directory + pathPlugins)
             logging.info("Delete: plugin " + pathPlugins)
             print colored('\tdelete:\tplugin ' + pathPlugins, 'red')
Exemplo n.º 11
0
 def deleteThemes(self):
     """
     :return: None
     """
     for pathThemes in self.themes:
         if os.path.exists(self.directory + pathThemes):
             shutil.rmtree(self.directory + pathThemes)
             logging.info("Delete: Theme " + pathThemes)
             print colored('\tdelete:\ttheme ' + pathThemes, 'red')
Exemplo n.º 12
0
 def deleteLicense(self):
     """
     :return: None
     """
     for pathLicese in self.license:
         if os.path.exists(self.directory + pathLicese):
             os.remove(self.directory + pathLicese)
             logging.info("Delete: file " + pathLicese)
             print colored('\tdelete:\tfile ' + pathLicese, 'red')
Exemplo n.º 13
0
 def deleteLicense(self):
     """
     :return: None
     """
     for pathLicese in self.license:
         if os.path.exists(self.directory + pathLicese):
             os.remove(self.directory + pathLicese)
             logging.info("Delete: file " + pathLicese)
             print colored('\tdelete:\tfile ' + pathLicese, 'red')
Exemplo n.º 14
0
 def deleteStaticFile(self):
     """
     :return: None
     """
     for pathFile in self.static_file:
         if os.path.exists(self.directory + pathFile):
             os.remove(self.directory + pathFile)
             logging.info("Delete: file " + pathFile)
             print colored('\tdelete:\tfile ' + pathFile, 'red')
Exemplo n.º 15
0
 def deletePlugins(self):
     """
     :return: None
     """
     for pathPlugins in self.plugins:
         if os.path.exists(self.directory + pathPlugins):
             os.remove(self.directory + pathPlugins)
             logging.info("Delete: plugin " + pathPlugins)
             print colored('\tdelete:\tplugin ' + pathPlugins, 'red')
Exemplo n.º 16
0
 def deleteThemes(self):
     """
     :return: None
     """
     for pathThemes in self.themes:
         if os.path.exists(self.directory + pathThemes):
             shutil.rmtree(self.directory + pathThemes)
             logging.info("Delete: Theme " + pathThemes)
             print colored('\tdelete:\ttheme ' + pathThemes, 'red')
Exemplo n.º 17
0
 def deleteStaticFile(self):
     """
     :return: None
     """
     for pathFile in self.static_file:
         if os.path.exists(self.directory + pathFile):
             os.remove(self.directory + pathFile)
             logging.info("Delete: file " + pathFile)
             print colored('\tdelete:\tfile ' + pathFile, 'red')
Exemplo n.º 18
0
 def decoratorOutput(self, foundFile):
     """
     :param foundFile: Number of found files
     :return: None
     """
     if foundFile == 0:
         print colored(
             "\nNot Found file library Timthumb in " +
             self.directory + "/", 'green'
         )
Exemplo n.º 19
0
 def createRobots(self):
     """
     :return: None
     """
     fpath = self.directory + "/robots.txt"
     f = open(fpath, "w")
     f.writelines(self.getRobots())
     f.close()
     logging.info("Create file robots.txt in " + self.directory)
     print colored('\tCreate:\tCreate robots.txt file ' + fpath, 'green')
Exemplo n.º 20
0
 def disableRestApi(self):
     """
     :return: None
     """
     f = open(self.filters, "w")
     f.writelines(self.getScript() + self.getFunctions())
     f.close
     print colored('\nDisabled REST API', 'yellow')
     print colored('\tModified:\twp-includes/default-filters.php', 'red')
     logging.info("Modified: wp-includes/default-filters.php")
Exemplo n.º 21
0
 def delete(self):
     f = open(self.filters, "w")
     f.writelines(self.getFilters() + self.getFunction())
     f.close()
     print colored('\nDeleted WordPress versions', 'yellow')
     logging.info("Modified: wp-includes/default-filters.php")
     print colored(
         '\tModified:\twp-includes/default-filters.php',
         'red'
     )
Exemplo n.º 22
0
 def scan(self):
     """
     :return: None
     """
     print colored('\nMalware Scan', 'yellow')
     for r, d, f in os.walk(self.directory):
         for wpfile in f:
             scanfile = open(os.path.join(r, wpfile), "r")
             content = scanfile.readlines()
             scanfile.close()
             self.search(content, r, wpfile)
Exemplo n.º 23
0
 def delete(self):
     """
     :return: None
     """
     print colored('\nRemove files by defaults', 'yellow')
     self.deleteReadme()
     self.deleteLicense()
     self.deleteThemes()
     self.deletePlugins()
     self.deleteStaticFile()
     self.deleteFilePlugins()
Exemplo n.º 24
0
 def deleteFilePlugins(self):
     """
     :return: None
     """
     for base, dirs, files in os.walk(self.directory +
                                      "/wp-content/plugins"):
         for pathFile in self.filesPlugins:
             if os.path.exists(base + pathFile):
                 os.remove(base + pathFile)
                 logging.info("Delete: file " + pathFile)
                 print colored('\tdelete:\tfile ' + pathFile, 'red')
Exemplo n.º 25
0
 def scan(self):
     """
     :return: None
     """
     print colored('\nMalware Scan', 'yellow')
     for r, d, f in os.walk(self.directory):
         for wpfile in f:
             scanfile = open(os.path.join(r, wpfile), "r")
             content = scanfile.readlines()
             scanfile.close()
             self.search(content, r, wpfile)
Exemplo n.º 26
0
 def deleteFilePlugins(self):
     """
     :return: None
     """
     for base, dirs, files in os.walk(
         self.directory + "/wp-content/plugins"
     ):
         for pathFile in self.filesPlugins:
             if os.path.exists(base + pathFile):
                 os.remove(base + pathFile)
                 logging.info("Delete: file " + pathFile)
                 print colored('\tdelete:\tfile ' + pathFile, 'red')
Exemplo n.º 27
0
 def createIndexes(self):
     for index in self.directory_create:
         if not os.path.exists(self.directory + index):
             os.makedirs(self.directory + index)
         f = open(self.directory + index + '/index.php', "w")
         f.close()
         logging.info(self.directory + index + "/index.php create.")
         # mode verbose
         # print "[ C ] index.php in " + \
         # self.directory + index + '/index.php'
     print colored('\nCreate Indexes Files', 'yellow')
     print colored('\tAll index.php files were created.', 'green')
     self.writeHtaccess()
Exemplo n.º 28
0
 def questions(self):
     """
     :return: None
     """
     idx = 1
     for plugin in self.list_plugins:
         print colored('\n%s) ' + plugin[0], 'yellow') % (idx)
         print colored('\t' + plugin[1], 'green')
         print colored('\t' + plugin[2], 'green')
         q = raw_input('\tYou want to download [y/n] > ').lower()
         idx += 1
         if q in self.yes:
             request = urllib2.Request(plugin[2])
             try:
                 resp = self.opener.open(request)
                 html = resp.read()
                 patron = re.compile(
                     "https://downloads.wordpress.org/plugin/" +
                     "[a-zA-Z0-9$-_@.&#+]+\.[zip|rar|gzip|tar.gz|tgz]+"
                 )
                 self.download(patron.findall(html))
                 logging.info(
                     "Download plugins " + plugin[0] +
                     " in " + self.directory + "/wp-contet/plugins")
             except urllib2.URLError, e:
                 print colored(
                     '\tPlease check your Internet connection,' +
                     ' you may have a problem.',
                     'red'
                 )
Exemplo n.º 29
0
 def questions(self):
     """
     :return: None
     """
     for plugin in self.list_plugins:
         print colored('\n' + plugin[0], 'yellow')
         print colored('\t' + plugin[1], 'green')
         print colored('\t' + plugin[2], 'green')
         q = raw_input('\tYou want to download [y/n] > ').lower()
         if q in self.yes:
             request = urllib2.Request(plugin[2])
             try:
                 resp = self.opener.open(request)
                 html = resp.read()
                 patron = re.compile(
                     "https://downloads.wordpress.org/plugin/" +
                     "[a-zA-Z0-9$-_@.&#+]+\.[zip|rar|gzip|tar.gz|tgz]+"
                 )
                 self.download(patron.findall(html))
                 logging.info(
                     "Download plugins " + plugin[0] +
                     " in " + self.directory + "/wp-contet/plugins")
             except urllib2.URLError, e:
                 print colored(
                     '\tPlease check your Internet connection,' +
                     ' you may have a problem.',
                     'red'
                 )
Exemplo n.º 30
0
 def __init__(self, directory, proxy):
     self.directory = directory
     print colored("\nCreated file wp-config-wphardening.php", "yellow")
     self.opener = urllib2.build_opener(urllib2.HTTPHandler)
     if proxy is not None:
         conexion_proxy = {}
         conexion_proxy["http"] = proxy
         proxy_handler = urllib2.ProxyHandler(conexion_proxy)
         proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
         proxy_auth_handler.add_password("", "", "", "")
         self.opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
         urllib2.install_opener(self.opener)
     else:
         self.opener = urllib2.build_opener(urllib2.HTTPHandler)
Exemplo n.º 31
0
 def info(c, msg, color='white'):
     if c.dbg:
         # I do this becaus i'm weird and like things lined up in my log output
         # and "INFO -" is fewer chars then "DEBUG -" and so things don't line
         # up.
         #
         if c.color:
             debug(colored(msg, color))
         else:
             debug(msg)
     else:
         if c.color:
             info(colored(msg, color))
         else:
             info(msg)
Exemplo n.º 32
0
 def searchStaticFile(self):
     for root, dirs, files in os.walk(self.directory):
         dirs[:] = [os.path.join(root, d) for d in dirs]
         # exclude/include files
         files = [os.path.join(root, f) for f in files]
         files = [f for f in files if re.match(self.includes, f)]
         for fname in files:
             f = open(fname, "r")
             script = f.readlines()
             f.close()
             f = open(fname, "w")
             f.writelines(self.getDateTime() + script)
             f.close()
     print colored('\nDeleted fingerprinting WordPress', 'yellow')
     logging.info("Fingerprinting: All changes implemented.")
     print colored('\tAll changes implemented.', 'green')
Exemplo n.º 33
0
   def fetch(self, url):
      """ Returns a lxml document and the urllib2 response object for the URL requested.

      Args:
         url: A string with the uniform resource locator.
      """
      logging.info('Started - fetch')
      
      if re.search(GeoSpider._RE_FILTER, url):
         raise gserror.FetchError('regular expression filter error')
      
      try:
         response = urllib2.urlopen(url)
         html = response.read()
      except urllib2.URLError as e:
         if hasattr(e,'code'):
            raise gserror.FetchError('{0} {1}'.format(e.code, GeoSpider.http_status_message(e.code)))
         raise gserror.FetchError('url error')
      except socket.timeout:
         raise gserror.FetchError('socket timeout')
      except socket.error:
         raise gserror.FetchError('socket error')

      logging.info(termcolor.colored('content-type: %s' % (response.info().gettype()), 'yellow'))
      
      try:
         doc = lxml.html.document_fromstring(html)
         doc.make_links_absolute(url)
      except lxml.etree.XMLSyntaxError as e:
         raise gserror.FetchError('lxml parse error')

      logging.info('Finished - fetch')
      return doc, response
Exemplo n.º 34
0
 def run(self):
     while self.dirqueue.qsize() > 0:
         try:
             url = self.dirqueue.get_nowait()
             req = self.fuzz_start(url)
             if req.status_code == requests.codes.ok:
                 mutex.acquire()
                 print colored('[%s]:','green')% req.status_code,url
                 mutex.release()
                 dir_exists.append(url)
             else:
                 mutex.acquire()
                 print colored('[%s]:','red')% req.status_code,url
                 mutex.release()
         except:
             pass
Exemplo n.º 35
0
def _fecth(test_url):
    kwargs = {
        "headers": {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0) Gecko/20100101 Firefox/56.0",
        },
        "timeout": 3,
        "allow_redirects":False
    }
    while not proxy_queue.empty():
        proxy = proxy_queue.get()
        cache_proxy.append(proxy)
        kwargs["proxies"] = {"http": proxy, "https": proxy}
        try:
            resp = requests.get(test_url, **kwargs)
        except:
            continue
        if resp.status_code == 200:
            # try:
            #     resp = requests.get(test_url, **kwargs)
            # except:
            #     continue
            print(colored("[%s] proxy pool add %s" % (time.strftime('%H:%M:%S', time.localtime(time.time())),proxy), 'yellow'))
            # if resp.status_code == 302:
            with threading.Lock():
                good_proxy.append(proxy)
Exemplo n.º 36
0
 def writeHtaccess(self):
     if os.path.exists(self.directory + '/.htaccess'):
         f = open(self.directory + '/.htaccess', 'r')
         self.script = f.readlines()
         f.close()
         f = open(self.directory + '/.htaccess', 'w')
         f.writelines(self.script + self.htaccess)
         f.close()
         logging.info("Add options to " + self.directory + '/.htaccess')
         print colored('\tAdd options to ', 'green') + \
             self.directory + '/.htaccess'
     else:
         f = open(self.directory + '/.htaccess', 'w')
         f.writelines(self.htaccess)
         f.close()
         logging.info("Create .htaccess file.")
         print colored('\tCreate Htaccess file ', 'green') + \
             self.directory + '/.htaccess'
Exemplo n.º 37
0
 def download(self, url):
     """
     :param url: URL Plugin.
     :return: None
     """
     self.url = url[0]
     file_name = self.url.split('/')[-1]
     try:
         u = urllib2.urlopen(self.url)
         f = open(file_name, 'wb')
         f.write(u.read())
         f.close()
         zip_file = zipfile.ZipFile(os.path.abspath(file_name), 'r')
         zip_file.extractall(self.directory + '/wp-content/plugins')
         if os.path.exists(os.path.abspath(file_name)):
             os.remove(os.path.abspath(file_name))
     except urllib2.URLError:
         print colored('\tYou can not download this plugins.', 'red')
Exemplo n.º 38
0
def usage():
    print(
        "\nUsage: python3 dirscan-py3.py http://www.xxxx.com dicname,dicname\n"
    )
    print("       python3 dirscan-py3.py host.ini dicname,dicname\n")
    print(
        "example: python3 dirscan-py3.py https://www.baidu.com common,php-small"
    )
    print("DIC LIST: " + colored(list(os.walk('./dic/'))[0][2], 'green'))
Exemplo n.º 39
0
 def download(self, url):
     """
     :param url: URL Plugin.
     :return: None
     """
     self.url = url[0]
     file_name = self.url.split('/')[-1]
     try:
         u = urllib2.urlopen(self.url)
         f = open(file_name, 'wb')
         f.write(u.read())
         f.close()
         zip_file = zipfile.ZipFile(os.path.abspath(file_name), 'r')
         zip_file.extractall(self.directory + '/wp-content/plugins')
         if os.path.exists(os.path.abspath(file_name)):
             os.remove(os.path.abspath(file_name))
     except urllib2.URLError:
         print colored('\tYou can not download this plugins.', 'red')
Exemplo n.º 40
0
 def search(self, content, r, wpfile):
     """
     :return: None
     """
     line = 1
     for i in content:
         matchObj = re.search("base64_decode.*", i)
         if matchObj:
             logging.info(
                 os.path.join(r, wpfile) + " - " + matchObj.group()
             )
             print colored(
                 "\n\t" +
                 os.path.join(r, wpfile) + " - " + matchObj.group() +
                 " in line " + str(line),
                 'red'
             )
         line += 1
Exemplo n.º 41
0
 def changePermisions(self):
     for r, d, f in os.walk(self.directory):
         os.chmod(r, 0755)
         for wpfile in f:
             os.chmod(os.path.join(r, wpfile), 0644)
     print colored('\nchmod on Directories', 'yellow')
     print colored('\tAll directories\t drwxr-xr-x (755)', 'green')
     logging.info("All directories drwxr-xr-x (755)")
     print colored('\nchmod on Files', 'yellow')
     print colored('\tAll files\t -rw-r--r-- (644)', 'green')
     logging.info("All files -rw-r--r-- (644)")
Exemplo n.º 42
0
 def __init__(self, directory, proxy):
     """
     :param directory: Absolute path of the directory to check.
     :param proxy: String connection proxy.
     """
     self.directory = directory
     print colored('\nCreated file wp-config-wphardening.php', 'yellow')
     self.opener = urllib2.build_opener(urllib2.HTTPHandler)
     if proxy is not None:
         conexion_proxy = {}
         conexion_proxy["http"] = proxy
         proxy_handler = urllib2.ProxyHandler(conexion_proxy)
         proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
         proxy_auth_handler.add_password('', '', '', '')
         self.opener = urllib2.build_opener(proxy_handler,
                                            proxy_auth_handler)
         urllib2.install_opener(self.opener)
     else:
         self.opener = urllib2.build_opener(urllib2.HTTPHandler)
Exemplo n.º 43
0
 def search(self, content, r, wpfile):
     """
     :return: None
     """
     line = 1
     for i in content:
         matchObj = re.search(
             "(file_get_contents.*|curl_exec.*|popen.*|proc_open.*|" +
             "unserialize.*|base64_decode.*|base64_encode.*|shell_exec.*|" +
             "passthru.*|ob_get_contents.*|curl_init.*|readfile.*|" +
             "fsockopen.*|pfsockopen.*|file_put_contents.*)", i)
         if matchObj:
             logging.info(
                 os.path.join(r, wpfile) + " - " + matchObj.group())
             print colored(
                 "\n\t" + str(self.getCount()) + ") " +
                 os.path.join(r, wpfile) + " - " + matchObj.group() +
                 " in line " + str(line), 'red')
             self.setCount()
         line += 1
Exemplo n.º 44
0
def dir_fuzz(domain, file_type, dic):
    if not domain.startswith('http://'):
        domain = 'http://%s' % domain
    use_dic = open(dic,'r')
    global dir_exists
    dir_exists = []
    for dic_line in use_dic.readlines():
        line = '%s/%s'%(domain,dic_line.strip().replace('%EXT%', file_type))
        dirqueue.put(line)
    use_dic.close()
    threadList = []
    for i in range (threads_num):
        threadList.append(Fuzz(dirqueue))
    for t in threadList:
        t.start()
    for t in threadList:
        t.join()
    print ('-'*50)
    for url in dir_exists:
        print colored('%s','yellow')% url
Exemplo n.º 45
0
 def checkTimbthumb(self):
     """
     :return: None
     """
     foundFile = 0
     for f in self.fileWordPress:
         if os.path.exists(
                 os.path.abspath(self.directory + "/" + f.split("\n")[0])):
             foundFile += 1
             logging.info(self.directory + " Found file library in " + "/" +
                          f.split("\n")[0])
             print colored(
                 self.directory +
                 "/" +
                 f.split("\n")[0], 'yellow') + ' -', \
                 colored(
                     '\n\tFound file library Timbthumb in ' +
                     "/" + f.split("\n")[0] + ' - ' +
                     self.searchVersion(f.split("\n")[0]), 'red'
                 )
     self.decoratorOutput(foundFile)
Exemplo n.º 46
0
    def _color_diff(self, diff):
        colours = {
            '+': 'cyan',
            '-': 'red',
            '?': 'yellow',
            ' ': 'white',
            '@': 'yellow'
        }

        defaultColour = 'white'

        return [colored(line, colours.get(line[0], defaultColour)) for line in diff]
Exemplo n.º 47
0
 def setDbUser(self):
     """
     :return: None
     """
     value = raw_input("\tName of the User > ")
     if value.lower().strip() == "root":
         print (colored("\n\tThe use of the root user is not recommended.", "red"))
         self.setDbUser()
     elif value.strip() == "":
         self.setDbUser()
     else:
         self.db_user = value
Exemplo n.º 48
0
def restore(args):
    context = {
        'dbsnp_build': args.dbsnp_build,
        'genome_build': args.genome_build,
        'prefix': args.prefix,
        'tag': args.tag,
    }
    context['db_src_name'] = 'dbsnp_{dbsnp_build}_{genome_build}'.format(**context)
    context['db_name'] = '{prefix}_{dbsnp_build}_{genome_build}'.format(**context)
    context['db_user'] = '******'
    log.info(colored(pformat(context), 'blue'))

    with cd(DBSNP_HOME):
        force('createuser {db_user}'.format(**context))
        run('./script/pg_restore.sh {db_src_name} {db_name} {db_user} {tag}'.format(**context))

    log.info('Done')
    log.info('To connect via psql, run:')
    log.info('')
    log.info(colored('$ psql {db_name} -U {db_user}'.format(**context), 'blue', attrs=['bold']))
    log.info('')
Exemplo n.º 49
0
 def isWordPress(self):
     """
     :return: True if successful, False otherwise.
     """
     value = self.existsFiles()
     if ((value * 100) / len(self.fileWordPress) > 60):
         logging.info(self.directory +
                      " This project directory is a WordPress.")
         print colored(self.directory, 'yellow') + ' -', \
             colored(
                 '\n\tThis project directory is a WordPress.', 'green'
             )
         if self.mode_verbose:
             self.resumen(value)
         return True
     else:
         logging.error(self.directory +
                       " This Project directory is not a WordPress.")
         print colored(self.directory, 'yellow') + ' -', \
             colored(
                 '\n\tThis Project directory is not a WordPress.', 'red'
             )
         if self.mode_verbose:
             self.resumen(value)
         return False
Exemplo n.º 50
0
 def existsFiles(self):
     """
     :return: Number of files found
     """
     foundFile = 0
     for f in self.fileWordPress:
         if os.path.exists(
                 os.path.abspath(self.directory + "/" + f.split("\n")[0])):
             if self.mode_verbose:
                 print colored(
                     "\t[OK]\t" + self.directory + "/" + f.split("\n")[0],
                     'green',
                 )
                 logging.info(self.directory + "/" + f.split("\n")[0])
             foundFile += 1
         elif self.mode_verbose:
             print colored(
                 "\t[FAIL]\t" + self.directory + "/" + f.split("\n")[0],
                 'red',
             )
             logging.error(self.directory + "/" + f.split("\n")[0])
     return foundFile
Exemplo n.º 51
0
 def writeHtaccess(self):
     """
     :return: None
     """
     if os.path.exists(self.directory + '/.htaccess'):
         f = open(self.directory + '/.htaccess', 'r')
         self.script = f.readlines()
         f.close()
         f = open(self.directory + '/.htaccess', 'w')
         f.writelines(self.script + self.htaccess)
         f.close()
         if self.mode_verbose:
             logging.info("Add options to " + self.directory + '/.htaccess')
             print colored('\tAdd options to ', 'green') + \
                 self.directory + '/.htaccess'
     else:
         f = open(self.directory + '/.htaccess', 'w')
         f.writelines(self.htaccess)
         f.close()
         if self.mode_verbose:
             logging.info("Create .htaccess file.")
             print colored('\tCreate Htaccess file ', 'green') + \
                 self.directory + '/.htaccess'
Exemplo n.º 52
0
 def setDbUser(self):
     """
     :return: None
     """
     value = raw_input('\tName of the User > ')
     if value.lower().strip() == 'root':
         print(
             colored('\n\tThe use of the root user is not recommended.',
                     'red'))
         self.setDbUser()
     elif value.strip() == '':
         self.setDbUser()
     else:
         self.db_user = value
Exemplo n.º 53
0
def init_demo(args):
    context = {
        'db_user': args.demo_db_user,
        'db_name': args.demo_db_name,
    }
    log.info(colored(pformat(context), 'blue'))

    with cd(DBSNP_HOME):
        force('createuser {db_user}'.format(**context))
        force('createdb --owner={db_user} {db_name}'.format(**context))

        for src in [DBSNP_HOME] + glob.glob(DBSNP_HOME + '/contrib/*'):
            with cd(src):
                run('pwd')
                if glob.glob('02_drop_create_table.*'):
                    context.update(src=src)
                    run('./02_drop_create_table.sh {db_name} {db_user} {src}'.format(**context))
                    run('./03_import_data.sh       {db_name} {db_user} {src} {src}/test/data'.format(**context))

    log.info('Done')
    log.info('To connect via psql, run:')
    log.info('')
    log.info(colored('$ psql {} -U {}'.format(args.demo_db_name, args.demo_db_user), 'blue', attrs=['bold']))
    log.info('')
Exemplo n.º 54
0
 def delete(self):
     """
     :return: None
     """
     f = open(self.filters, "w")
     f.writelines(self.getFilters() + self.getFunction())
     f.close()
     print colored('\nDeleted WordPress versions', 'yellow')
     print colored('\tModified:\twp-includes/default-filters.php', 'red')
     print colored(
         '\t// This is a function that removes versions of WordPress.\n' +
         '\tfunction delete_version_wp() {\n' + '\t\treturn "";\n' +
         '\t}\n' +
         '\tadd_filter(\'the_generator\', \'delete_version_wp\');', 'green')
     logging.info("Modified: wp-includes/default-filters.php")
Exemplo n.º 55
0
 def createIndexes(self):
     """
     :return: None
     """
     for index in self.directory_create:
         if not os.path.exists(self.directory + index):
             os.makedirs(self.directory + index)
         f = open(self.directory + index + '/index.php', "w")
         f.close()
         if self.mode_verbose:
             print colored(
                 '\nCreate Indexes Files in %s%s%s' %
                 (self.directory, index, '/index.php'), 'yellow')
         logging.info(self.directory + index + "/index.php create.")
     print colored('\nCreate Indexes Files', 'yellow')
     print colored('\tAll index.php files were created.', 'green')
     self.writeHtaccess()
Exemplo n.º 56
0
 def searchStaticFileJS(self):
     """
     :return: None
     """
     for root, dirs, files in os.walk(self.directory):
         dirs[:] = [os.path.join(root, d) for d in dirs]
         # exclude/include files
         files = [os.path.join(root, f) for f in files]
         files = [f for f in files if re.match(self.includes_js, f)]
         for fname in files:
             f = open(fname, "r").read()
             data = cssmin(f)
             f = open(fname, "w+b")
             f.write(data)
             f.close()
             if self.mode_verbose:
                 print colored('\tCompress content in ' + fname, 'green')
                 logging.info("Compress content in " + fname)
     print colored('\nDeleted fingerprinting WordPress', 'yellow')
     logging.info("Fingerprinting: All changes implemented.")
     print colored('\tAll changes implemented.', 'green')
Exemplo n.º 57
0
 def searchStaticFile(self):
     """
     :return: None
     """
     for root, dirs, files in os.walk(self.directory):
         dirs[:] = [os.path.join(root, d) for d in dirs]
         # exclude/include files
         files = [os.path.join(root, f) for f in files]
         files = [f for f in files if re.match(self.includes, f)]
         for fname in files:
             f = open(fname, "r")
             script = f.readlines()
             f.close()
             f = open(fname, "w")
             f.writelines(self.getDateTime() + script)
             f.close()
             if self.mode_verbose:
                 print colored('\tChange content in ' + fname, 'green')
                 logging.info("Change content in " + fname)
     print colored('\nDeleted fingerprinting WordPress', 'yellow')
     logging.info("Fingerprinting: All changes implemented.")
     print colored('\tAll changes implemented.', 'green')
Exemplo n.º 58
0
 def leave(c, msg):
     c.indent -= 4
     if c.color:
         c.debug(colored(msg, 'green'))
     else:
         c.debug(msg)
Exemplo n.º 59
0
def cmdLineParser():
    """Implementation to WPHardening."""

    version_wph = "1.6"
    usage = "usage: python %prog [options]"
    version = colored('WPHardening', 'green') + ' version ' + \
        colored(version_wph, 'yellow') + '\n'

    parser = OptionParser(usage, version=version)

    parser.add_option("-v", "--verbose", action="store_true",
                      dest="verbose", default=False,
                      help="Active verbose mode output results")

    parser.add_option("--update", action="store_true", dest="update",
                      default=False,
                      help="Check for WPHardening latest stable version")

    target = OptionGroup(parser, "Target", "This option must be "
                         "specified to modify the package WordPress.")

    target.add_option("-d", "--dir", dest="path", help="**REQUIRED** -"
                      " Working Directory.", metavar="DIRECTORY")

    target.add_option("--load-conf", dest="loadconf", metavar="FILE",
                      help="Load file configuration.")

    hardening = OptionGroup(parser, "Hardening", "Different tools to"
                            " hardening WordPress.")

    hardening.add_option("-c", "--chmod", action="store_true", dest="chmod",
                         help="Chmod 755 in directory and 644 in files.")

    hardening.add_option("-r", "--remove", action="store_true",
                         dest="remove", help="Remove files and directory.")

    hardening.add_option("-b", "--robots", action="store_true", dest="robots",
                         help="Create file robots.txt")

    hardening.add_option("-f", "--fingerprinting", action="store_true",
                         dest="finger", help="Deleted fingerprinting "
                         "WordPress.")

    hardening.add_option("-t", "--timthumb", action="store_true",
                         dest="timthumb", help="Find the library TimThumb.")

    hardening.add_option("--chown", action="store", type="string",
                         dest="chown", metavar="user:group", help="Changing "
                         "file and directory owner.")

    hardening.add_option("--wp-config", action="store_true", dest="wpconfig",
                         help="Wizard generated wp-config.php")

    hardening.add_option("--plugins", action="store_true", dest="plugins",
                         help="Download Plugins Security.")

    hardening.add_option("--proxy", action="store", type="string",
                         dest="proxy", help="Use a HTTP proxy to connect to "
                         "the target url for --plugins and --wp-config.")

    hardening.add_option("--indexes", action="store_true", dest="indexes",
                         help="It deny you to display the contents of "
                         "directories.")

    hardening.add_option("--minify", action="store_true", dest="minify",
                         help="Compressing static file .css and .js")

    hardening.add_option("--malware-scan", action="store_true",
                         dest="malwares", help="Malware Scan in WordPress "
                         "project.")

    hardening.add_option("--6g-firewall", action="store_true",
                         dest="sixg", help="6G Firewall.")

    hardening.add_option("--rest-api", action="store_true",
                         dest="api", help="Disable REST API.")

    miscellaneous = OptionGroup(parser, "Miscellaneous")

    miscellaneous.add_option("-o", "--output", help="Write log report to "
                             "FILE.log", metavar="FILE", dest="output")

    parser.add_option_group(target)
    parser.add_option_group(hardening)
    parser.add_option_group(miscellaneous)

    cmdBanner()

    (options, args) = parser.parse_args()

    if options.loadconf is not None:
        options.path = loadConfWordPress(options.loadconf).getDirectory()
        options.chmod = loadConfWordPress(options.loadconf).getChmod()
        options.robots = loadConfWordPress(options.loadconf).getRobots()
        options.finger = loadConfWordPress(
            options.loadconf
        ).getFingerprinting()
        options.wpconfig = loadConfWordPress(options.loadconf).getWpConfig()
        options.indexes = loadConfWordPress(options.loadconf).getIndexes()
        options.timthumb = loadConfWordPress(options.loadconf).getTimthumb()
        options.malwares = loadConfWordPress(options.loadconf).getMalwareScan()
        options.output = loadConfWordPress(options.loadconf).getOutput()

    if options.output is None:
        filename = 'wphardening.log'
    else:
        filename = options.output

    log = registerLog(filename)
    log.setConfigure()

    if options.update:
        log.add("Check for WPHardening latest stable version")
        updateWPHardening(os.path.abspath(".")).update()
        sys.exit()

    if options.path is None:
        log.add("Did not specify a working directory.")
        parser.print_help()
        sys.exit()

    options.path = os.path.abspath(options.path)

    if os.path.exists(options.path):

        fname = "output.html"
        context = {
            'directory': options.path,
            'version': version_wph
        }

        if checkWordpress(options.path, options.verbose).isWordPress():

            if options.chown is not None:
                changeOwner = chownWordPress(
                    options.path, options.chown, options.verbose
                )

                if changeOwner.isValid():
                    changeOwner.changeOwner()
                    context['chown'] = options.chown

            if options.chmod is not None:
                chmodWordPress(
                    options.path, options.verbose
                ).changePermisions()
                context['chmod'] = True

            if options.robots is not None:
                robotsWordPress(options.path).createRobots()
                context['robots'] = True

            if options.finger is not None:
                deleteVersionWordPress(options.path).delete()
                fingerprintingWordPress(
                    options.path, options.verbose
                ).searchStaticFile()
                context['finger'] = True

            if options.wpconfig is not None:

                if options.proxy is not None:
                    protocolo, rest = urllib2.splittype(options.proxy)

                    if protocolo is None:
                        raise ValueError("unknown URL type: %s") % \
                            (options.proxy)
                    host, rest = urllib2.splithost(rest)
                    host, port = urllib2.splitport(host)

                    if port is None:
                        raise ValueError("unknown protocol for %s") % \
                            (options.proxy)
                    puerto = int(port)
                    asdf = wpconfigWordPress(options.path, options.proxy)
                else:
                    asdf = wpconfigWordPress(options.path, options.proxy)
                asdf.createConfig()

            if options.indexes is not None:
                indexesWordPress(options.path, options.verbose).createIndexes()
                context['indexes'] = True

            if options.timthumb is not None:
                timthumbWordPress(options.path).checkTimbthumb()

            if options.plugins is not None:

                if options.proxy is not None:
                    protocolo, rest = urllib2.splittype(options.proxy)

                    if protocolo is None:
                        raise ValueError("unknown URL type: %s") % \
                            (options.proxy)
                    host, rest = urllib2.splithost(rest)
                    host, port = urllib2.splitport(host)

                    if port is None:
                        raise ValueError("unknown protocol for %s") % \
                            (options.proxy)
                    puerto = int(port)
                    asdf = pluginsWordPress(options.path, options.proxy)
                else:
                    asdf = pluginsWordPress(options.path, options.proxy)
                asdf.questions()

            if options.malwares is not None:
                malwareScanWordPress(options.path).scan()

            if options.remove is not None:
                removeWordPress(options.path).delete()
                context['remove'] = True

            if options.minify is not None:
                minifyWordPress(options.path, options.verbose).minify()

            if options.sixg is not None:
                sixgWordPress(options.path, options.verbose).createFirewall()
                context['sixg'] = True

            if options.api is not None:
                restApiWordPress(options.path).disableRestApi()
                context['api'] = True

        # output jinja2
        with open(fname, 'w') as f:
            html = render_template('index.html.tmpl', context)
            f.write(html)

    else:
        log.add("Could not find the specified directory.")
        print colored('\nCould not find the specified directory.\n', 'red')