lcmlog-server 13 KB

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