sftpd_test.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. package sftpd_test
  2. import (
  3. "crypto/rand"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "testing"
  13. "time"
  14. _ "github.com/go-sql-driver/mysql"
  15. _ "github.com/lib/pq"
  16. _ "github.com/mattn/go-sqlite3"
  17. "golang.org/x/crypto/ssh"
  18. "github.com/drakkan/sftpgo/api"
  19. "github.com/drakkan/sftpgo/config"
  20. "github.com/drakkan/sftpgo/dataprovider"
  21. "github.com/drakkan/sftpgo/logger"
  22. "github.com/drakkan/sftpgo/sftpd"
  23. "github.com/pkg/sftp"
  24. "github.com/rs/zerolog"
  25. )
  26. const (
  27. logSender = "sftpdTesting"
  28. sftpServerAddr = "127.0.0.1:2022"
  29. defaultUsername = "test_user_sftp"
  30. defaultPassword = "test_password"
  31. testPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  32. testPubKey1 = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCd60+/j+y8f0tLftihWV1YN9RSahMI9btQMDIMqts/jeNbD8jgoogM3nhF7KxfcaMKURuD47KC4Ey6iAJUJ0sWkSNNxOcIYuvA+5MlspfZDsa8Ag76Fe1vyz72WeHMHMeh/hwFo2TeIeIXg480T1VI6mzfDrVp2GzUx0SS0dMsQBjftXkuVR8YOiOwMCAH2a//M1OrvV7d/NBk6kBN0WnuIBb2jKm15PAA7+jQQG7tzwk2HedNH3jeL5GH31xkSRwlBczRK0xsCQXehAlx6cT/e/s44iJcJTHfpPKoSk6UAhPJYe7Z1QnuoawY9P9jQaxpyeImBZxxUEowhjpj2avBxKdRGBVK8R7EL8tSOeLbhdyWe5Mwc1+foEbq9Zz5j5Kd+hn3Wm1UnsGCrXUUUoZp1jnlNl0NakCto+5KmqnT9cHxaY+ix2RLUWAZyVFlRq71OYux1UHJnEJPiEI1/tr4jFBSL46qhQZv/TfpkfVW8FLz0lErfqu0gQEZnNHr3Fc= nicola@p1"
  33. testPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
  34. b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
  35. NhAAAAAwEAAQAAAYEAtN449A/nY5O6cSH/9Doa8a3ISU0WZJaHydTaCLuO+dkqtNpnV5mq
  36. zFbKidXAI1eSwVctw9ReVOl1uK6aZF3lbXdOD8W9PXobR9KUUT2qBx5QC4ibfAqDKWymDA
  37. PG9ylzz64hsYBqJr7VNk9kTFEUsDmWzLabLoH42Elnp8mF/lTkWIcpVp0ly/etS08gttXo
  38. XenekJ1vRuxOYWDCEzGPU7kGc920TmM14k7IDdPoOh5+3sRUKedKeOUrVDH1f0n7QjHQsZ
  39. cbshp8tgqzf734zu8cTqNrr+6taptdEOOij1iUL/qYGfzny/hA48tO5+UFUih5W8ftp0+E
  40. NBIDkkGgk2MJ92I7QAXyMVsIABXco+mJT7pQi9tqlODGIQ3AOj0gcA3X/Ib8QX77Ih3TPi
  41. XEh77/P1XiYZOgpp2cRmNH8QbqaL9u898hDvJwIPJPuj2lIltTElH7hjBf5LQfCzrLV7BD
  42. 10rM7sl4jr+A2q8jl1Ikp+25kainBBZSbrDummT9AAAFgDU/VLk1P1S5AAAAB3NzaC1yc2
  43. EAAAGBALTeOPQP52OTunEh//Q6GvGtyElNFmSWh8nU2gi7jvnZKrTaZ1eZqsxWyonVwCNX
  44. ksFXLcPUXlTpdbiummRd5W13Tg/FvT16G0fSlFE9qgceUAuIm3wKgylspgwDxvcpc8+uIb
  45. GAaia+1TZPZExRFLA5lsy2my6B+NhJZ6fJhf5U5FiHKVadJcv3rUtPILbV6F3p3pCdb0bs
  46. TmFgwhMxj1O5BnPdtE5jNeJOyA3T6Doeft7EVCnnSnjlK1Qx9X9J+0Ix0LGXG7IafLYKs3
  47. +9+M7vHE6ja6/urWqbXRDjoo9YlC/6mBn858v4QOPLTuflBVIoeVvH7adPhDQSA5JBoJNj
  48. CfdiO0AF8jFbCAAV3KPpiU+6UIvbapTgxiENwDo9IHAN1/yG/EF++yId0z4lxIe+/z9V4m
  49. GToKadnEZjR/EG6mi/bvPfIQ7ycCDyT7o9pSJbUxJR+4YwX+S0Hws6y1ewQ9dKzO7JeI6/
  50. gNqvI5dSJKftuZGopwQWUm6w7ppk/QAAAAMBAAEAAAGAHKnC+Nq0XtGAkIFE4N18e6SAwy
  51. 0WSWaZqmCzFQM0S2AhJnweOIG/0ZZHjsRzKKauOTmppQk40dgVsejpytIek9R+aH172gxJ
  52. 2n4Cx0UwduRU5x8FFQlNc/kl722B0JWfJuB/snOZXv6LJ4o5aObIkozt2w9tVFeAqjYn2S
  53. 1UsNOfRHBXGsTYwpRDwFWP56nKo2d2wBBTHDhCy6fb2dLW1fvSi/YspueOGIlHpvlYKi2/
  54. CWqvs9xVrwcScMtiDoQYq0khhO0efLCxvg/o+W9CLMVM2ms4G1zoSUQKN0oYWWQJyW4+VI
  55. YneWO8UpN0J3ElXKi7bhgAat7dBaM1g9IrAzk153DiEFZNsPxGOgL/+YdQN7zUBx/z7EkI
  56. jyv80RV7fpUXvcq2p+qNl6UVig3VSzRrnsaJkUWu/A0u59ha7ocv6NxDIXjxpIDJme16GF
  57. quiGVBQNnYJymS/vFEbGf6bgf7iRmMCRUMG4nqLA6fPYP9uAtch+CmDfVLZC/fIdC5AAAA
  58. wQCDissV4zH6bfqgxJSuYNk8Vbb+19cF3b7gH1rVlB3zxpCAgcRgMHC+dP1z2NRx7UW9MR
  59. nye6kjpkzZZ0OigLqo7TtEq8uTglD9o6W7mRXqhy5A/ySOmqPL3ernHHQhGuoNODYAHkOU
  60. u2Rh8HXi+VLwKZcLInPOYJvcuLG4DxN8WfeVvlMHwhAOaTNNOtL4XZDHQeIPc4qHmJymmv
  61. sV7GuyQ6yW5C10uoGdxRPd90Bh4z4h2bKfZFjvEBbSBVkqrlAAAADBAN/zNtNayd/dX7Cr
  62. Nb4sZuzCh+CW4BH8GOePZWNCATwBbNXBVb5cR+dmuTqYm+Ekz0VxVQRA1TvKncluJOQpoa
  63. Xj8r0xdIgqkehnfDPMKtYVor06B9Fl1jrXtXU0Vrr6QcBWruSVyK1ZxqcmcNK/+KolVepe
  64. A6vcl/iKaG4U7su166nxLST06M2EgcSVsFJHpKn5+WAXC+X0Gx8kNjWIIb3GpiChdc0xZD
  65. mq02xZthVJrTCVw/e7gfDoB2QRsNV8HwAAAMEAzsCghZVp+0YsYg9oOrw4tEqcbEXEMhwY
  66. 0jW8JNL8Spr1Ibp5Dw6bRSk5azARjmJtnMJhJ3oeHfF0eoISqcNuQXGndGQbVM9YzzAzc1
  67. NbbCNsVroqKlChT5wyPNGS+phi2bPARBno7WSDvshTZ7dAVEP2c9MJW0XwoSevwKlhgSdt
  68. RLFFQ/5nclJSdzPBOmQouC0OBcMFSrYtMeknJ4VvueVvve5HcHFaEsaMc7ABAGaLYaBQOm
  69. iixITGvaNZh/tjAAAACW5pY29sYUBwMQE=
  70. -----END OPENSSH PRIVATE KEY-----`
  71. configDir = ".."
  72. )
  73. var (
  74. allPerms = []string{dataprovider.PermAny}
  75. homeBasePath string
  76. )
  77. func TestMain(m *testing.M) {
  78. logfilePath := filepath.Join(configDir, "sftpgo_sftpd_test.log")
  79. logger.InitLogger(logfilePath, 5, 1, 28, false, zerolog.DebugLevel)
  80. config.LoadConfig(configDir, "")
  81. providerConf := config.GetProviderConf()
  82. err := dataprovider.Initialize(providerConf, configDir)
  83. if err != nil {
  84. logger.Warn(logSender, "error initializing data provider: %v", err)
  85. os.Exit(1)
  86. }
  87. dataProvider := dataprovider.GetProvider()
  88. sftpdConf := config.GetSFTPDConfig()
  89. httpdConf := config.GetHTTPDConfig()
  90. router := api.GetHTTPRouter()
  91. // we run the test cases with UploadMode atomic. The non atomic code path
  92. // simply does not execute some code so if it works in atomic mode will
  93. // work in non atomic mode too
  94. sftpdConf.UploadMode = 1
  95. if runtime.GOOS == "windows" {
  96. homeBasePath = "C:\\"
  97. } else {
  98. homeBasePath = "/tmp"
  99. sftpdConf.Actions.ExecuteOn = []string{"download", "upload", "rename", "delete"}
  100. sftpdConf.Actions.Command = "/bin/true"
  101. sftpdConf.Actions.HTTPNotificationURL = "http://127.0.0.1:8080/"
  102. }
  103. sftpd.SetDataProvider(dataProvider)
  104. api.SetDataProvider(dataProvider)
  105. go func() {
  106. logger.Debug(logSender, "initializing SFTP server with config %+v", sftpdConf)
  107. if err := sftpdConf.Initialize(configDir); err != nil {
  108. logger.Error(logSender, "could not start SFTP server: %v", err)
  109. }
  110. }()
  111. go func() {
  112. logger.Debug(logSender, "initializing HTTP server with config %+v", httpdConf)
  113. s := &http.Server{
  114. Addr: fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort),
  115. Handler: router,
  116. ReadTimeout: 300 * time.Second,
  117. WriteTimeout: 300 * time.Second,
  118. MaxHeaderBytes: 1 << 20, // 1MB
  119. }
  120. if err := s.ListenAndServe(); err != nil {
  121. logger.Error(logSender, "could not start HTTP server: %v", err)
  122. }
  123. }()
  124. waitTCPListening(fmt.Sprintf("%s:%d", sftpdConf.BindAddress, sftpdConf.BindPort))
  125. waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort))
  126. exitCode := m.Run()
  127. os.Remove(logfilePath)
  128. os.Exit(exitCode)
  129. }
  130. func TestInitialization(t *testing.T) {
  131. config.LoadConfig(configDir, "")
  132. sftpdConf := config.GetSFTPDConfig()
  133. sftpdConf.Umask = "invalid umask"
  134. err := sftpdConf.Initialize(configDir)
  135. if err == nil {
  136. t.Errorf("Inizialize must fail, a SFTP server should be already running")
  137. }
  138. }
  139. func TestBasicSFTPHandling(t *testing.T) {
  140. usePubKey := false
  141. u := getTestUser(usePubKey)
  142. u.QuotaSize = 6553600
  143. user, _, err := api.AddUser(u, http.StatusOK)
  144. if err != nil {
  145. t.Errorf("unable to add user: %v", err)
  146. }
  147. client, err := getSftpClient(user, usePubKey)
  148. if err != nil {
  149. t.Errorf("unable to create sftp client: %v", err)
  150. } else {
  151. defer client.Close()
  152. testFileName := "test_file.dat"
  153. testFilePath := filepath.Join(homeBasePath, testFileName)
  154. testFileSize := int64(65535)
  155. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  156. expectedQuotaFiles := user.UsedQuotaFiles + 1
  157. err = createTestFile(testFilePath, testFileSize)
  158. if err != nil {
  159. t.Errorf("unable to create test file: %v", err)
  160. }
  161. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  162. if err != nil {
  163. t.Errorf("file upload error: %v", err)
  164. }
  165. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  166. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  167. if err != nil {
  168. t.Errorf("file download error: %v", err)
  169. }
  170. user, _, err = api.GetUserByID(user.ID, http.StatusOK)
  171. if err != nil {
  172. t.Errorf("error getting user: %v", err)
  173. }
  174. if expectedQuotaFiles != user.UsedQuotaFiles {
  175. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  176. }
  177. if expectedQuotaSize != user.UsedQuotaSize {
  178. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  179. }
  180. err = client.Remove(testFileName)
  181. if err != nil {
  182. t.Errorf("error removing uploaded file: %v", err)
  183. }
  184. _, err = client.Lstat(testFileName)
  185. if err == nil {
  186. t.Errorf("stat for deleted file must not succeed")
  187. }
  188. user, _, err = api.GetUserByID(user.ID, http.StatusOK)
  189. if err != nil {
  190. t.Errorf("error getting user: %v", err)
  191. }
  192. if (expectedQuotaFiles - 1) != user.UsedQuotaFiles {
  193. t.Errorf("quota files does not match after delete, expected: %v, actual: %v", expectedQuotaFiles-1, user.UsedQuotaFiles)
  194. }
  195. if (expectedQuotaSize - testFileSize) != user.UsedQuotaSize {
  196. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize-testFileSize, user.UsedQuotaSize)
  197. }
  198. }
  199. _, err = api.RemoveUser(user, http.StatusOK)
  200. if err != nil {
  201. t.Errorf("unable to remove user: %v", err)
  202. }
  203. }
  204. func TestDirCommands(t *testing.T) {
  205. usePubKey := false
  206. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  207. if err != nil {
  208. t.Errorf("unable to add user: %v", err)
  209. }
  210. // remove the home dir to test auto creation
  211. _, err = os.Stat(user.HomeDir)
  212. if err == nil {
  213. os.RemoveAll(user.HomeDir)
  214. }
  215. client, err := getSftpClient(user, usePubKey)
  216. if err != nil {
  217. t.Errorf("unable to create sftp client: %v", err)
  218. } else {
  219. defer client.Close()
  220. err = client.Mkdir("test")
  221. if err != nil {
  222. t.Errorf("error mkdir: %v", err)
  223. }
  224. err = client.Rename("test", "test1")
  225. if err != nil {
  226. t.Errorf("error rename: %v", err)
  227. }
  228. err = client.Remove("test1")
  229. if err != nil {
  230. t.Errorf("error rmdir: %v", err)
  231. }
  232. err = client.Mkdir("/test/test1")
  233. if err != nil {
  234. t.Errorf("error mkdir all: %v", err)
  235. }
  236. testFileName := "/test_file.dat"
  237. testFilePath := filepath.Join(homeBasePath, testFileName)
  238. testFileSize := int64(65535)
  239. err = createTestFile(testFilePath, testFileSize)
  240. if err != nil {
  241. t.Errorf("unable to create test file: %v", err)
  242. }
  243. err = sftpUploadFile(testFilePath, filepath.Join("/test", testFileName), testFileSize, client)
  244. if err != nil {
  245. t.Errorf("file upload error: %v", err)
  246. }
  247. // internally client.Remove will call RemoveDirectory on failure
  248. // the first remove will fail since test directory is not empty
  249. // the RemoveDirectory called internally by client.Remove will succeed
  250. err = client.Remove("/test")
  251. if err != nil {
  252. t.Errorf("error rmdir all: %v", err)
  253. }
  254. _, err = client.Lstat("/test")
  255. if err == nil {
  256. t.Errorf("stat for deleted dir must not succeed")
  257. }
  258. err = client.Remove("/test")
  259. if err == nil {
  260. t.Errorf("remove missing path must fail")
  261. }
  262. }
  263. _, err = api.RemoveUser(user, http.StatusOK)
  264. if err != nil {
  265. t.Errorf("unable to remove user: %v", err)
  266. }
  267. }
  268. func TestSymlink(t *testing.T) {
  269. usePubKey := false
  270. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  271. if err != nil {
  272. t.Errorf("unable to add user: %v", err)
  273. }
  274. client, err := getSftpClient(user, usePubKey)
  275. if err != nil {
  276. t.Errorf("unable to create sftp client: %v", err)
  277. } else {
  278. defer client.Close()
  279. testFileName := "test_file.dat"
  280. testFilePath := filepath.Join(homeBasePath, testFileName)
  281. testFileSize := int64(65535)
  282. err = createTestFile(testFilePath, testFileSize)
  283. if err != nil {
  284. t.Errorf("unable to create test file: %v", err)
  285. }
  286. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  287. if err != nil {
  288. t.Errorf("file upload error: %v", err)
  289. }
  290. err = client.Symlink(testFileName, testFileName+".link")
  291. if err != nil {
  292. t.Errorf("error creating symlink: %v", err)
  293. }
  294. err = client.Remove(testFileName + ".link")
  295. if err != nil {
  296. t.Errorf("error removing symlink: %v", err)
  297. }
  298. err = client.Remove(testFileName)
  299. if err != nil {
  300. t.Errorf("error removing uploaded file: %v", err)
  301. }
  302. }
  303. _, err = api.RemoveUser(user, http.StatusOK)
  304. if err != nil {
  305. t.Errorf("unable to remove user: %v", err)
  306. }
  307. }
  308. func TestStat(t *testing.T) {
  309. usePubKey := false
  310. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  311. if err != nil {
  312. t.Errorf("unable to add user: %v", err)
  313. }
  314. client, err := getSftpClient(user, usePubKey)
  315. if err != nil {
  316. t.Errorf("unable to create sftp client: %v", err)
  317. } else {
  318. defer client.Close()
  319. testFileName := "test_file.dat"
  320. testFilePath := filepath.Join(homeBasePath, testFileName)
  321. testFileSize := int64(65535)
  322. err = createTestFile(testFilePath, testFileSize)
  323. if err != nil {
  324. t.Errorf("unable to create test file: %v", err)
  325. }
  326. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  327. if err != nil {
  328. t.Errorf("file upload error: %v", err)
  329. }
  330. fi, err := client.Lstat(testFileName)
  331. if err != nil {
  332. t.Errorf("stat error: %v", err)
  333. }
  334. err = client.Chown(testFileName, 1000, 1000)
  335. if err != nil {
  336. t.Errorf("chown error: %v", err)
  337. }
  338. err = client.Chmod(testFileName, 0600)
  339. if err != nil {
  340. t.Errorf("chmod error: %v", err)
  341. }
  342. newFi, err := client.Lstat(testFileName)
  343. if err != nil {
  344. t.Errorf("stat error: %v", err)
  345. }
  346. if fi.Mode().Perm() != newFi.Mode().Perm() {
  347. t.Errorf("stat must remain unchanged")
  348. }
  349. _, err = client.ReadLink(testFileName)
  350. if err == nil {
  351. t.Errorf("readlink is not supported and must fail")
  352. }
  353. err = client.Remove(testFileName)
  354. if err != nil {
  355. t.Errorf("error removing uploaded file: %v", err)
  356. }
  357. }
  358. _, err = api.RemoveUser(user, http.StatusOK)
  359. if err != nil {
  360. t.Errorf("unable to remove user: %v", err)
  361. }
  362. }
  363. // basic tests to verify virtual chroot, should be improved to cover more cases ...
  364. func TestEscapeHomeDir(t *testing.T) {
  365. usePubKey := true
  366. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  367. if err != nil {
  368. t.Errorf("unable to add user: %v", err)
  369. }
  370. client, err := getSftpClient(user, usePubKey)
  371. if err != nil {
  372. t.Errorf("unable to create sftp client: %v", err)
  373. } else {
  374. defer client.Close()
  375. _, err := client.Getwd()
  376. if err != nil {
  377. t.Errorf("unable to get working dir: %v", err)
  378. }
  379. testDir := "testDir"
  380. linkPath := filepath.Join(homeBasePath, defaultUsername, testDir)
  381. err = os.Symlink(homeBasePath, linkPath)
  382. if err != nil {
  383. t.Errorf("error making local symlink: %v", err)
  384. }
  385. _, err = client.ReadDir(testDir)
  386. if err == nil {
  387. t.Errorf("reading a symbolic link outside home dir should not succeeded")
  388. }
  389. os.Remove(linkPath)
  390. testFileName := "test_file.dat"
  391. testFilePath := filepath.Join(homeBasePath, testFileName)
  392. testFileSize := int64(65535)
  393. err = createTestFile(testFilePath, testFileSize)
  394. if err != nil {
  395. t.Errorf("unable to create test file: %v", err)
  396. }
  397. remoteDestPath := filepath.Join("..", "..", testFileName)
  398. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  399. if err != nil {
  400. t.Errorf("file upload error: %v", err)
  401. }
  402. _, err = client.Lstat(testFileName)
  403. if err != nil {
  404. t.Errorf("file stat error: %v the file was created outside the user dir!", err)
  405. }
  406. err = client.Remove(testFileName)
  407. if err != nil {
  408. t.Errorf("error removing uploaded file: %v", err)
  409. }
  410. linkPath = filepath.Join(homeBasePath, defaultUsername, testFileName)
  411. err = os.Symlink(homeBasePath, linkPath)
  412. if err != nil {
  413. t.Errorf("error making local symlink: %v", err)
  414. }
  415. err = sftpDownloadFile(testFileName, testFilePath, 0, client)
  416. if err == nil {
  417. t.Errorf("download file outside home dir must fail")
  418. }
  419. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  420. if err == nil {
  421. t.Errorf("overwrite a file outside home dir must fail")
  422. }
  423. err = client.Chmod(remoteDestPath, 0644)
  424. if err == nil {
  425. t.Errorf("setstat on a file outside home dir must fail")
  426. }
  427. os.Remove(linkPath)
  428. }
  429. _, err = api.RemoveUser(user, http.StatusOK)
  430. if err != nil {
  431. t.Errorf("unable to remove user: %v", err)
  432. }
  433. }
  434. func TestHomeSpecialChars(t *testing.T) {
  435. usePubKey := true
  436. u := getTestUser(usePubKey)
  437. u.HomeDir = filepath.Join(homeBasePath, "abc açà#&%lk")
  438. user, _, err := api.AddUser(u, http.StatusOK)
  439. if err != nil {
  440. t.Errorf("unable to add user: %v", err)
  441. }
  442. client, err := getSftpClient(user, usePubKey)
  443. if err != nil {
  444. t.Errorf("unable to create sftp client: %v", err)
  445. } else {
  446. defer client.Close()
  447. _, err := client.Getwd()
  448. if err != nil {
  449. t.Errorf("unable to get working dir: %v", err)
  450. }
  451. testFileName := "test_file.dat"
  452. testFilePath := filepath.Join(homeBasePath, testFileName)
  453. testFileSize := int64(65535)
  454. err = createTestFile(testFilePath, testFileSize)
  455. if err != nil {
  456. t.Errorf("unable to create test file: %v", err)
  457. }
  458. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  459. if err != nil {
  460. t.Errorf("file upload error: %v", err)
  461. }
  462. files, err := client.ReadDir(".")
  463. if err != nil {
  464. t.Errorf("unable to read remote dir: %v", err)
  465. }
  466. if len(files) < 1 {
  467. t.Errorf("expected at least 1 file in this dir")
  468. }
  469. err = client.Remove(testFileName)
  470. if err != nil {
  471. t.Errorf("error removing uploaded file: %v", err)
  472. }
  473. }
  474. _, err = api.RemoveUser(user, http.StatusOK)
  475. if err != nil {
  476. t.Errorf("unable to remove user: %v", err)
  477. }
  478. }
  479. func TestLogin(t *testing.T) {
  480. u := getTestUser(false)
  481. u.PublicKey = []string{testPubKey}
  482. user, _, err := api.AddUser(u, http.StatusOK)
  483. if err != nil {
  484. t.Errorf("unable to add user: %v", err)
  485. }
  486. client, err := getSftpClient(user, false)
  487. if err != nil {
  488. t.Errorf("unable to create sftp client: %v", err)
  489. } else {
  490. defer client.Close()
  491. _, err := client.Getwd()
  492. if err != nil {
  493. t.Errorf("sftp client with valid password must work")
  494. }
  495. }
  496. client, err = getSftpClient(user, true)
  497. if err != nil {
  498. t.Errorf("unable to create sftp client: %v", err)
  499. } else {
  500. defer client.Close()
  501. _, err := client.Getwd()
  502. if err != nil {
  503. t.Errorf("sftp client with valid public key must work")
  504. }
  505. }
  506. user.Password = "invalid password"
  507. client, err = getSftpClient(user, false)
  508. if err == nil {
  509. t.Errorf("login with invalid password must fail")
  510. defer client.Close()
  511. }
  512. // testPubKey1 is not authorized
  513. user.PublicKey = []string{testPubKey1}
  514. user.Password = ""
  515. _, _, err = api.UpdateUser(user, http.StatusOK)
  516. if err != nil {
  517. t.Errorf("unable to update user: %v", err)
  518. }
  519. client, err = getSftpClient(user, true)
  520. if err == nil {
  521. t.Errorf("login with invalid public key must fail")
  522. defer client.Close()
  523. }
  524. // login a user with multiple public keys, only the second one is valid
  525. user.PublicKey = []string{testPubKey1, testPubKey}
  526. user.Password = ""
  527. _, _, err = api.UpdateUser(user, http.StatusOK)
  528. if err != nil {
  529. t.Errorf("unable to update user: %v", err)
  530. }
  531. client, err = getSftpClient(user, true)
  532. if err != nil {
  533. t.Errorf("unable to create sftp client: %v", err)
  534. } else {
  535. defer client.Close()
  536. _, err := client.Getwd()
  537. if err != nil {
  538. t.Errorf("sftp client with multiple public key must work if at least one public key is valid")
  539. }
  540. }
  541. _, err = api.RemoveUser(user, http.StatusOK)
  542. if err != nil {
  543. t.Errorf("unable to remove user: %v", err)
  544. }
  545. }
  546. func TestLoginAfterUserUpdateEmptyPwd(t *testing.T) {
  547. usePubKey := false
  548. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  549. if err != nil {
  550. t.Errorf("unable to add user: %v", err)
  551. }
  552. user.Password = ""
  553. user.PublicKey = []string{}
  554. // password and public key should remain unchanged
  555. _, _, err = api.UpdateUser(user, http.StatusOK)
  556. if err != nil {
  557. t.Errorf("unable to update user: %v", err)
  558. }
  559. client, err := getSftpClient(user, usePubKey)
  560. if err != nil {
  561. t.Errorf("unable to create sftp client: %v", err)
  562. } else {
  563. defer client.Close()
  564. _, err := client.Getwd()
  565. if err != nil {
  566. t.Errorf("unable to get working dir: %v", err)
  567. }
  568. _, err = client.ReadDir(".")
  569. if err != nil {
  570. t.Errorf("unable to read remote dir: %v", err)
  571. }
  572. }
  573. _, err = api.RemoveUser(user, http.StatusOK)
  574. if err != nil {
  575. t.Errorf("unable to remove user: %v", err)
  576. }
  577. }
  578. func TestLoginAfterUserUpdateEmptyPubKey(t *testing.T) {
  579. usePubKey := true
  580. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  581. if err != nil {
  582. t.Errorf("unable to add user: %v", err)
  583. }
  584. user.Password = ""
  585. user.PublicKey = []string{}
  586. // password and public key should remain unchanged
  587. _, _, err = api.UpdateUser(user, http.StatusOK)
  588. if err != nil {
  589. t.Errorf("unable to update user: %v", err)
  590. }
  591. client, err := getSftpClient(user, usePubKey)
  592. if err != nil {
  593. t.Errorf("unable to create sftp client: %v", err)
  594. } else {
  595. defer client.Close()
  596. _, err := client.Getwd()
  597. if err != nil {
  598. t.Errorf("unable to get working dir: %v", err)
  599. }
  600. _, err = client.ReadDir(".")
  601. if err != nil {
  602. t.Errorf("unable to read remote dir: %v", err)
  603. }
  604. }
  605. _, err = api.RemoveUser(user, http.StatusOK)
  606. if err != nil {
  607. t.Errorf("unable to remove user: %v", err)
  608. }
  609. }
  610. func TestMaxSessions(t *testing.T) {
  611. usePubKey := false
  612. u := getTestUser(usePubKey)
  613. u.MaxSessions = 1
  614. user, _, err := api.AddUser(u, http.StatusOK)
  615. if err != nil {
  616. t.Errorf("unable to add user: %v", err)
  617. }
  618. client, err := getSftpClient(user, usePubKey)
  619. if err != nil {
  620. t.Errorf("unable to create sftp client: %v", err)
  621. } else {
  622. defer client.Close()
  623. _, err := client.Getwd()
  624. if err != nil {
  625. t.Errorf("unable to get working dir: %v", err)
  626. }
  627. _, err = client.ReadDir(".")
  628. if err != nil {
  629. t.Errorf("unable to read remote dir: %v", err)
  630. }
  631. _, err = getSftpClient(user, usePubKey)
  632. if err == nil {
  633. t.Errorf("max sessions exceeded, new login should not succeed")
  634. }
  635. }
  636. _, err = api.RemoveUser(user, http.StatusOK)
  637. if err != nil {
  638. t.Errorf("unable to remove user: %v", err)
  639. }
  640. }
  641. func TestQuotaFileReplace(t *testing.T) {
  642. usePubKey := false
  643. u := getTestUser(usePubKey)
  644. u.QuotaFiles = 1000
  645. user, _, err := api.AddUser(u, http.StatusOK)
  646. if err != nil {
  647. t.Errorf("unable to add user: %v", err)
  648. }
  649. testFileSize := int64(65535)
  650. testFileName := "test_file.dat"
  651. testFilePath := filepath.Join(homeBasePath, testFileName)
  652. client, err := getSftpClient(user, usePubKey)
  653. if err != nil {
  654. t.Errorf("unable to create sftp client: %v", err)
  655. } else {
  656. defer client.Close()
  657. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  658. expectedQuotaFiles := user.UsedQuotaFiles + 1
  659. err = createTestFile(testFilePath, testFileSize)
  660. if err != nil {
  661. t.Errorf("unable to create test file: %v", err)
  662. }
  663. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  664. if err != nil {
  665. t.Errorf("file upload error: %v", err)
  666. }
  667. user, _, err = api.GetUserByID(user.ID, http.StatusOK)
  668. if err != nil {
  669. t.Errorf("error getting user: %v", err)
  670. }
  671. // now replace the same file, the quota must not change
  672. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  673. if err != nil {
  674. t.Errorf("file upload error: %v", err)
  675. }
  676. user, _, err = api.GetUserByID(user.ID, http.StatusOK)
  677. if err != nil {
  678. t.Errorf("error getting user: %v", err)
  679. }
  680. if expectedQuotaFiles != user.UsedQuotaFiles {
  681. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  682. }
  683. if expectedQuotaSize != user.UsedQuotaSize {
  684. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  685. }
  686. }
  687. // now set a quota size restriction and upload the same fail, upload should fail for space limit exceeded
  688. user.QuotaSize = testFileSize - 1
  689. user, _, err = api.UpdateUser(user, http.StatusOK)
  690. if err != nil {
  691. t.Errorf("error updating user: %v", err)
  692. }
  693. client, err = getSftpClient(user, usePubKey)
  694. if err != nil {
  695. t.Errorf("unable to create sftp client: %v", err)
  696. } else {
  697. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  698. if err == nil {
  699. t.Errorf("quota size exceeded, file upload must fail")
  700. }
  701. err = client.Remove(testFileName)
  702. if err != nil {
  703. t.Errorf("error removing uploaded file: %v", err)
  704. }
  705. }
  706. _, err = api.RemoveUser(user, http.StatusOK)
  707. if err != nil {
  708. t.Errorf("unable to remove user: %v", err)
  709. }
  710. }
  711. func TestQuotaScan(t *testing.T) {
  712. usePubKey := false
  713. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  714. if err != nil {
  715. t.Errorf("unable to add user: %v", err)
  716. }
  717. testFileSize := int64(65535)
  718. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  719. expectedQuotaFiles := user.UsedQuotaFiles + 1
  720. client, err := getSftpClient(user, usePubKey)
  721. if err != nil {
  722. t.Errorf("unable to create sftp client: %v", err)
  723. } else {
  724. defer client.Close()
  725. testFileName := "test_file.dat"
  726. testFilePath := filepath.Join(homeBasePath, testFileName)
  727. err = createTestFile(testFilePath, testFileSize)
  728. if err != nil {
  729. t.Errorf("unable to create test file: %v", err)
  730. }
  731. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  732. if err != nil {
  733. t.Errorf("file upload error: %v", err)
  734. }
  735. }
  736. _, err = api.RemoveUser(user, http.StatusOK)
  737. if err != nil {
  738. t.Errorf("unable to remove user: %v", err)
  739. }
  740. // create user with the same home dir, so there is at least an untracked file
  741. user, _, err = api.AddUser(getTestUser(usePubKey), http.StatusOK)
  742. if err != nil {
  743. t.Errorf("unable to add user: %v", err)
  744. }
  745. _, err = api.StartQuotaScan(user, http.StatusCreated)
  746. if err != nil {
  747. t.Errorf("error starting quota scan: %v", err)
  748. }
  749. scans, _, err := api.GetQuotaScans(http.StatusOK)
  750. if err != nil {
  751. t.Errorf("error getting active quota scans: %v", err)
  752. }
  753. for len(scans) > 0 {
  754. scans, _, err = api.GetQuotaScans(http.StatusOK)
  755. if err != nil {
  756. t.Errorf("error getting active quota scans: %v", err)
  757. break
  758. }
  759. }
  760. user, _, err = api.GetUserByID(user.ID, http.StatusOK)
  761. if err != nil {
  762. t.Errorf("error getting user: %v", err)
  763. }
  764. if expectedQuotaFiles != user.UsedQuotaFiles {
  765. t.Errorf("quota files does not match after scan, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  766. }
  767. if expectedQuotaSize != user.UsedQuotaSize {
  768. t.Errorf("quota size does not match after scan, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  769. }
  770. _, err = api.RemoveUser(user, http.StatusOK)
  771. if err != nil {
  772. t.Errorf("unable to remove user: %v", err)
  773. }
  774. }
  775. func TestMultipleQuotaScans(t *testing.T) {
  776. if !sftpd.AddQuotaScan(defaultUsername) {
  777. t.Errorf("add quota failed")
  778. }
  779. if sftpd.AddQuotaScan(defaultUsername) {
  780. t.Errorf("add quota must fail if another scan is already active")
  781. }
  782. sftpd.RemoveQuotaScan(defaultPassword)
  783. }
  784. func TestQuotaSize(t *testing.T) {
  785. usePubKey := false
  786. testFileSize := int64(65535)
  787. u := getTestUser(usePubKey)
  788. u.QuotaFiles = 1
  789. u.QuotaSize = testFileSize - 1
  790. user, _, err := api.AddUser(u, http.StatusOK)
  791. if err != nil {
  792. t.Errorf("unable to add user: %v", err)
  793. }
  794. client, err := getSftpClient(user, usePubKey)
  795. if err != nil {
  796. t.Errorf("unable to create sftp client: %v", err)
  797. } else {
  798. defer client.Close()
  799. testFileName := "test_file.dat"
  800. testFilePath := filepath.Join(homeBasePath, testFileName)
  801. err = createTestFile(testFilePath, testFileSize)
  802. if err != nil {
  803. t.Errorf("unable to create test file: %v", err)
  804. }
  805. err = sftpUploadFile(testFilePath, testFileName+".quota", testFileSize, client)
  806. if err != nil {
  807. t.Errorf("file upload error: %v", err)
  808. }
  809. err = sftpUploadFile(testFilePath, testFileName+".quota.1", testFileSize, client)
  810. if err == nil {
  811. t.Errorf("user is over quota file upload must fail")
  812. }
  813. err = client.Remove(testFileName + ".quota")
  814. if err != nil {
  815. t.Errorf("error removing uploaded file: %v", err)
  816. }
  817. }
  818. _, err = api.RemoveUser(user, http.StatusOK)
  819. if err != nil {
  820. t.Errorf("unable to remove user: %v", err)
  821. }
  822. }
  823. func TestBandwidthAndConnections(t *testing.T) {
  824. usePubKey := false
  825. testFileSize := int64(131072)
  826. u := getTestUser(usePubKey)
  827. u.UploadBandwidth = 30
  828. u.DownloadBandwidth = 25
  829. wantedUploadElapsed := 1000 * (testFileSize / 1000) / u.UploadBandwidth
  830. wantedDownloadElapsed := 1000 * (testFileSize / 1000) / u.DownloadBandwidth
  831. // 100 ms tolerance
  832. wantedUploadElapsed -= 100
  833. wantedDownloadElapsed -= 100
  834. user, _, err := api.AddUser(u, http.StatusOK)
  835. if err != nil {
  836. t.Errorf("unable to add user: %v", err)
  837. }
  838. client, err := getSftpClient(user, usePubKey)
  839. if err != nil {
  840. t.Errorf("unable to create sftp client: %v", err)
  841. } else {
  842. defer client.Close()
  843. testFileName := "test_file.dat"
  844. testFilePath := filepath.Join(homeBasePath, testFileName)
  845. err = createTestFile(testFilePath, testFileSize)
  846. if err != nil {
  847. t.Errorf("unable to create test file: %v", err)
  848. }
  849. startTime := time.Now()
  850. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  851. if err != nil {
  852. t.Errorf("file upload error: %v", err)
  853. }
  854. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  855. if elapsed < (wantedUploadElapsed) {
  856. t.Errorf("upload bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedUploadElapsed)
  857. }
  858. startTime = time.Now()
  859. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  860. c := sftpDownloadNonBlocking(testFileName, localDownloadPath, testFileSize, client)
  861. waitForActiveTransfer()
  862. // wait some additional arbitrary time to wait for transfer activity to happen
  863. // it is need to reach all the code in CheckIdleConnections
  864. time.Sleep(100 * time.Millisecond)
  865. sftpd.CheckIdleConnections()
  866. err = <-c
  867. if err != nil {
  868. t.Errorf("file download error: %v", err)
  869. }
  870. elapsed = time.Since(startTime).Nanoseconds() / 1000000
  871. if elapsed < (wantedDownloadElapsed) {
  872. t.Errorf("download bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedDownloadElapsed)
  873. }
  874. // test disconnection
  875. c = sftpUploadNonBlocking(testFilePath, testFileName+"_partial", testFileSize, client)
  876. waitForActiveTransfer()
  877. time.Sleep(100 * time.Millisecond)
  878. sftpd.CheckIdleConnections()
  879. stats := sftpd.GetConnectionsStats()
  880. for _, stat := range stats {
  881. sftpd.CloseActiveConnection(stat.ConnectionID)
  882. }
  883. err = <-c
  884. if err == nil {
  885. t.Errorf("connection closed upload must fail")
  886. }
  887. }
  888. _, err = api.RemoveUser(user, http.StatusOK)
  889. if err != nil {
  890. t.Errorf("unable to remove user: %v", err)
  891. }
  892. }
  893. func TestMissingFile(t *testing.T) {
  894. usePubKey := false
  895. u := getTestUser(usePubKey)
  896. user, _, err := api.AddUser(u, http.StatusOK)
  897. if err != nil {
  898. t.Errorf("unable to add user: %v", err)
  899. }
  900. client, err := getSftpClient(user, usePubKey)
  901. if err != nil {
  902. t.Errorf("unable to create sftp client: %v", err)
  903. } else {
  904. defer client.Close()
  905. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  906. err = sftpDownloadFile("missing_file", localDownloadPath, 0, client)
  907. if err == nil {
  908. t.Errorf("download missing file must fail")
  909. }
  910. }
  911. _, err = api.RemoveUser(user, http.StatusOK)
  912. if err != nil {
  913. t.Errorf("unable to remove user: %v", err)
  914. }
  915. }
  916. func TestOverwriteDirWithFile(t *testing.T) {
  917. usePubKey := false
  918. u := getTestUser(usePubKey)
  919. user, _, err := api.AddUser(u, http.StatusOK)
  920. if err != nil {
  921. t.Errorf("unable to add user: %v", err)
  922. }
  923. client, err := getSftpClient(user, usePubKey)
  924. if err != nil {
  925. t.Errorf("unable to create sftp client: %v", err)
  926. } else {
  927. defer client.Close()
  928. testFileSize := int64(65535)
  929. testFileName := "test_file.dat"
  930. testDirName := "test_dir"
  931. testFilePath := filepath.Join(homeBasePath, testFileName)
  932. err = createTestFile(testFilePath, testFileSize)
  933. if err != nil {
  934. t.Errorf("unable to create test file: %v", err)
  935. }
  936. err = client.Mkdir(testDirName)
  937. if err != nil {
  938. t.Errorf("mkdir error: %v", err)
  939. }
  940. err = sftpUploadFile(testFilePath, testDirName, testFileSize, client)
  941. if err == nil {
  942. t.Errorf("copying a file over an existing dir must fail")
  943. }
  944. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  945. if err != nil {
  946. t.Errorf("file upload error: %v", err)
  947. }
  948. err = client.Rename(testFileName, testDirName)
  949. if err == nil {
  950. t.Errorf("rename a file over an existing dir must fail")
  951. }
  952. err = client.RemoveDirectory(testDirName)
  953. if err != nil {
  954. t.Errorf("dir remove error: %v", err)
  955. }
  956. err = client.Remove(testFileName)
  957. if err != nil {
  958. t.Errorf("error removing uploaded file: %v", err)
  959. }
  960. }
  961. _, err = api.RemoveUser(user, http.StatusOK)
  962. if err != nil {
  963. t.Errorf("unable to remove user: %v", err)
  964. }
  965. }
  966. func TestPermList(t *testing.T) {
  967. usePubKey := true
  968. u := getTestUser(usePubKey)
  969. u.Permissions = []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  970. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks}
  971. user, _, err := api.AddUser(u, http.StatusOK)
  972. if err != nil {
  973. t.Errorf("unable to add user: %v", err)
  974. }
  975. client, err := getSftpClient(user, usePubKey)
  976. if err != nil {
  977. t.Errorf("unable to create sftp client: %v", err)
  978. } else {
  979. defer client.Close()
  980. _, err = client.ReadDir(".")
  981. if err == nil {
  982. t.Errorf("read remote dir without permission should not succeed")
  983. }
  984. _, err = client.Stat("test_file")
  985. if err == nil {
  986. t.Errorf("stat remote file without permission should not succeed")
  987. }
  988. }
  989. _, err = api.RemoveUser(user, http.StatusOK)
  990. if err != nil {
  991. t.Errorf("unable to remove user: %v", err)
  992. }
  993. }
  994. func TestPermDownload(t *testing.T) {
  995. usePubKey := true
  996. u := getTestUser(usePubKey)
  997. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  998. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks}
  999. user, _, err := api.AddUser(u, http.StatusOK)
  1000. if err != nil {
  1001. t.Errorf("unable to add user: %v", err)
  1002. }
  1003. client, err := getSftpClient(user, usePubKey)
  1004. if err != nil {
  1005. t.Errorf("unable to create sftp client: %v", err)
  1006. } else {
  1007. defer client.Close()
  1008. testFileName := "test_file.dat"
  1009. testFilePath := filepath.Join(homeBasePath, testFileName)
  1010. testFileSize := int64(65535)
  1011. err = createTestFile(testFilePath, testFileSize)
  1012. if err != nil {
  1013. t.Errorf("unable to create test file: %v", err)
  1014. }
  1015. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1016. if err != nil {
  1017. t.Errorf("file upload error: %v", err)
  1018. }
  1019. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  1020. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  1021. if err == nil {
  1022. t.Errorf("file download without permission should not succeed")
  1023. }
  1024. err = client.Remove(testFileName)
  1025. if err != nil {
  1026. t.Errorf("error removing uploaded file: %v", err)
  1027. }
  1028. }
  1029. _, err = api.RemoveUser(user, http.StatusOK)
  1030. if err != nil {
  1031. t.Errorf("unable to remove user: %v", err)
  1032. }
  1033. }
  1034. func TestPermUpload(t *testing.T) {
  1035. usePubKey := false
  1036. u := getTestUser(usePubKey)
  1037. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermDelete, dataprovider.PermRename,
  1038. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks}
  1039. user, _, err := api.AddUser(u, http.StatusOK)
  1040. if err != nil {
  1041. t.Errorf("unable to add user: %v", err)
  1042. }
  1043. client, err := getSftpClient(user, usePubKey)
  1044. if err != nil {
  1045. t.Errorf("unable to create sftp client: %v", err)
  1046. } else {
  1047. defer client.Close()
  1048. testFileName := "test_file.dat"
  1049. testFilePath := filepath.Join(homeBasePath, testFileName)
  1050. testFileSize := int64(65535)
  1051. err = createTestFile(testFilePath, testFileSize)
  1052. if err != nil {
  1053. t.Errorf("unable to create test file: %v", err)
  1054. }
  1055. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1056. if err == nil {
  1057. t.Errorf("file upload without permission should not succeed")
  1058. }
  1059. }
  1060. _, err = api.RemoveUser(user, http.StatusOK)
  1061. if err != nil {
  1062. t.Errorf("unable to remove user: %v", err)
  1063. }
  1064. }
  1065. func TestPermDelete(t *testing.T) {
  1066. usePubKey := false
  1067. u := getTestUser(usePubKey)
  1068. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermRename,
  1069. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks}
  1070. user, _, err := api.AddUser(u, http.StatusOK)
  1071. if err != nil {
  1072. t.Errorf("unable to add user: %v", err)
  1073. }
  1074. client, err := getSftpClient(user, usePubKey)
  1075. if err != nil {
  1076. t.Errorf("unable to create sftp client: %v", err)
  1077. } else {
  1078. defer client.Close()
  1079. testFileName := "test_file.dat"
  1080. testFilePath := filepath.Join(homeBasePath, testFileName)
  1081. testFileSize := int64(65535)
  1082. err = createTestFile(testFilePath, testFileSize)
  1083. if err != nil {
  1084. t.Errorf("unable to create test file: %v", err)
  1085. }
  1086. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1087. if err != nil {
  1088. t.Errorf("file upload error: %v", err)
  1089. }
  1090. err = client.Remove(testFileName)
  1091. if err == nil {
  1092. t.Errorf("delete without permission should not succeed")
  1093. }
  1094. }
  1095. _, err = api.RemoveUser(user, http.StatusOK)
  1096. if err != nil {
  1097. t.Errorf("unable to remove user: %v", err)
  1098. }
  1099. }
  1100. func TestPermRename(t *testing.T) {
  1101. usePubKey := false
  1102. u := getTestUser(usePubKey)
  1103. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  1104. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks}
  1105. user, _, err := api.AddUser(u, http.StatusOK)
  1106. if err != nil {
  1107. t.Errorf("unable to add user: %v", err)
  1108. }
  1109. client, err := getSftpClient(user, usePubKey)
  1110. if err != nil {
  1111. t.Errorf("unable to create sftp client: %v", err)
  1112. } else {
  1113. defer client.Close()
  1114. testFileName := "test_file.dat"
  1115. testFilePath := filepath.Join(homeBasePath, testFileName)
  1116. testFileSize := int64(65535)
  1117. err = createTestFile(testFilePath, testFileSize)
  1118. if err != nil {
  1119. t.Errorf("unable to create test file: %v", err)
  1120. }
  1121. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1122. if err != nil {
  1123. t.Errorf("file upload error: %v", err)
  1124. }
  1125. err = client.Rename(testFileName, testFileName+".rename")
  1126. if err == nil {
  1127. t.Errorf("rename without permission should not succeed")
  1128. }
  1129. err = client.Remove(testFileName)
  1130. if err != nil {
  1131. t.Errorf("error removing uploaded file: %v", err)
  1132. }
  1133. }
  1134. _, err = api.RemoveUser(user, http.StatusOK)
  1135. if err != nil {
  1136. t.Errorf("unable to remove user: %v", err)
  1137. }
  1138. }
  1139. func TestPermCreateDirs(t *testing.T) {
  1140. usePubKey := false
  1141. u := getTestUser(usePubKey)
  1142. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  1143. dataprovider.PermRename, dataprovider.PermCreateSymlinks}
  1144. user, _, err := api.AddUser(u, http.StatusOK)
  1145. if err != nil {
  1146. t.Errorf("unable to add user: %v", err)
  1147. }
  1148. client, err := getSftpClient(user, usePubKey)
  1149. if err != nil {
  1150. t.Errorf("unable to create sftp client: %v", err)
  1151. } else {
  1152. defer client.Close()
  1153. err = client.Mkdir("testdir")
  1154. if err == nil {
  1155. t.Errorf("mkdir without permission should not succeed")
  1156. }
  1157. testFileName := "test_file.dat"
  1158. testFilePath := filepath.Join(homeBasePath, testFileName)
  1159. testFileSize := int64(65535)
  1160. err = createTestFile(testFilePath, testFileSize)
  1161. if err != nil {
  1162. t.Errorf("unable to create test file: %v", err)
  1163. }
  1164. err = sftpUploadFile(testFilePath, "/dir/subdir/test_file.dat", testFileSize, client)
  1165. if err == nil {
  1166. t.Errorf("mkdir without permission should not succeed")
  1167. }
  1168. }
  1169. _, err = api.RemoveUser(user, http.StatusOK)
  1170. if err != nil {
  1171. t.Errorf("unable to remove user: %v", err)
  1172. }
  1173. }
  1174. func TestPermSymlink(t *testing.T) {
  1175. usePubKey := false
  1176. u := getTestUser(usePubKey)
  1177. u.Permissions = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  1178. dataprovider.PermRename, dataprovider.PermCreateDirs}
  1179. user, _, err := api.AddUser(u, http.StatusOK)
  1180. if err != nil {
  1181. t.Errorf("unable to add user: %v", err)
  1182. }
  1183. client, err := getSftpClient(user, usePubKey)
  1184. if err != nil {
  1185. t.Errorf("unable to create sftp client: %v", err)
  1186. } else {
  1187. defer client.Close()
  1188. testFileName := "test_file.dat"
  1189. testFilePath := filepath.Join(homeBasePath, testFileName)
  1190. testFileSize := int64(65535)
  1191. err = createTestFile(testFilePath, testFileSize)
  1192. if err != nil {
  1193. t.Errorf("unable to create test file: %v", err)
  1194. }
  1195. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1196. if err != nil {
  1197. t.Errorf("file upload error: %v", err)
  1198. }
  1199. err = client.Symlink(testFilePath, testFilePath+".symlink")
  1200. if err == nil {
  1201. t.Errorf("symlink without permission should not succeed")
  1202. }
  1203. err = client.Remove(testFileName)
  1204. if err != nil {
  1205. t.Errorf("error removing uploaded file: %v", err)
  1206. }
  1207. }
  1208. _, err = api.RemoveUser(user, http.StatusOK)
  1209. if err != nil {
  1210. t.Errorf("unable to remove user: %v", err)
  1211. }
  1212. }
  1213. func TestSSHConnection(t *testing.T) {
  1214. usePubKey := false
  1215. user, _, err := api.AddUser(getTestUser(usePubKey), http.StatusOK)
  1216. if err != nil {
  1217. t.Errorf("unable to add user: %v", err)
  1218. }
  1219. err = doSSH(user, usePubKey)
  1220. if err == nil {
  1221. t.Errorf("ssh connection must fail: %v", err)
  1222. }
  1223. _, err = api.RemoveUser(user, http.StatusOK)
  1224. if err != nil {
  1225. t.Errorf("unable to remove user: %v", err)
  1226. }
  1227. }
  1228. func waitTCPListening(address string) {
  1229. for {
  1230. conn, err := net.Dial("tcp", address)
  1231. if err != nil {
  1232. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  1233. time.Sleep(100 * time.Millisecond)
  1234. continue
  1235. }
  1236. logger.InfoToConsole("tcp server %v now listening\n", address)
  1237. defer conn.Close()
  1238. break
  1239. }
  1240. }
  1241. func getTestUser(usePubKey bool) dataprovider.User {
  1242. user := dataprovider.User{
  1243. Username: defaultUsername,
  1244. Password: defaultPassword,
  1245. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  1246. Permissions: allPerms,
  1247. }
  1248. if usePubKey {
  1249. user.PublicKey = []string{testPubKey}
  1250. user.Password = ""
  1251. }
  1252. return user
  1253. }
  1254. func doSSH(user dataprovider.User, usePubKey bool) error {
  1255. var sshSession *ssh.Session
  1256. config := &ssh.ClientConfig{
  1257. User: defaultUsername,
  1258. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  1259. return nil
  1260. },
  1261. }
  1262. if usePubKey {
  1263. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  1264. if err != nil {
  1265. return err
  1266. }
  1267. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  1268. } else {
  1269. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  1270. }
  1271. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  1272. if err != nil {
  1273. return err
  1274. }
  1275. defer conn.Close()
  1276. sshSession, err = conn.NewSession()
  1277. if err != nil {
  1278. return err
  1279. }
  1280. _, err = sshSession.CombinedOutput("ls")
  1281. return err
  1282. }
  1283. func getSftpClient(user dataprovider.User, usePubKey bool) (*sftp.Client, error) {
  1284. var sftpClient *sftp.Client
  1285. config := &ssh.ClientConfig{
  1286. User: user.Username,
  1287. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  1288. return nil
  1289. },
  1290. }
  1291. if usePubKey {
  1292. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  1293. if err != nil {
  1294. return nil, err
  1295. }
  1296. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  1297. } else {
  1298. if len(user.Password) > 0 {
  1299. config.Auth = []ssh.AuthMethod{ssh.Password(user.Password)}
  1300. } else {
  1301. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  1302. }
  1303. }
  1304. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  1305. if err != nil {
  1306. return sftpClient, err
  1307. }
  1308. sftpClient, err = sftp.NewClient(conn)
  1309. return sftpClient, err
  1310. }
  1311. func createTestFile(path string, size int64) error {
  1312. content := make([]byte, size)
  1313. _, err := rand.Read(content)
  1314. if err != nil {
  1315. return err
  1316. }
  1317. return ioutil.WriteFile(path, content, 0666)
  1318. }
  1319. func sftpUploadFile(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) error {
  1320. srcFile, err := os.Open(localSourcePath)
  1321. if err != nil {
  1322. return err
  1323. }
  1324. defer srcFile.Close()
  1325. destFile, err := client.Create(remoteDestPath)
  1326. if err != nil {
  1327. return err
  1328. }
  1329. _, err = io.Copy(destFile, srcFile)
  1330. if err != nil {
  1331. destFile.Close()
  1332. return err
  1333. }
  1334. // we need to close the file to trigger the close method on server
  1335. // we cannot defer closing or Lstat will fail for upload atomic mode
  1336. destFile.Close()
  1337. if expectedSize > 0 {
  1338. fi, err := client.Lstat(remoteDestPath)
  1339. if err != nil {
  1340. return err
  1341. }
  1342. if fi.Size() != expectedSize {
  1343. return fmt.Errorf("uploaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  1344. }
  1345. }
  1346. return err
  1347. }
  1348. func sftpDownloadFile(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) error {
  1349. downloadDest, err := os.Create(localDestPath)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. defer downloadDest.Close()
  1354. sftpSrcFile, err := client.Open(remoteSourcePath)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. defer sftpSrcFile.Close()
  1359. _, err = io.Copy(downloadDest, sftpSrcFile)
  1360. if err != nil {
  1361. return err
  1362. }
  1363. err = downloadDest.Sync()
  1364. if err != nil {
  1365. return err
  1366. }
  1367. if expectedSize > 0 {
  1368. fi, err := downloadDest.Stat()
  1369. if err != nil {
  1370. return err
  1371. }
  1372. if fi.Size() != expectedSize {
  1373. return fmt.Errorf("downloaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  1374. }
  1375. }
  1376. return err
  1377. }
  1378. func sftpUploadNonBlocking(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  1379. c := make(chan error)
  1380. go func() {
  1381. c <- sftpUploadFile(localSourcePath, remoteDestPath, expectedSize, client)
  1382. }()
  1383. return c
  1384. }
  1385. func sftpDownloadNonBlocking(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  1386. c := make(chan error)
  1387. go func() {
  1388. c <- sftpDownloadFile(remoteSourcePath, localDestPath, expectedSize, client)
  1389. }()
  1390. return c
  1391. }
  1392. func waitForActiveTransfer() {
  1393. stats := sftpd.GetConnectionsStats()
  1394. for len(stats) < 1 {
  1395. stats = sftpd.GetConnectionsStats()
  1396. }
  1397. activeTransferFound := false
  1398. for !activeTransferFound {
  1399. stats = sftpd.GetConnectionsStats()
  1400. if len(stats) == 0 {
  1401. break
  1402. }
  1403. for _, stat := range stats {
  1404. if len(stat.Transfers) > 0 {
  1405. activeTransferFound = true
  1406. }
  1407. }
  1408. }
  1409. }