lcmlog-server 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #!/usr/bin/env python3
  2. DIR = "/var/local/log/lcmlog-data"
  3. FROM_DOMAIN = "lcm.mi.infn.it"
  4. import os
  5. import os.path
  6. #from os import stat
  7. #from pwd import getpwuid
  8. import sys
  9. import shlex
  10. import pwd
  11. import logging
  12. import logging.handlers
  13. import hashlib
  14. import contextlib
  15. import toml
  16. import subprocess
  17. # We log what happens every time someone connects
  18. # Preparing the logger
  19. logger = logging.getLogger(__name__)
  20. file_formatter = logging.Formatter("%(asctime)s | %(levelname)8s | %(message)s")
  21. logger.setLevel(logging.INFO)
  22. # Logger handle to log all info
  23. # We use a TimedRotatingFileHandler to rotate logs once a week
  24. file_handler = logging.handlers.TimedRotatingFileHandler(filename = DIR + "/logs/logfile", when = "W6", backupCount = 10)
  25. file_handler.setFormatter(file_formatter)
  26. logger.addHandler(file_handler)
  27. # Update logfile acl
  28. #if pwd.getpwuid(os.stat(DIR + "/logs/logfile").st_uid).pw_name == pwd.getpwuid(os.geteuid()).pw_name:
  29. # subprocess.call(["touch", DIR + "/logs/logfile"])
  30. # #subprocess.call(["chmod", "444", DIR + "/logs/*"])
  31. # subprocess.call(["chmod", "666", DIR + "/logs/logfile"])
  32. #------------------------------------------------------------------------------
  33. def main():
  34. # The user is going to call us through ssh, so to know who he is we can simply get his effective uid
  35. user_id = os.geteuid()
  36. user_name = pwd.getpwuid(user_id).pw_name
  37. logger.info("Started by user " + user_name + " (id " + str(user_id) + ")")
  38. try:
  39. method = input() # Can be GET, POST or UPDATE
  40. logger.info("Method: " + method)
  41. if method == "UPDATE": # We don't need more input lines for the UPDATE method
  42. auth(user_id, "UPDATE", "") # Check if the user can update the database
  43. method_update()
  44. else:
  45. kind = input() # This is the kind of the log, and it can be 150 or Admin
  46. logger.info("Kind: " + kind)
  47. # Now date check is implemented in the client side script
  48. # Maybe, for the future, date control can be implemented aslo here
  49. date = input() # The date of the log
  50. logger.info("Date: " + date)
  51. tags = input() # Tags are comma separated
  52. logger.info("Tags: " + tags)
  53. if kind != "150" and kind != "Admin": # We only have this two log types
  54. raise KindError
  55. if method == "POST":
  56. optional_line = input()
  57. auth(user_id, "POST", kind) # Check if the user can post for the requested kind
  58. log = sys.stdin.read() # Read the log content
  59. if optional_line == "MAIL":
  60. send_mail = True
  61. TO_ADDRESS = "working@lcm.mi.infn.it"
  62. REPLY_TO = True
  63. else:
  64. send_mail = False
  65. # optional_line consumes the input but it is not
  66. # a recognized header, so it's
  67. # the first line of the log
  68. log = optional_line + log
  69. method_post(kind, user_name, date, tags, log, send_mail)
  70. elif method == "GET":
  71. auth(user_id, "GET", kind) # Check if the user can get logs for the requested kind
  72. user_to_find = input() # Read the user name of the log writer to search
  73. logger.info("User to find: " + user_to_find)
  74. method_get(kind, user_to_find, date, tags)
  75. else:
  76. raise MethodError
  77. except EOFError as error:
  78. logger.critical("1 Not enough input lines")
  79. sys.exit(1)
  80. except FileNotFoundError as error:
  81. logger.critical("2 File not found")
  82. sys.exit(2)
  83. except FileExistsError as error:
  84. logger.critical("3 File already exists")
  85. sys.exit(3)
  86. except OSError as error:
  87. logger.critical("4 File error")
  88. sys.exit(4)
  89. except MethodError as error:
  90. logger.critical("5 Undefined method")
  91. sys.exit(5)
  92. except KindError as error:
  93. logger.critical("6 Undefined log kind")
  94. sys.exit(6)
  95. except AuthError as error:
  96. logger.critical("7 Authentication error")
  97. sys.exit(7)
  98. except Exception as error:
  99. logger.critical("8 Generic error: " + str(error))
  100. sys.exit(8)
  101. finally:
  102. logger.info("End\n")
  103. #------------------------------------------------------------------------------
  104. # Create new log file and adds it to the database
  105. # kind, user_name, date and tags is the log metadata
  106. # log is the log content
  107. # The log metadata and content is hashed, and the hash is saved in the database and used as the filename for the log
  108. # The return value of the function is the hash
  109. def log_create(kind, user_name, date, tags, log):
  110. name = hashlib.sha512((kind + user_name + date + tags + log).encode("utf-8")).hexdigest()
  111. with open(DIR + "/data/" + name, "x") as f:
  112. f.write(name + "\n" + kind + "\n" + user_name + "\n" + date + "\n" + tags + "\n" + log) # Write the file
  113. with open(DIR + "/data/.data", "a") as f:
  114. f.write(name + ":" + kind + ":" + user_name + ":" + date + ":" + tags + "\n") # And add the entry to the .data file
  115. return name
  116. # Search for the requested entry
  117. # The functions returns a list containing the hash (saved in the database) of all the files that meet the specified criteria
  118. # The kind parameter is mandatory (because different users have different privileges based on it).
  119. # All the other arguments can be empty. Only the arguments that are not empty are taken into consideration for the search
  120. def log_find(kind, user_name, date, tags):
  121. file_list = list()
  122. with open(DIR + "/data/.data", "r") as f:
  123. for line in f:
  124. found = True
  125. l = line.split(":")
  126. # The kind is different
  127. if l[1].find(kind) == -1:
  128. continue
  129. # The username is different, or we aren't searching by username
  130. if user_name and l[2].find(user_name) == -1:
  131. continue
  132. # The date is different, or we aren't searching by date
  133. if date and l[3].find(date) == -1:
  134. continue
  135. # Searh tags
  136. for t in tags.split(","):
  137. if t and l[4].find(t) == -1:
  138. found = False
  139. break
  140. # Save
  141. if found:
  142. file_list.append(l[0])
  143. return file_list
  144. # TODO: the following functions work with the hash of the log files. The problem is that there are three different places where the hash is: the first line of the file,
  145. # the database entry for the log and the filename of the log. I have to decide which function operates on which hash, because for example if the hash is changed in the file,
  146. # it needs to be changed also in the other two locations.
  147. # Add log file to .data
  148. # This function reads an existing log file and adds it to the database
  149. # Tha hash that is saved in the database is not calculated: the first line in the file is considered to be the hash. Use log_check to check if they are the same
  150. def log_add(name):
  151. with open(DIR + "/data/" + name, "r") as f, open(DIR + "/data/.data", "a") as data:
  152. data.write(f.readline().rstrip("\n") + ":" + # Hash
  153. f.readline().rstrip("\n") + ":" + # Kind
  154. f.readline().rstrip("\n") + ":" + # User name
  155. f.readline().rstrip("\n") + ":" + # Date
  156. f.readline().rstrip("\n") + "\n") # Tags
  157. # Check if the saved hash is correct, and if it is not, ask the user what to do
  158. # This function calculates the hash of the file with filename name, and returns True if it is the same as the first line of the file, False otherwise
  159. # If it doesn't correspond, it asks the user if he wants to keep it like it is or change it. Currently, it is pretty messed up: only the hash saved in the file is changed,
  160. # not the one saved in the database or the file name. Also, the dialog to ask if the hash is to be changed probably should not be in this function.
  161. def log_check(name):
  162. with open(DIR + "/data/" + name, "r") as f:
  163. saved_hash = f.readline().rstrip("\n")
  164. kind = f.readline().rstrip("\n")
  165. user = f.readline().rstrip("\n")
  166. date = f.readline().rstrip("\n")
  167. tags = f.readline().rstrip("\n")
  168. log = f.read()
  169. calc_hash = log_hash(name)
  170. result = saved_hash == calc_hash
  171. if not result:
  172. logger.warning(calc_hash + " hash does not correspond to saved one")
  173. while True:
  174. print("Warning: " + calc_hash + " sh does not correspond to saved one.\n" +
  175. "Do you want to: print the log (p), change the saved hash (c), or leave it as it is (l)?")
  176. c = input()
  177. if c == "p":
  178. sys.stdout.write("Hash: " + saved_hash + "\n")
  179. sys.stdout.write("Kind: " + kind + "\n")
  180. sys.stdout.write("User: " + user + "\n")
  181. sys.stdout.write("Date: " + date + "\n")
  182. sys.stdout.write("Tags: " + tags + "\n")
  183. sys.stdout.write("\n" + log + "\n")
  184. elif c == "l":
  185. logger.info("Hash unchanged")
  186. break
  187. elif c == "c":
  188. with open(DIR + "/data/" + name, "w") as f:
  189. f.write(calc_hash + "\n" + kind + "\n" + user + "\n" + date + "\n" + tags + "\n" + log)
  190. logger.info("Hash changed")
  191. break
  192. return result
  193. # Calculates hash of file
  194. # The first line of the file is the saved hash, therefore it is not considered in the calculation
  195. def log_hash(name):
  196. with open(DIR + "/data/" + name, "r") as f:
  197. f.readline() # The saved hash doesn't enter in the calculation
  198. kind = f.readline().rstrip("\n")
  199. user_name = f.readline().rstrip("\n")
  200. date = f.readline().rstrip("\n")
  201. tags = f.readline().rstrip("\n")
  202. log = f.read()
  203. return hashlib.sha512((kind + user_name + date + tags + log).encode("utf-8")).hexdigest()
  204. # Email the log contents from USER_NAME@FROM_DOMAIN to TO_ADDRESS
  205. # Emails the log contents using the 'mail(1)' program. If REPLY_TO is
  206. # True add the 'Reply-to: ' header to the email
  207. def log_mail(kind, user_name, date, tags, log):
  208. if REPLY_TO:
  209. subprocess.run('printf "%s\n" ' + f'{shlex.quote(log)} | mail -s "Log{kind} {date} {tags}" ' +
  210. f'-r {user_name}@{FROM_DOMAIN} -S replyto="{TO_ADDRESS}" {TO_ADDRESS}', shell=True)
  211. else:
  212. subprocess.run('printf "%s\n" ' + f'{shlex.quote(log)} | mail -s "Log{kind} {date} {tags}" ' +
  213. f'-r {user_name}@{FROM_DOMAIN} {TO_ADDRESS}', shell=True)
  214. return
  215. #------------------------------------------------------------------------------
  216. # Print specified log on stdout
  217. def method_get(kind, user_to_find, date, tags):
  218. file_list = log_find(kind, user_to_find, date, tags)
  219. for name in file_list:
  220. with open(DIR + "/data/" + name, "r") as f:
  221. sys.stdout.write("Hash: " + f.readline())
  222. sys.stdout.write("Kind: " + f.readline())
  223. sys.stdout.write("User: " + f.readline())
  224. sys.stdout.write("Date: " + f.readline())
  225. sys.stdout.write("Tags: " + f.readline())
  226. sys.stdout.write("\n" + f.read() + "------------------\n")
  227. logger.info("GET successful: got " + str(len(file_list)) + " files")
  228. # Write log
  229. def method_post(kind, user_name, date, tags, log, send_mail):
  230. name = log_create(kind, user_name, date, tags, log)
  231. logger.info("POST successful: hash " + name)
  232. if send_mail:
  233. log_mail(kind, user_name, date, tags, log)
  234. logger.info("MAIL sent.")
  235. # Generate .data file
  236. def method_update():
  237. with contextlib.suppress(FileNotFoundError):
  238. os.remove(DIR + "/data/.data")
  239. file_list = os.listdir(DIR + "/data/")
  240. open(DIR + "/data/.data", "x").close()
  241. for name in file_list:
  242. newname = log_hash(name)
  243. if not log_check(name):
  244. os.rename(DIR + "/data/" + name, DIR + "/data/" + newname)
  245. log_add(newname)
  246. logger.info("UPDATE successful: added " + str(len(file_list)) + " files")
  247. #------------------------------------------------------------------------------
  248. # Checks if the user has the permissions to use the requested method
  249. def auth(user_id, method, kind):
  250. # Check if user id is in auth files
  251. # We suppose that every authorized user is ONLY IN A FILE!
  252. user_type = ""
  253. for file_name in ["150","Admin","Valhalla","Nirvana"]:
  254. with open(DIR + "/auth/" + file_name) as f:
  255. for line in f:
  256. line = line.split()[0]
  257. if int(line) == user_id:
  258. # If present, we consider only the user type
  259. user_type = file_name
  260. break
  261. if not user_type == "":
  262. break
  263. else:
  264. # If not in auth files, the user cannot do anything
  265. raise AuthError()
  266. # Now we check the user type permissions
  267. auth_list = toml.load(DIR + "/auth/auth.toml")[user_type]["auth"]
  268. if not method + " " + kind in auth_list:
  269. raise AuthError()
  270. return
  271. #------------------------------------------------------------------------------
  272. # Error definitions
  273. class AuthError(Exception):
  274. pass
  275. class KindError(Exception):
  276. pass
  277. class MethodError(Exception):
  278. pass
  279. #------------------------------------------------------------------------------
  280. # Starting point
  281. if __name__ == "__main__":
  282. main()
  283. # Change permissions to logfile just before leaving. Dirty fix to a not well understood problem
  284. subprocess.call(["chmod", "666", DIR + "/logs/logfile"])