lcmlog-server 12 KB

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