restore.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package backup
  2. import (
  3. "archive/zip"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx"
  9. "github.com/0xJacky/Nginx-UI/settings"
  10. "github.com/uozi-tech/cosy"
  11. cosysettings "github.com/uozi-tech/cosy/settings"
  12. )
  13. // RestoreResult contains the results of a restore operation
  14. type RestoreResult struct {
  15. RestoreDir string
  16. NginxUIRestored bool
  17. NginxRestored bool
  18. HashMatch bool
  19. }
  20. // RestoreOptions contains options for restore operation
  21. type RestoreOptions struct {
  22. BackupPath string
  23. AESKey []byte
  24. AESIv []byte
  25. RestoreDir string
  26. RestoreNginx bool
  27. VerifyHash bool
  28. RestoreNginxUI bool
  29. }
  30. // Restore restores data from a backup archive
  31. func Restore(options RestoreOptions) (RestoreResult, error) {
  32. // Create restore directory if it doesn't exist
  33. if err := os.MkdirAll(options.RestoreDir, 0755); err != nil {
  34. return RestoreResult{}, cosy.WrapErrorWithParams(ErrCreateRestoreDir, err.Error())
  35. }
  36. // Extract main archive to restore directory
  37. if err := extractZipArchive(options.BackupPath, options.RestoreDir); err != nil {
  38. return RestoreResult{}, cosy.WrapErrorWithParams(ErrExtractArchive, err.Error())
  39. }
  40. // Decrypt the extracted files
  41. hashInfoPath := filepath.Join(options.RestoreDir, HashInfoFile)
  42. nginxUIZipPath := filepath.Join(options.RestoreDir, NginxUIZipName)
  43. nginxZipPath := filepath.Join(options.RestoreDir, NginxZipName)
  44. // Decrypt hash info file
  45. if err := decryptFile(hashInfoPath, options.AESKey, options.AESIv); err != nil {
  46. return RestoreResult{}, cosy.WrapErrorWithParams(ErrDecryptFile, HashInfoFile)
  47. }
  48. // Decrypt nginx-ui.zip
  49. if err := decryptFile(nginxUIZipPath, options.AESKey, options.AESIv); err != nil {
  50. return RestoreResult{}, cosy.WrapErrorWithParams(ErrDecryptNginxUIDir, err.Error())
  51. }
  52. // Decrypt nginx.zip
  53. if err := decryptFile(nginxZipPath, options.AESKey, options.AESIv); err != nil {
  54. return RestoreResult{}, cosy.WrapErrorWithParams(ErrDecryptNginxDir, err.Error())
  55. }
  56. // Extract zip files to subdirectories
  57. nginxUIDir := filepath.Join(options.RestoreDir, NginxUIDir)
  58. nginxDir := filepath.Join(options.RestoreDir, NginxDir)
  59. if err := os.MkdirAll(nginxUIDir, 0755); err != nil {
  60. return RestoreResult{}, cosy.WrapErrorWithParams(ErrCreateDir, nginxUIDir)
  61. }
  62. if err := os.MkdirAll(nginxDir, 0755); err != nil {
  63. return RestoreResult{}, cosy.WrapErrorWithParams(ErrCreateDir, nginxDir)
  64. }
  65. // Extract nginx-ui.zip to nginx-ui directory
  66. if err := extractZipArchive(nginxUIZipPath, nginxUIDir); err != nil {
  67. return RestoreResult{}, cosy.WrapErrorWithParams(ErrExtractArchive, "nginx-ui.zip")
  68. }
  69. // Extract nginx.zip to nginx directory
  70. if err := extractZipArchive(nginxZipPath, nginxDir); err != nil {
  71. return RestoreResult{}, cosy.WrapErrorWithParams(ErrExtractArchive, "nginx.zip")
  72. }
  73. result := RestoreResult{
  74. RestoreDir: options.RestoreDir,
  75. NginxUIRestored: false,
  76. NginxRestored: false,
  77. HashMatch: false,
  78. }
  79. // Verify hashes if requested
  80. if options.VerifyHash {
  81. hashMatch, err := verifyHashes(options.RestoreDir, nginxUIZipPath, nginxZipPath)
  82. if err != nil {
  83. return result, cosy.WrapErrorWithParams(ErrVerifyHashes, err.Error())
  84. }
  85. result.HashMatch = hashMatch
  86. }
  87. // Restore nginx configs if requested
  88. if options.RestoreNginx {
  89. if err := restoreNginxConfigs(nginxDir); err != nil {
  90. return result, cosy.WrapErrorWithParams(ErrRestoreNginxConfigs, err.Error())
  91. }
  92. result.NginxRestored = true
  93. }
  94. // Restore nginx-ui config if requested
  95. if options.RestoreNginxUI {
  96. if err := restoreNginxUIConfig(nginxUIDir); err != nil {
  97. return result, cosy.WrapErrorWithParams(ErrBackupNginxUI, err.Error())
  98. }
  99. result.NginxUIRestored = true
  100. }
  101. return result, nil
  102. }
  103. // extractZipArchive extracts a zip archive to the specified directory
  104. func extractZipArchive(zipPath, destDir string) error {
  105. reader, err := zip.OpenReader(zipPath)
  106. if err != nil {
  107. return cosy.WrapErrorWithParams(ErrOpenZipFile, err.Error())
  108. }
  109. defer reader.Close()
  110. for _, file := range reader.File {
  111. err := extractZipFile(file, destDir)
  112. if err != nil {
  113. return err
  114. }
  115. }
  116. return nil
  117. }
  118. // extractZipFile extracts a single file from a zip archive
  119. func extractZipFile(file *zip.File, destDir string) error {
  120. // Check for directory traversal elements in the file name
  121. if strings.Contains(file.Name, "..") {
  122. return cosy.WrapErrorWithParams(ErrInvalidFilePath, file.Name)
  123. }
  124. // Create directory path if needed
  125. filePath := filepath.Join(destDir, file.Name)
  126. // Ensure the resulting file path is within the destination directory
  127. destDirAbs, err := filepath.Abs(destDir)
  128. if err != nil {
  129. return cosy.WrapErrorWithParams(ErrInvalidFilePath, "cannot resolve destination path")
  130. }
  131. filePathAbs, err := filepath.Abs(filePath)
  132. if err != nil {
  133. return cosy.WrapErrorWithParams(ErrInvalidFilePath, file.Name)
  134. }
  135. if !strings.HasPrefix(filePathAbs, destDirAbs+string(os.PathSeparator)) {
  136. return cosy.WrapErrorWithParams(ErrInvalidFilePath, file.Name)
  137. }
  138. if file.FileInfo().IsDir() {
  139. if err := os.MkdirAll(filePath, file.Mode()); err != nil {
  140. return cosy.WrapErrorWithParams(ErrCreateDir, filePath)
  141. }
  142. return nil
  143. }
  144. // Create parent directory if needed
  145. if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
  146. return cosy.WrapErrorWithParams(ErrCreateParentDir, filePath)
  147. }
  148. // Check if this is a symlink by examining mode bits
  149. if file.Mode()&os.ModeSymlink != 0 {
  150. // Open source file in zip to read the link target
  151. srcFile, err := file.Open()
  152. if err != nil {
  153. return cosy.WrapErrorWithParams(ErrOpenZipEntry, file.Name)
  154. }
  155. defer srcFile.Close()
  156. // Read the link target
  157. linkTargetBytes, err := io.ReadAll(srcFile)
  158. if err != nil {
  159. return cosy.WrapErrorWithParams(ErrReadSymlink, file.Name)
  160. }
  161. linkTarget := string(linkTargetBytes)
  162. // Verify the link target doesn't escape the destination directory
  163. absLinkTarget := filepath.Clean(filepath.Join(filepath.Dir(filePath), linkTarget))
  164. if !strings.HasPrefix(absLinkTarget, destDirAbs+string(os.PathSeparator)) {
  165. return cosy.WrapErrorWithParams(ErrInvalidFilePath, linkTarget)
  166. }
  167. // Remove any existing file/link at the target path
  168. _ = os.Remove(filePath)
  169. // Create the symlink
  170. if err := os.Symlink(linkTarget, filePath); err != nil {
  171. return cosy.WrapErrorWithParams(ErrCreateSymlink, file.Name)
  172. }
  173. // Verify the resolved symlink path is within destination directory
  174. resolvedPath, err := filepath.EvalSymlinks(filePath)
  175. if err != nil {
  176. return cosy.WrapErrorWithParams(ErrEvalSymlinks, filePath)
  177. }
  178. resolvedPathAbs, err := filepath.Abs(resolvedPath)
  179. if err != nil {
  180. return cosy.WrapErrorWithParams(ErrInvalidFilePath, resolvedPath)
  181. }
  182. if !strings.HasPrefix(resolvedPathAbs, destDirAbs+string(os.PathSeparator)) {
  183. // Remove the symlink if it points outside the destination directory
  184. _ = os.Remove(filePath)
  185. return cosy.WrapErrorWithParams(ErrInvalidFilePath, resolvedPath)
  186. }
  187. return nil
  188. }
  189. // Create file
  190. destFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
  191. if err != nil {
  192. return cosy.WrapErrorWithParams(ErrCreateFile, filePath)
  193. }
  194. defer destFile.Close()
  195. // Open source file in zip
  196. srcFile, err := file.Open()
  197. if err != nil {
  198. return cosy.WrapErrorWithParams(ErrOpenZipEntry, file.Name)
  199. }
  200. defer srcFile.Close()
  201. // Copy content
  202. if _, err := io.Copy(destFile, srcFile); err != nil {
  203. return cosy.WrapErrorWithParams(ErrCopyContent, file.Name)
  204. }
  205. return nil
  206. }
  207. // verifyHashes verifies the hashes of the extracted zip files
  208. func verifyHashes(restoreDir, nginxUIZipPath, nginxZipPath string) (bool, error) {
  209. hashFile := filepath.Join(restoreDir, HashInfoFile)
  210. hashContent, err := os.ReadFile(hashFile)
  211. if err != nil {
  212. return false, cosy.WrapErrorWithParams(ErrReadHashFile, err.Error())
  213. }
  214. hashInfo := parseHashInfo(string(hashContent))
  215. // Calculate hash for nginx-ui.zip
  216. nginxUIHash, err := calculateFileHash(nginxUIZipPath)
  217. if err != nil {
  218. return false, cosy.WrapErrorWithParams(ErrCalculateUIHash, err.Error())
  219. }
  220. // Calculate hash for nginx.zip
  221. nginxHash, err := calculateFileHash(nginxZipPath)
  222. if err != nil {
  223. return false, cosy.WrapErrorWithParams(ErrCalculateNginxHash, err.Error())
  224. }
  225. // Verify hashes
  226. return (hashInfo.NginxUIHash == nginxUIHash && hashInfo.NginxHash == nginxHash), nil
  227. }
  228. // parseHashInfo parses hash info from content string
  229. func parseHashInfo(content string) HashInfo {
  230. info := HashInfo{}
  231. lines := strings.Split(content, "\n")
  232. for _, line := range lines {
  233. line = strings.TrimSpace(line)
  234. if line == "" {
  235. continue
  236. }
  237. parts := strings.SplitN(line, ":", 2)
  238. if len(parts) != 2 {
  239. continue
  240. }
  241. key := strings.TrimSpace(parts[0])
  242. value := strings.TrimSpace(parts[1])
  243. switch key {
  244. case "nginx-ui_hash":
  245. info.NginxUIHash = value
  246. case "nginx_hash":
  247. info.NginxHash = value
  248. case "timestamp":
  249. info.Timestamp = value
  250. case "version":
  251. info.Version = value
  252. }
  253. }
  254. return info
  255. }
  256. // restoreNginxConfigs restores nginx configuration files
  257. func restoreNginxConfigs(nginxBackupDir string) error {
  258. destDir := nginx.GetConfPath()
  259. if destDir == "" {
  260. return ErrNginxConfigDirEmpty
  261. }
  262. // Remove all contents in the destination directory first
  263. // Read directory entries
  264. entries, err := os.ReadDir(destDir)
  265. if err != nil {
  266. return cosy.WrapErrorWithParams(ErrCopyNginxConfigDir, "failed to read directory: "+err.Error())
  267. }
  268. // Remove each entry
  269. for _, entry := range entries {
  270. entryPath := filepath.Join(destDir, entry.Name())
  271. err := os.RemoveAll(entryPath)
  272. if err != nil {
  273. return cosy.WrapErrorWithParams(ErrCopyNginxConfigDir, "failed to remove: "+err.Error())
  274. }
  275. }
  276. // Copy files from backup to nginx config directory
  277. if err := copyDirectory(nginxBackupDir, destDir); err != nil {
  278. return err
  279. }
  280. return nil
  281. }
  282. // restoreNginxUIConfig restores nginx-ui configuration files
  283. func restoreNginxUIConfig(nginxUIBackupDir string) error {
  284. // Get config directory
  285. configDir := filepath.Dir(cosysettings.ConfPath)
  286. if configDir == "" {
  287. return ErrConfigPathEmpty
  288. }
  289. // Restore app.ini to the configured location
  290. srcConfigPath := filepath.Join(nginxUIBackupDir, "app.ini")
  291. if err := copyFile(srcConfigPath, cosysettings.ConfPath); err != nil {
  292. return err
  293. }
  294. // Restore database file if exists
  295. dbName := settings.DatabaseSettings.GetName()
  296. srcDBPath := filepath.Join(nginxUIBackupDir, dbName+".db")
  297. destDBPath := filepath.Join(configDir, dbName+".db")
  298. // Only attempt to copy if database file exists in backup
  299. if _, err := os.Stat(srcDBPath); err == nil {
  300. if err := copyFile(srcDBPath, destDBPath); err != nil {
  301. return err
  302. }
  303. }
  304. return nil
  305. }