honestly no idea, just trying to fix my fckin git
This commit is contained in:
		
							parent
							
								
									6b3c04d759
								
							
						
					
					
						commit
						97bb22a290
					
				
							
								
								
									
										271
									
								
								certAlert.py
									
									
									
									
									
								
							
							
						
						
									
										271
									
								
								certAlert.py
									
									
									
									
									
								
							| @ -1,137 +1,136 @@ | |||||||
| #!/usr/bin/env python | #!/usr/bin/env python | ||||||
| # before running this you might want to export PYTHONIOENCODING=UTF-8, or add it permanently to /etc/environment | # before running this you might want to export PYTHONIOENCODING=UTF-8, or add it permanently to /etc/environment | ||||||
| import datetime, sys, re, urllib2, logging | import datetime, sys, re, urllib2, logging | ||||||
| from bs4 import BeautifulSoup | from bs4 import BeautifulSoup | ||||||
| from pyfcm import FCMNotification | from pyfcm import FCMNotification | ||||||
| 
 | 
 | ||||||
| ERRSTR = '!!!!!!!!!!!!! ' | ERRSTR = '!!!!!!!!!!!!! ' | ||||||
| 
 | 
 | ||||||
| # REMEMBER TO CHANGE THESE!!! | # REMEMBER TO CHANGE THESE!!! | ||||||
| TARGET_URL = 'https://www.cert-bund.de/overview/AdvisoryShort' | TARGET_URL = 'https://www.cert-bund.de/overview/AdvisoryShort' | ||||||
| 
 | 
 | ||||||
| MEMORY_PATH = 'C:\Users\Panki\Desktop\Privat\Dev\certAlert\out.txt' | MEMORY_PATH = 'C:\Users\Panki\Desktop\Privat\Dev\certAlert\out.txt' | ||||||
| KEY_FILE_PATH = 'C:\Users\Panki\Desktop\Privat\Dev\keyfile' | KEY_FILE_PATH = 'C:\Users\Panki\Desktop\Privat\Dev\keyfile' | ||||||
| 
 | 
 | ||||||
| # To monitor more programs, simply add a string here | # To monitor more programs, simply add a string here | ||||||
| PROGRAMS = [u'Android', u'Git', u'Chrome', u'OpenSSH', u'Java', u'Linux', u'Apache', u'Windows'] | PROGRAMS = [u'Android', u'Git', u'Chrome', u'OpenSSH', u'Java', u'Linux', u'Apache', u'Windows'] | ||||||
| 
 | 
 | ||||||
| # object to store a single cert alert | # object to store a single cert alert | ||||||
| class Advisory: | class Advisory: | ||||||
|     def __init__(self, html): |     def __init__(self, html): | ||||||
|         # this is the fun parts. here we 'fish' the information out of the HTML |         # this is the fun parts. here we 'fish' the information out of the HTML | ||||||
|         self.date = datetime.datetime.strptime(html.td.text, '%d.%m.%y').date() |         self.date = datetime.datetime.strptime(html.td.text, '%d.%m.%y').date() | ||||||
|         self.risk = int(html.find('span', {'class': re.compile('search-result-crit-*')}).text) |         self.risk = int(html.find('span', {'class': re.compile('search-result-crit-*')}).text) | ||||||
|         self.identifier = html.find('a', {'class': 'search-result-link'}).text |         self.identifier = html.find('a', {'class': 'search-result-link'}).text | ||||||
|         self.link = 'https://www.cert-bund.de/' + html.find('a', {'class': 'search-result-link'})['href'] |         self.link = 'https://www.cert-bund.de/' + html.find('a', {'class': 'search-result-link'})['href'] | ||||||
|         self.description = html.find_all('a', {'class': 'search-result-link'})[1].text  |         self.description = html.find_all('a', {'class': 'search-result-link'})[1].text  | ||||||
|     def debug(self): |     def debug(self): | ||||||
|         print('date: '+ self.date.isoformat()) |         print('date: '+ self.date.isoformat()) | ||||||
|         print('risk: '+ str(self.risk)) |         print('risk: '+ str(self.risk)) | ||||||
|         print('id: ' + self.identifier) |         print('id: ' + self.identifier) | ||||||
|         print('desc: ' + self.description) |         print('desc: ' + self.description) | ||||||
|         print('link: ' + self.link) |         print('link: ' + self.link) | ||||||
| 
 | 
 | ||||||
| def startLogger(): | def startLogger(): | ||||||
|     # todo: figure out how this works? |     # todo: figure out how this works? | ||||||
|     # thanks to whoever i stole this from |     # thanks to whoever i stole this from | ||||||
|     logger = logging.getLogger('certAlert') |     logger = logging.getLogger('certAlert') | ||||||
|     logger.setLevel(logging.DEBUG) |     logger.setLevel(logging.DEBUG) | ||||||
|     formatter = logging.Formatter('%(name)s-%(levelname)s: %(message)s') |     formatter = logging.Formatter('%(name)s-%(levelname)s: %(message)s') | ||||||
|     handler = logging.StreamHandler() |     handler = logging.StreamHandler() | ||||||
|     handler.setFormatter(formatter) |     handler.setFormatter(formatter) | ||||||
|     logger.addHandler(handler) |     logger.addHandler(handler) | ||||||
| 
 | 
 | ||||||
| def getHTML(url): | def getHTML(url): | ||||||
|     import urllib2 |     import urllib2 | ||||||
|     try: |     try: | ||||||
|         response = urllib2.urlopen(url) |         response = urllib2.urlopen(url) | ||||||
|     except URLError: |     except URLError: | ||||||
|         print(ERRSTR + 'Failed getting webpage!') |         print(ERRSTR + 'Failed getting webpage!') | ||||||
|         print(ERRSTR + 'Check your internet connection or TARGET_URL.') |         print(ERRSTR + 'Check your internet connection or TARGET_URL.') | ||||||
|         sys.exit(ERRSTR + 'Stopping execution!') |         sys.exit(ERRSTR + 'Stopping execution!') | ||||||
|     except: |     except: | ||||||
|         e = sys.exc_info()[1] |         e = sys.exc_info()[1] | ||||||
|         print(ERRSTR + 'Error getting Webpage!') |         print(ERRSTR + 'Error getting Webpage!') | ||||||
|         print(e) |         print(e) | ||||||
|         sys.exit(ERRSTR + 'Stopping execution!') |         sys.exit(ERRSTR + 'Stopping execution!') | ||||||
|     result = response.read() |     result = response.read() | ||||||
|     return result |     return result | ||||||
| 
 | 
 | ||||||
| def readFile(path, lines = False): | def readFile(path, lines = False): | ||||||
|     try: |     try: | ||||||
|         with open(path, 'r') as file: |         with open(path, 'r') as file: | ||||||
|             if(lines): |             if(lines): | ||||||
|                 contents = file.readlines() |                 contents = file.readlines() | ||||||
|             else: |             else: | ||||||
|                 contents = file.read() |                 contents = file.read() | ||||||
|             file.close() |             file.close() | ||||||
|     except IOError: |     except IOError: | ||||||
|         # this most likely means file not found. this can happen during the first run |         # this most likely means file not found. this can happen during the first run | ||||||
|         print(ERRSTR + 'Error reading file ' + path + '!') |         print(ERRSTR + 'Error reading file ' + path + '!') | ||||||
|         contents = '' |         contents = '' | ||||||
|     except: |     except: | ||||||
|         e = sys.exc_info()[1] |         e = sys.exc_info()[1] | ||||||
|         print('An unknown error occured!') |         print('An unknown error occured!') | ||||||
|         print(e) |         print(e) | ||||||
|         contents = '' |         contents = '' | ||||||
|     finally: |     finally: | ||||||
|         return contents |         return contents | ||||||
| 
 | 
 | ||||||
| def main(): | def main(): | ||||||
| # this loads our API keys into memory from an external file which is specified above | # this loads our API keys into memory from an external file which is specified above | ||||||
|     try: |     try: | ||||||
|         contents = readFile(KEY_FILE_PATH, True) |         contents = readFile(KEY_FILE_PATH, True) | ||||||
|         # extract just the text behind the equals sign |         # extract just the text behind the equals sign | ||||||
|         API_KEY = contents[0].split("=",1)[1] |         API_KEY = contents[0].split("=",1)[1] | ||||||
|         USER_KEYS = contents[1].split("=",1)[1] |         USER_KEYS = contents[1].split("=",1)[1] | ||||||
|         # get rid of that pesky newline |         # get rid of that pesky newline | ||||||
|         API_KEY = API_KEY.strip() |         API_KEY = API_KEY.strip() | ||||||
|         # now we split along semicolons to get single keys in a list |         # now we split along semicolons to get single keys in a list | ||||||
|         USER_KEYS = USER_KEYS.split(";") |         USER_KEYS = USER_KEYS.split(";") | ||||||
|     except: |     except: | ||||||
|         e = sys.exc_info()[1] |         e = sys.exc_info()[1] | ||||||
|         print(e) |         print(e) | ||||||
|         print(ERRSTR + "I couldn't load your credentials. Did you specify your keyfile?") |         print(ERRSTR + "I couldn't load your credentials. Did you specify your keyfile?") | ||||||
|         sys.exit(ERRSTR + 'Stopping execution!') |         sys.exit(ERRSTR + 'Stopping execution!') | ||||||
| 
 | 
 | ||||||
|     #startLogger() |     #startLogger() | ||||||
|     print('Getting client using ' + API_KEY) |     print('Getting client using ' + API_KEY) | ||||||
|     client = FCMNotification(api_key=API_KEY) |     client = FCMNotification(api_key=API_KEY) | ||||||
|     html = getHTML(TARGET_URL) |     html = getHTML(TARGET_URL) | ||||||
|     soup = BeautifulSoup(html, 'html.parser') |     soup = BeautifulSoup(html, 'html.parser') | ||||||
|     # create a list of results and add objects created with the data of each table row |     # create a list of results and add objects created with the data of each table row | ||||||
|     results = []  |     results = []  | ||||||
|     for adv in soup.find_all('tr', {'class' : re.compile('search-result-*')}): |     for adv in soup.find_all('tr', {'class' : re.compile('search-result-*')}): | ||||||
|         x = Advisory(adv) |         x = Advisory(adv) | ||||||
|         results.append(x) |         results.append(x) | ||||||
|     # here we're checking which advisory IDs we've already seen,  |     # here we're checking which advisory IDs we've already seen,  | ||||||
|     # so we don't send multiple notifications for the same advisory |     # so we don't send multiple notifications for the same advisory | ||||||
|     # TODO: refactor into functions writeMemory(checkeIDs), readMemory() |     checkedIDs = readFile(MEMORY_PATH) | ||||||
|     checkedIDs = readFile(MEMORY_PATH) |     for result in results: | ||||||
|     for result in results: |         if result.risk > 3: | ||||||
|         if result.risk > 3: |             # here we're checking if the is related to our programs | ||||||
|             # here we're checking if the is related to our programs |             for prog in PROGRAMS: | ||||||
|             for prog in PROGRAMS: |                 if re.search(prog, result.description, re.IGNORECASE): | ||||||
|                 if re.search(prog, result.description, re.IGNORECASE): |                     if ( len(checkedIDs) == 0 ) or ( result.identifier not in checkedIDs ): | ||||||
|                     if ( len(checkedIDs) == 0 ) or ( result.identifier not in checkedIDs ): |                         #this means we have found an alert that we have not seen before! lets alert the user... | ||||||
|                         #this means we have found an alert that we have not seen before! lets alert the user... |                         for key in USER_KEYS: | ||||||
|                         for key in USER_KEYS: |                             try: | ||||||
|                             try: |                                 key = key.rstrip() | ||||||
|                                 key = key.rstrip() |                                 response = client.notify_single_device(registration_id=key, message_body=result.description, message_title=result.identifier) | ||||||
|                                 response = client.notify_single_device(registration_id=key, message_body=result.description, message_title=result.identifier) |                             except: | ||||||
|                             except: |                                 e = sys.exc_info()[1] | ||||||
|                                 e = sys.exc_info()[1] |                                 print(e) | ||||||
|                                 print(e) |                                 print("we fucked up!") | ||||||
|                                 print("we fucked up!") |                         result.debug() | ||||||
|                         result.debug() |                         print('========================================================================') | ||||||
|                         print('========================================================================') |                     else: | ||||||
|                     else: |                         print('Already sent an alert for ' + result.identifier +', skipping...') | ||||||
|                         print('Already sent an alert for ' + result.identifier +', skipping...') |     # now we overwrite our memory file with the IDs we just checked | ||||||
|     # now we overwrite our memory file with the IDs we just checked |     with open(MEMORY_PATH, 'w') as memFile: | ||||||
|     with open(MEMORY_PATH, 'w') as memFile: |         for result in results: | ||||||
|         for result in results: |             memFile.write(result.identifier + '\r') | ||||||
|             memFile.write(result.identifier + '\r') |         memFile.close() | ||||||
|         memFile.close() | 
 | ||||||
| 
 | if __name__ == '__main__': | ||||||
| if __name__ == '__main__': |  | ||||||
|     main() |     main() | ||||||
		Loading…
	
		Reference in New Issue
	
	Block a user