lcmlog-server 10 KB

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