restore.go 13 KB

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