sftpd_test.go 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738
  1. package sftpd_test
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "crypto/sha512"
  8. "encoding/json"
  9. "fmt"
  10. "hash"
  11. "io"
  12. "io/ioutil"
  13. "math"
  14. "net"
  15. "net/http"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "path/filepath"
  20. "runtime"
  21. "strings"
  22. "testing"
  23. "time"
  24. _ "github.com/go-sql-driver/mysql"
  25. _ "github.com/lib/pq"
  26. _ "github.com/mattn/go-sqlite3"
  27. "golang.org/x/crypto/ssh"
  28. "github.com/drakkan/sftpgo/config"
  29. "github.com/drakkan/sftpgo/dataprovider"
  30. "github.com/drakkan/sftpgo/httpd"
  31. "github.com/drakkan/sftpgo/logger"
  32. "github.com/drakkan/sftpgo/sftpd"
  33. "github.com/drakkan/sftpgo/utils"
  34. "github.com/drakkan/sftpgo/vfs"
  35. "github.com/pkg/sftp"
  36. "github.com/rs/zerolog"
  37. )
  38. const (
  39. logSender = "sftpdTesting"
  40. sftpServerAddr = "127.0.0.1:2022"
  41. defaultUsername = "test_user_sftp"
  42. defaultPassword = "test_password"
  43. testPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  44. testPubKey1 = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCd60+/j+y8f0tLftihWV1YN9RSahMI9btQMDIMqts/jeNbD8jgoogM3nhF7KxfcaMKURuD47KC4Ey6iAJUJ0sWkSNNxOcIYuvA+5MlspfZDsa8Ag76Fe1vyz72WeHMHMeh/hwFo2TeIeIXg480T1VI6mzfDrVp2GzUx0SS0dMsQBjftXkuVR8YOiOwMCAH2a//M1OrvV7d/NBk6kBN0WnuIBb2jKm15PAA7+jQQG7tzwk2HedNH3jeL5GH31xkSRwlBczRK0xsCQXehAlx6cT/e/s44iJcJTHfpPKoSk6UAhPJYe7Z1QnuoawY9P9jQaxpyeImBZxxUEowhjpj2avBxKdRGBVK8R7EL8tSOeLbhdyWe5Mwc1+foEbq9Zz5j5Kd+hn3Wm1UnsGCrXUUUoZp1jnlNl0NakCto+5KmqnT9cHxaY+ix2RLUWAZyVFlRq71OYux1UHJnEJPiEI1/tr4jFBSL46qhQZv/TfpkfVW8FLz0lErfqu0gQEZnNHr3Fc= nicola@p1"
  45. testPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
  46. b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
  47. NhAAAAAwEAAQAAAYEAtN449A/nY5O6cSH/9Doa8a3ISU0WZJaHydTaCLuO+dkqtNpnV5mq
  48. zFbKidXAI1eSwVctw9ReVOl1uK6aZF3lbXdOD8W9PXobR9KUUT2qBx5QC4ibfAqDKWymDA
  49. PG9ylzz64hsYBqJr7VNk9kTFEUsDmWzLabLoH42Elnp8mF/lTkWIcpVp0ly/etS08gttXo
  50. XenekJ1vRuxOYWDCEzGPU7kGc920TmM14k7IDdPoOh5+3sRUKedKeOUrVDH1f0n7QjHQsZ
  51. cbshp8tgqzf734zu8cTqNrr+6taptdEOOij1iUL/qYGfzny/hA48tO5+UFUih5W8ftp0+E
  52. NBIDkkGgk2MJ92I7QAXyMVsIABXco+mJT7pQi9tqlODGIQ3AOj0gcA3X/Ib8QX77Ih3TPi
  53. XEh77/P1XiYZOgpp2cRmNH8QbqaL9u898hDvJwIPJPuj2lIltTElH7hjBf5LQfCzrLV7BD
  54. 10rM7sl4jr+A2q8jl1Ikp+25kainBBZSbrDummT9AAAFgDU/VLk1P1S5AAAAB3NzaC1yc2
  55. EAAAGBALTeOPQP52OTunEh//Q6GvGtyElNFmSWh8nU2gi7jvnZKrTaZ1eZqsxWyonVwCNX
  56. ksFXLcPUXlTpdbiummRd5W13Tg/FvT16G0fSlFE9qgceUAuIm3wKgylspgwDxvcpc8+uIb
  57. GAaia+1TZPZExRFLA5lsy2my6B+NhJZ6fJhf5U5FiHKVadJcv3rUtPILbV6F3p3pCdb0bs
  58. TmFgwhMxj1O5BnPdtE5jNeJOyA3T6Doeft7EVCnnSnjlK1Qx9X9J+0Ix0LGXG7IafLYKs3
  59. +9+M7vHE6ja6/urWqbXRDjoo9YlC/6mBn858v4QOPLTuflBVIoeVvH7adPhDQSA5JBoJNj
  60. CfdiO0AF8jFbCAAV3KPpiU+6UIvbapTgxiENwDo9IHAN1/yG/EF++yId0z4lxIe+/z9V4m
  61. GToKadnEZjR/EG6mi/bvPfIQ7ycCDyT7o9pSJbUxJR+4YwX+S0Hws6y1ewQ9dKzO7JeI6/
  62. gNqvI5dSJKftuZGopwQWUm6w7ppk/QAAAAMBAAEAAAGAHKnC+Nq0XtGAkIFE4N18e6SAwy
  63. 0WSWaZqmCzFQM0S2AhJnweOIG/0ZZHjsRzKKauOTmppQk40dgVsejpytIek9R+aH172gxJ
  64. 2n4Cx0UwduRU5x8FFQlNc/kl722B0JWfJuB/snOZXv6LJ4o5aObIkozt2w9tVFeAqjYn2S
  65. 1UsNOfRHBXGsTYwpRDwFWP56nKo2d2wBBTHDhCy6fb2dLW1fvSi/YspueOGIlHpvlYKi2/
  66. CWqvs9xVrwcScMtiDoQYq0khhO0efLCxvg/o+W9CLMVM2ms4G1zoSUQKN0oYWWQJyW4+VI
  67. YneWO8UpN0J3ElXKi7bhgAat7dBaM1g9IrAzk153DiEFZNsPxGOgL/+YdQN7zUBx/z7EkI
  68. jyv80RV7fpUXvcq2p+qNl6UVig3VSzRrnsaJkUWu/A0u59ha7ocv6NxDIXjxpIDJme16GF
  69. quiGVBQNnYJymS/vFEbGf6bgf7iRmMCRUMG4nqLA6fPYP9uAtch+CmDfVLZC/fIdC5AAAA
  70. wQCDissV4zH6bfqgxJSuYNk8Vbb+19cF3b7gH1rVlB3zxpCAgcRgMHC+dP1z2NRx7UW9MR
  71. nye6kjpkzZZ0OigLqo7TtEq8uTglD9o6W7mRXqhy5A/ySOmqPL3ernHHQhGuoNODYAHkOU
  72. u2Rh8HXi+VLwKZcLInPOYJvcuLG4DxN8WfeVvlMHwhAOaTNNOtL4XZDHQeIPc4qHmJymmv
  73. sV7GuyQ6yW5C10uoGdxRPd90Bh4z4h2bKfZFjvEBbSBVkqrlAAAADBAN/zNtNayd/dX7Cr
  74. Nb4sZuzCh+CW4BH8GOePZWNCATwBbNXBVb5cR+dmuTqYm+Ekz0VxVQRA1TvKncluJOQpoa
  75. Xj8r0xdIgqkehnfDPMKtYVor06B9Fl1jrXtXU0Vrr6QcBWruSVyK1ZxqcmcNK/+KolVepe
  76. A6vcl/iKaG4U7su166nxLST06M2EgcSVsFJHpKn5+WAXC+X0Gx8kNjWIIb3GpiChdc0xZD
  77. mq02xZthVJrTCVw/e7gfDoB2QRsNV8HwAAAMEAzsCghZVp+0YsYg9oOrw4tEqcbEXEMhwY
  78. 0jW8JNL8Spr1Ibp5Dw6bRSk5azARjmJtnMJhJ3oeHfF0eoISqcNuQXGndGQbVM9YzzAzc1
  79. NbbCNsVroqKlChT5wyPNGS+phi2bPARBno7WSDvshTZ7dAVEP2c9MJW0XwoSevwKlhgSdt
  80. RLFFQ/5nclJSdzPBOmQouC0OBcMFSrYtMeknJ4VvueVvve5HcHFaEsaMc7ABAGaLYaBQOm
  81. iixITGvaNZh/tjAAAACW5pY29sYUBwMQE=
  82. -----END OPENSSH PRIVATE KEY-----`
  83. configDir = ".."
  84. )
  85. var (
  86. allPerms = []string{dataprovider.PermAny}
  87. homeBasePath string
  88. scpPath string
  89. gitPath string
  90. sshPath string
  91. pubKeyPath string
  92. privateKeyPath string
  93. gitWrapPath string
  94. extAuthPath string
  95. keyIntAuthPath string
  96. logFilePath string
  97. )
  98. func TestMain(m *testing.M) {
  99. logFilePath = filepath.Join(configDir, "sftpgo_sftpd_test.log")
  100. loginBannerFileName := "login_banner"
  101. loginBannerFile := filepath.Join(configDir, loginBannerFileName)
  102. ioutil.WriteFile(loginBannerFile, []byte("simple login banner\n"), 0777)
  103. logger.InitLogger(logFilePath, 5, 1, 28, false, zerolog.DebugLevel)
  104. config.LoadConfig(configDir, "")
  105. providerConf := config.GetProviderConf()
  106. err := dataprovider.Initialize(providerConf, configDir)
  107. if err != nil {
  108. logger.Warn(logSender, "", "error initializing data provider: %v", err)
  109. os.Exit(1)
  110. }
  111. dataProvider := dataprovider.GetProvider()
  112. sftpdConf := config.GetSFTPDConfig()
  113. httpdConf := config.GetHTTPDConfig()
  114. sftpdConf.BindPort = 2022
  115. sftpdConf.KexAlgorithms = []string{"[email protected]", "ecdh-sha2-nistp256",
  116. "ecdh-sha2-nistp384"}
  117. sftpdConf.Ciphers = []string{"[email protected]", "[email protected]",
  118. "aes256-ctr"}
  119. sftpdConf.MACs = []string{"[email protected]", "hmac-sha2-256"}
  120. sftpdConf.LoginBannerFile = loginBannerFileName
  121. // we need to test all supported ssh commands
  122. sftpdConf.EnabledSSHCommands = []string{"*"}
  123. // we run the test cases with UploadMode atomic and resume support. The non atomic code path
  124. // simply does not execute some code so if it works in atomic mode will
  125. // work in non atomic mode too
  126. sftpdConf.UploadMode = 2
  127. homeBasePath = os.TempDir()
  128. var scriptArgs string
  129. if runtime.GOOS == "windows" {
  130. scriptArgs = "%*"
  131. } else {
  132. sftpdConf.Actions.ExecuteOn = []string{"download", "upload", "rename", "delete", "ssh_cmd"}
  133. sftpdConf.Actions.Command = "/usr/bin/true"
  134. sftpdConf.Actions.HTTPNotificationURL = "http://127.0.0.1:8083/"
  135. scriptArgs = "$@"
  136. }
  137. keyIntAuthPath = filepath.Join(homeBasePath, "keyintauth.sh")
  138. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  139. sftpdConf.KeyboardInteractiveProgram = keyIntAuthPath
  140. scpPath, err = exec.LookPath("scp")
  141. if err != nil {
  142. logger.Warn(logSender, "", "unable to get scp command. SCP tests will be skipped, err: %v", err)
  143. logger.WarnToConsole("unable to get scp command. SCP tests will be skipped, err: %v", err)
  144. scpPath = ""
  145. }
  146. gitPath, err = exec.LookPath("git")
  147. if err != nil {
  148. logger.Warn(logSender, "", "unable to get git command. GIT tests will be skipped, err: %v", err)
  149. logger.WarnToConsole("unable to get git command. GIT tests will be skipped, err: %v", err)
  150. gitPath = ""
  151. }
  152. sshPath, err = exec.LookPath("ssh")
  153. if err != nil {
  154. logger.Warn(logSender, "", "unable to get ssh command. GIT tests will be skipped, err: %v", err)
  155. logger.WarnToConsole("unable to get ssh command. GIT tests will be skipped, err: %v", err)
  156. gitPath = ""
  157. }
  158. pubKeyPath = filepath.Join(homeBasePath, "ssh_key.pub")
  159. privateKeyPath = filepath.Join(homeBasePath, "ssh_key")
  160. gitWrapPath = filepath.Join(homeBasePath, "gitwrap.sh")
  161. extAuthPath = filepath.Join(homeBasePath, "extauth.sh")
  162. err = ioutil.WriteFile(pubKeyPath, []byte(testPubKey+"\n"), 0600)
  163. if err != nil {
  164. logger.WarnToConsole("unable to save public key to file: %v", err)
  165. }
  166. err = ioutil.WriteFile(privateKeyPath, []byte(testPrivateKey+"\n"), 0600)
  167. if err != nil {
  168. logger.WarnToConsole("unable to save private key to file: %v", err)
  169. }
  170. err = ioutil.WriteFile(gitWrapPath, []byte(fmt.Sprintf("%v -i %v -oStrictHostKeyChecking=no %v\n",
  171. sshPath, privateKeyPath, scriptArgs)), 0755)
  172. if err != nil {
  173. logger.WarnToConsole("unable to save gitwrap shell script: %v", err)
  174. }
  175. sftpd.SetDataProvider(dataProvider)
  176. httpd.SetDataProvider(dataProvider)
  177. go func() {
  178. logger.Debug(logSender, "", "initializing SFTP server with config %+v", sftpdConf)
  179. if err := sftpdConf.Initialize(configDir); err != nil {
  180. logger.Error(logSender, "", "could not start SFTP server: %v", err)
  181. }
  182. }()
  183. go func() {
  184. if err := httpdConf.Initialize(configDir); err != nil {
  185. logger.Error(logSender, "", "could not start HTTP server: %v", err)
  186. }
  187. }()
  188. waitTCPListening(fmt.Sprintf("%s:%d", sftpdConf.BindAddress, sftpdConf.BindPort))
  189. waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort))
  190. exitCode := m.Run()
  191. os.Remove(logFilePath)
  192. os.Remove(loginBannerFile)
  193. os.Remove(pubKeyPath)
  194. os.Remove(privateKeyPath)
  195. os.Remove(gitWrapPath)
  196. os.Remove(extAuthPath)
  197. os.Remove(keyIntAuthPath)
  198. os.Exit(exitCode)
  199. }
  200. func TestInitialization(t *testing.T) {
  201. config.LoadConfig(configDir, "")
  202. sftpdConf := config.GetSFTPDConfig()
  203. sftpdConf.Umask = "invalid umask"
  204. sftpdConf.BindPort = 2022
  205. sftpdConf.LoginBannerFile = "invalid_file"
  206. sftpdConf.IsSCPEnabled = true
  207. sftpdConf.EnabledSSHCommands = append(sftpdConf.EnabledSSHCommands, "ls")
  208. err := sftpdConf.Initialize(configDir)
  209. if err == nil {
  210. t.Error("Inizialize must fail, a SFTP server should be already running")
  211. }
  212. sftpdConf.KeyboardInteractiveProgram = "invalid_file"
  213. err = sftpdConf.Initialize(configDir)
  214. if err == nil {
  215. t.Error("Inizialize must fail, a SFTP server should be already running")
  216. }
  217. sftpdConf.KeyboardInteractiveProgram = filepath.Join(homeBasePath, "invalid_file")
  218. err = sftpdConf.Initialize(configDir)
  219. if err == nil {
  220. t.Error("Inizialize must fail, a SFTP server should be already running")
  221. }
  222. }
  223. func TestBasicSFTPHandling(t *testing.T) {
  224. usePubKey := false
  225. u := getTestUser(usePubKey)
  226. u.QuotaSize = 6553600
  227. user, _, err := httpd.AddUser(u, http.StatusOK)
  228. if err != nil {
  229. t.Errorf("unable to add user: %v", err)
  230. }
  231. os.RemoveAll(user.GetHomeDir())
  232. client, err := getSftpClient(user, usePubKey)
  233. if err != nil {
  234. t.Errorf("unable to create sftp client: %v", err)
  235. } else {
  236. defer client.Close()
  237. testFileName := "test_file.dat"
  238. testFilePath := filepath.Join(homeBasePath, testFileName)
  239. testFileSize := int64(65535)
  240. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  241. expectedQuotaFiles := user.UsedQuotaFiles + 1
  242. createTestFile(testFilePath, testFileSize)
  243. err = sftpUploadFile(testFilePath, path.Join("/missing_dir", testFileName), testFileSize, client)
  244. if err == nil {
  245. t.Errorf("upload a file to a missing dir must fail")
  246. }
  247. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  248. if err != nil {
  249. t.Errorf("file upload error: %v", err)
  250. }
  251. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  252. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  253. if err != nil {
  254. t.Errorf("file download error: %v", err)
  255. }
  256. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  257. if err != nil {
  258. t.Errorf("error getting user: %v", err)
  259. }
  260. if expectedQuotaFiles != user.UsedQuotaFiles {
  261. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  262. }
  263. if expectedQuotaSize != user.UsedQuotaSize {
  264. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  265. }
  266. err = client.Remove(testFileName)
  267. if err != nil {
  268. t.Errorf("error removing uploaded file: %v", err)
  269. }
  270. _, err = client.Lstat(testFileName)
  271. if err == nil {
  272. t.Errorf("stat for deleted file must not succeed")
  273. }
  274. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  275. if err != nil {
  276. t.Errorf("error getting user: %v", err)
  277. }
  278. if (expectedQuotaFiles - 1) != user.UsedQuotaFiles {
  279. t.Errorf("quota files does not match after delete, expected: %v, actual: %v", expectedQuotaFiles-1, user.UsedQuotaFiles)
  280. }
  281. if (expectedQuotaSize - testFileSize) != user.UsedQuotaSize {
  282. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize-testFileSize, user.UsedQuotaSize)
  283. }
  284. os.Remove(testFilePath)
  285. os.Remove(localDownloadPath)
  286. }
  287. _, err = httpd.RemoveUser(user, http.StatusOK)
  288. if err != nil {
  289. t.Errorf("unable to remove user: %v", err)
  290. }
  291. os.RemoveAll(user.GetHomeDir())
  292. }
  293. func TestUploadResume(t *testing.T) {
  294. usePubKey := false
  295. u := getTestUser(usePubKey)
  296. user, _, err := httpd.AddUser(u, http.StatusOK)
  297. if err != nil {
  298. t.Errorf("unable to add user: %v", err)
  299. }
  300. os.RemoveAll(user.GetHomeDir())
  301. client, err := getSftpClient(user, usePubKey)
  302. if err != nil {
  303. t.Errorf("unable to create sftp client: %v", err)
  304. } else {
  305. defer client.Close()
  306. testFileName := "test_file.dat"
  307. testFilePath := filepath.Join(homeBasePath, testFileName)
  308. testFileSize := int64(65535)
  309. appendDataSize := int64(65535)
  310. err = createTestFile(testFilePath, testFileSize)
  311. if err != nil {
  312. t.Errorf("unable to create test file: %v", err)
  313. }
  314. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  315. if err != nil {
  316. t.Errorf("file upload error: %v", err)
  317. }
  318. err = appendToTestFile(testFilePath, appendDataSize)
  319. if err != nil {
  320. t.Errorf("unable to append to test file: %v", err)
  321. }
  322. err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, false, client)
  323. if err != nil {
  324. t.Errorf("file upload resume error: %v", err)
  325. }
  326. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  327. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize+appendDataSize, client)
  328. if err != nil {
  329. t.Errorf("file download error: %v", err)
  330. }
  331. initialHash, err := computeHashForFile(sha256.New(), testFilePath)
  332. if err != nil {
  333. t.Errorf("error computing file hash: %v", err)
  334. }
  335. donwloadedFileHash, err := computeHashForFile(sha256.New(), localDownloadPath)
  336. if err != nil {
  337. t.Errorf("error computing downloaded file hash: %v", err)
  338. }
  339. if donwloadedFileHash != initialHash {
  340. t.Errorf("resume failed: file hash does not match")
  341. }
  342. err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, true, client)
  343. if err == nil {
  344. t.Errorf("file upload resume with invalid offset must fail")
  345. }
  346. os.Remove(testFilePath)
  347. os.Remove(localDownloadPath)
  348. }
  349. _, err = httpd.RemoveUser(user, http.StatusOK)
  350. if err != nil {
  351. t.Errorf("unable to remove user: %v", err)
  352. }
  353. os.RemoveAll(user.GetHomeDir())
  354. }
  355. func TestDirCommands(t *testing.T) {
  356. usePubKey := false
  357. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  358. if err != nil {
  359. t.Errorf("unable to add user: %v", err)
  360. }
  361. // remove the home dir to test auto creation
  362. os.RemoveAll(user.HomeDir)
  363. client, err := getSftpClient(user, usePubKey)
  364. if err != nil {
  365. t.Errorf("unable to create sftp client: %v", err)
  366. } else {
  367. defer client.Close()
  368. err = client.Mkdir("test1")
  369. if err != nil {
  370. t.Errorf("error mkdir: %v", err)
  371. }
  372. err = client.Rename("test1", "test")
  373. if err != nil {
  374. t.Errorf("error rename: %v", err)
  375. }
  376. _, err = client.Lstat("/test1")
  377. if err == nil {
  378. t.Errorf("stat for renamed dir must not succeed")
  379. }
  380. err = client.PosixRename("test", "test1")
  381. if err != nil {
  382. t.Errorf("error posix rename: %v", err)
  383. }
  384. err = client.Remove("test1")
  385. if err != nil {
  386. t.Errorf("error rmdir: %v", err)
  387. }
  388. err = client.Mkdir("/test/test1")
  389. if err == nil {
  390. t.Errorf("recursive mkdir must fail")
  391. }
  392. client.Mkdir("/test")
  393. err = client.Mkdir("/test/test1")
  394. if err != nil {
  395. t.Errorf("mkdir dir error: %v", err)
  396. }
  397. _, err = client.ReadDir("/this/dir/does/not/exist")
  398. if err == nil {
  399. t.Errorf("reading a missing dir must fail")
  400. }
  401. err = client.RemoveDirectory("/test/test1")
  402. if err != nil {
  403. t.Errorf("remove dir error: %v", err)
  404. }
  405. err = client.RemoveDirectory("/test")
  406. if err != nil {
  407. t.Errorf("remove dir error: %v", err)
  408. }
  409. _, err = client.Lstat("/test")
  410. if err == nil {
  411. t.Errorf("stat for deleted dir must not succeed")
  412. }
  413. err = client.RemoveDirectory("/test")
  414. if err == nil {
  415. t.Errorf("remove missing path must fail")
  416. }
  417. }
  418. httpd.RemoveUser(user, http.StatusOK)
  419. os.RemoveAll(user.GetHomeDir())
  420. }
  421. func TestRemove(t *testing.T) {
  422. usePubKey := true
  423. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  424. if err != nil {
  425. t.Errorf("unable to add user: %v", err)
  426. }
  427. client, err := getSftpClient(user, usePubKey)
  428. if err != nil {
  429. t.Errorf("unable to create sftp client: %v", err)
  430. } else {
  431. defer client.Close()
  432. err = client.Mkdir("test")
  433. if err != nil {
  434. t.Errorf("error mkdir: %v", err)
  435. }
  436. err = client.Mkdir("/test/test1")
  437. if err != nil {
  438. t.Errorf("error mkdir subdir: %v", err)
  439. }
  440. testFileName := "/test_file.dat"
  441. testFilePath := filepath.Join(homeBasePath, testFileName)
  442. testFileSize := int64(65535)
  443. err = createTestFile(testFilePath, testFileSize)
  444. if err != nil {
  445. t.Errorf("unable to create test file: %v", err)
  446. }
  447. err = sftpUploadFile(testFilePath, path.Join("/test", testFileName), testFileSize, client)
  448. if err != nil {
  449. t.Errorf("file upload error: %v", err)
  450. }
  451. err = client.Remove("/test")
  452. if err == nil {
  453. t.Errorf("remove non empty dir must fail")
  454. }
  455. err = client.RemoveDirectory(path.Join("/test", testFileName))
  456. if err == nil {
  457. t.Errorf("remove a file with rmdir must fail")
  458. }
  459. err = client.Remove(path.Join("/test", testFileName))
  460. if err != nil {
  461. t.Errorf("remove file error: %v", err)
  462. }
  463. err = client.Remove(path.Join("/test", testFileName))
  464. if err == nil {
  465. t.Errorf("remove missing file must fail")
  466. }
  467. err = client.Remove("/test/test1")
  468. if err != nil {
  469. t.Errorf("remove dir error: %v", err)
  470. }
  471. err = client.Remove("/test")
  472. if err != nil {
  473. t.Errorf("remove dir error: %v", err)
  474. }
  475. os.Remove(testFilePath)
  476. }
  477. _, err = httpd.RemoveUser(user, http.StatusOK)
  478. if err != nil {
  479. t.Errorf("unable to remove user: %v", err)
  480. }
  481. os.RemoveAll(user.GetHomeDir())
  482. }
  483. func TestLink(t *testing.T) {
  484. usePubKey := false
  485. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  486. if err != nil {
  487. t.Errorf("unable to add user: %v", err)
  488. }
  489. client, err := getSftpClient(user, usePubKey)
  490. if err != nil {
  491. t.Errorf("unable to create sftp client: %v", err)
  492. } else {
  493. defer client.Close()
  494. testFileName := "test_file.dat"
  495. testFilePath := filepath.Join(homeBasePath, testFileName)
  496. testFileSize := int64(65535)
  497. err = createTestFile(testFilePath, testFileSize)
  498. if err != nil {
  499. t.Errorf("unable to create test file: %v", err)
  500. }
  501. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  502. if err != nil {
  503. t.Errorf("file upload error: %v", err)
  504. }
  505. err = client.Symlink(testFileName, testFileName+".link")
  506. if err != nil {
  507. t.Errorf("error creating symlink: %v", err)
  508. }
  509. _, err = client.ReadLink(testFileName + ".link")
  510. if err == nil {
  511. t.Errorf("readlink is currently not implemented so must fail")
  512. }
  513. err = client.Symlink(testFileName, testFileName+".link")
  514. if err == nil {
  515. t.Errorf("creating a symlink to an existing one must fail")
  516. }
  517. err = client.Link(testFileName, testFileName+".hlink")
  518. if err == nil {
  519. t.Errorf("hard link is not supported and must fail")
  520. }
  521. err = client.Remove(testFileName + ".link")
  522. if err != nil {
  523. t.Errorf("error removing symlink: %v", err)
  524. }
  525. err = client.Remove(testFileName)
  526. if err != nil {
  527. t.Errorf("error removing uploaded file: %v", err)
  528. }
  529. os.Remove(testFilePath)
  530. }
  531. _, err = httpd.RemoveUser(user, http.StatusOK)
  532. if err != nil {
  533. t.Errorf("unable to remove user: %v", err)
  534. }
  535. os.RemoveAll(user.GetHomeDir())
  536. }
  537. func TestStat(t *testing.T) {
  538. usePubKey := false
  539. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  540. if err != nil {
  541. t.Errorf("unable to add user: %v", err)
  542. }
  543. client, err := getSftpClient(user, usePubKey)
  544. if err != nil {
  545. t.Errorf("unable to create sftp client: %v", err)
  546. } else {
  547. defer client.Close()
  548. testFileName := "test_file.dat"
  549. testFilePath := filepath.Join(homeBasePath, testFileName)
  550. testFileSize := int64(65535)
  551. createTestFile(testFilePath, testFileSize)
  552. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  553. if err != nil {
  554. t.Errorf("file upload error: %v", err)
  555. }
  556. _, err := client.Lstat(testFileName)
  557. if err != nil {
  558. t.Errorf("stat error: %v", err)
  559. }
  560. // mode 0666 and 0444 works on Windows too
  561. newPerm := os.FileMode(0666)
  562. err = client.Chmod(testFileName, newPerm)
  563. if err != nil {
  564. t.Errorf("chmod error: %v", err)
  565. }
  566. newFi, err := client.Lstat(testFileName)
  567. if err != nil {
  568. t.Errorf("stat error: %v", err)
  569. }
  570. if newPerm != newFi.Mode().Perm() {
  571. t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  572. }
  573. newPerm = os.FileMode(0444)
  574. err = client.Chmod(testFileName, newPerm)
  575. if err != nil {
  576. t.Errorf("chmod error: %v", err)
  577. }
  578. newFi, err = client.Lstat(testFileName)
  579. if err != nil {
  580. t.Errorf("stat error: %v", err)
  581. }
  582. if newPerm != newFi.Mode().Perm() {
  583. t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  584. }
  585. _, err = client.ReadLink(testFileName)
  586. if err == nil {
  587. t.Errorf("readlink is not supported and must fail")
  588. }
  589. err = client.Truncate(testFileName, 0)
  590. if err != nil {
  591. t.Errorf("truncate must be silently ignored: %v", err)
  592. }
  593. os.Remove(testFilePath)
  594. }
  595. _, err = httpd.RemoveUser(user, http.StatusOK)
  596. if err != nil {
  597. t.Errorf("unable to remove user: %v", err)
  598. }
  599. os.RemoveAll(user.GetHomeDir())
  600. }
  601. func TestStatChownChmod(t *testing.T) {
  602. if runtime.GOOS == "windows" {
  603. t.Skip("chown is not supported on Windows, chmod is partially supported")
  604. }
  605. usePubKey := true
  606. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  607. if err != nil {
  608. t.Errorf("unable to add user: %v", err)
  609. }
  610. client, err := getSftpClient(user, usePubKey)
  611. if err != nil {
  612. t.Errorf("unable to create sftp client: %v", err)
  613. } else {
  614. defer client.Close()
  615. testFileName := "test_file.dat"
  616. testFilePath := filepath.Join(homeBasePath, testFileName)
  617. testFileSize := int64(65535)
  618. createTestFile(testFilePath, testFileSize)
  619. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  620. if err != nil {
  621. t.Errorf("file upload error: %v", err)
  622. }
  623. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  624. if err != nil {
  625. t.Errorf("chown error: %v", err)
  626. }
  627. newPerm := os.FileMode(0600)
  628. err = client.Chmod(testFileName, newPerm)
  629. if err != nil {
  630. t.Errorf("chmod error: %v", err)
  631. }
  632. newFi, err := client.Lstat(testFileName)
  633. if err != nil {
  634. t.Errorf("stat error: %v", err)
  635. }
  636. if newPerm != newFi.Mode().Perm() {
  637. t.Errorf("chown failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  638. }
  639. err = client.Remove(testFileName)
  640. if err != nil {
  641. t.Errorf("error removing uploaded file: %v", err)
  642. }
  643. // l'errore viene riconvertito da sftp.ErrSSHFxNoSuchFile in os.ErrNotExist
  644. err = client.Chmod(testFileName, newPerm)
  645. if err != os.ErrNotExist {
  646. t.Errorf("unexpected chmod error: %v expected: %v", err, os.ErrNotExist)
  647. }
  648. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  649. if err != os.ErrNotExist {
  650. t.Errorf("unexpected chown error: %v expected: %v", err, os.ErrNotExist)
  651. }
  652. os.Remove(testFilePath)
  653. }
  654. _, err = httpd.RemoveUser(user, http.StatusOK)
  655. if err != nil {
  656. t.Errorf("unable to remove user: %v", err)
  657. }
  658. os.RemoveAll(user.GetHomeDir())
  659. }
  660. func TestChtimes(t *testing.T) {
  661. usePubKey := false
  662. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  663. if err != nil {
  664. t.Errorf("unable to add user: %v", err)
  665. }
  666. client, err := getSftpClient(user, usePubKey)
  667. if err != nil {
  668. t.Errorf("unable to create sftp client: %v", err)
  669. } else {
  670. defer client.Close()
  671. testFileName := "test_file.dat"
  672. testFilePath := filepath.Join(homeBasePath, testFileName)
  673. testFileSize := int64(65535)
  674. testDir := "test"
  675. createTestFile(testFilePath, testFileSize)
  676. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  677. if err != nil {
  678. t.Errorf("file upload error: %v", err)
  679. }
  680. acmodTime := time.Now()
  681. err = client.Chtimes(testFileName, acmodTime, acmodTime)
  682. if err != nil {
  683. t.Errorf("error changing file times")
  684. }
  685. newFi, err := client.Lstat(testFileName)
  686. if err != nil {
  687. t.Errorf("file stat error: %v", err)
  688. }
  689. diff := math.Abs(newFi.ModTime().Sub(acmodTime).Seconds())
  690. if diff > 1 {
  691. t.Errorf("diff between wanted and real modification time too big: %v", diff)
  692. }
  693. err = client.Chtimes("invalidFile", acmodTime, acmodTime)
  694. if !os.IsNotExist(err) {
  695. t.Errorf("unexpected error: %v", err)
  696. }
  697. err = client.Mkdir(testDir)
  698. if err != nil {
  699. t.Errorf("unable to create dir: %v", err)
  700. }
  701. err = client.Chtimes(testDir, acmodTime, acmodTime)
  702. if err != nil {
  703. t.Errorf("error changing dir times")
  704. }
  705. newFi, err = client.Lstat(testDir)
  706. if err != nil {
  707. t.Errorf("dir stat error: %v", err)
  708. }
  709. diff = math.Abs(newFi.ModTime().Sub(acmodTime).Seconds())
  710. if diff > 1 {
  711. t.Errorf("diff between wanted and real modification time too big: %v", diff)
  712. }
  713. os.Remove(testFilePath)
  714. }
  715. _, err = httpd.RemoveUser(user, http.StatusOK)
  716. if err != nil {
  717. t.Errorf("unable to remove user: %v", err)
  718. }
  719. os.RemoveAll(user.GetHomeDir())
  720. }
  721. // basic tests to verify virtual chroot, should be improved to cover more cases ...
  722. func TestEscapeHomeDir(t *testing.T) {
  723. usePubKey := true
  724. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  725. if err != nil {
  726. t.Errorf("unable to add user: %v", err)
  727. }
  728. client, err := getSftpClient(user, usePubKey)
  729. if err != nil {
  730. t.Errorf("unable to create sftp client: %v", err)
  731. } else {
  732. defer client.Close()
  733. _, err := client.Getwd()
  734. if err != nil {
  735. t.Errorf("unable to get working dir: %v", err)
  736. }
  737. testDir := "testDir"
  738. linkPath := filepath.Join(homeBasePath, defaultUsername, testDir)
  739. err = os.Symlink(homeBasePath, linkPath)
  740. if err != nil {
  741. t.Errorf("error making local symlink: %v", err)
  742. }
  743. _, err = client.ReadDir(testDir)
  744. if err == nil {
  745. t.Errorf("reading a symbolic link outside home dir should not succeeded")
  746. }
  747. os.Remove(linkPath)
  748. testFileName := "test_file.dat"
  749. testFilePath := filepath.Join(homeBasePath, testFileName)
  750. testFileSize := int64(65535)
  751. err = createTestFile(testFilePath, testFileSize)
  752. if err != nil {
  753. t.Errorf("unable to create test file: %v", err)
  754. }
  755. remoteDestPath := path.Join("..", "..", testFileName)
  756. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  757. if err != nil {
  758. t.Errorf("file upload error: %v", err)
  759. }
  760. _, err = client.Lstat(testFileName)
  761. if err != nil {
  762. t.Errorf("file stat error: %v the file was created outside the user dir!", err)
  763. }
  764. err = client.Remove(testFileName)
  765. if err != nil {
  766. t.Errorf("error removing uploaded file: %v", err)
  767. }
  768. linkPath = filepath.Join(homeBasePath, defaultUsername, testFileName)
  769. err = os.Symlink(homeBasePath, linkPath)
  770. if err != nil {
  771. t.Errorf("error making local symlink: %v", err)
  772. }
  773. err = sftpDownloadFile(testFileName, testFilePath, 0, client)
  774. if err == nil {
  775. t.Errorf("download file outside home dir must fail")
  776. }
  777. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  778. if err == nil {
  779. t.Errorf("overwrite a file outside home dir must fail")
  780. }
  781. err = client.Chmod(remoteDestPath, 0644)
  782. if err == nil {
  783. t.Errorf("setstat on a file outside home dir must fail")
  784. }
  785. os.Remove(linkPath)
  786. os.Remove(testFilePath)
  787. }
  788. _, err = httpd.RemoveUser(user, http.StatusOK)
  789. if err != nil {
  790. t.Errorf("unable to remove user: %v", err)
  791. }
  792. os.RemoveAll(user.GetHomeDir())
  793. }
  794. func TestHomeSpecialChars(t *testing.T) {
  795. usePubKey := true
  796. u := getTestUser(usePubKey)
  797. u.HomeDir = filepath.Join(homeBasePath, "abc açà#&%lk")
  798. user, _, err := httpd.AddUser(u, http.StatusOK)
  799. if err != nil {
  800. t.Errorf("unable to add user: %v", err)
  801. }
  802. client, err := getSftpClient(user, usePubKey)
  803. if err != nil {
  804. t.Errorf("unable to create sftp client: %v", err)
  805. } else {
  806. defer client.Close()
  807. _, err := client.Getwd()
  808. if err != nil {
  809. t.Errorf("unable to get working dir: %v", err)
  810. }
  811. testFileName := "test_file.dat"
  812. testFilePath := filepath.Join(homeBasePath, testFileName)
  813. testFileSize := int64(65535)
  814. err = createTestFile(testFilePath, testFileSize)
  815. if err != nil {
  816. t.Errorf("unable to create test file: %v", err)
  817. }
  818. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  819. if err != nil {
  820. t.Errorf("file upload error: %v", err)
  821. }
  822. files, err := client.ReadDir(".")
  823. if err != nil {
  824. t.Errorf("unable to read remote dir: %v", err)
  825. }
  826. if len(files) < 1 {
  827. t.Errorf("expected at least 1 file in this dir")
  828. }
  829. err = client.Remove(testFileName)
  830. if err != nil {
  831. t.Errorf("error removing uploaded file: %v", err)
  832. }
  833. os.Remove(testFilePath)
  834. }
  835. _, err = httpd.RemoveUser(user, http.StatusOK)
  836. if err != nil {
  837. t.Errorf("unable to remove user: %v", err)
  838. }
  839. os.RemoveAll(user.GetHomeDir())
  840. }
  841. func TestLogin(t *testing.T) {
  842. u := getTestUser(false)
  843. u.PublicKeys = []string{testPubKey}
  844. user, _, err := httpd.AddUser(u, http.StatusOK)
  845. if err != nil {
  846. t.Errorf("unable to add user: %v", err)
  847. }
  848. client, err := getSftpClient(user, false)
  849. if err != nil {
  850. t.Errorf("unable to create sftp client: %v", err)
  851. } else {
  852. defer client.Close()
  853. _, err := client.Getwd()
  854. if err != nil {
  855. t.Errorf("sftp client with valid password must work")
  856. }
  857. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  858. if err != nil {
  859. t.Errorf("error getting user: %v", err)
  860. }
  861. if user.LastLogin <= 0 {
  862. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  863. }
  864. }
  865. client, err = getSftpClient(user, true)
  866. if err != nil {
  867. t.Errorf("unable to create sftp client: %v", err)
  868. } else {
  869. defer client.Close()
  870. _, err := client.Getwd()
  871. if err != nil {
  872. t.Errorf("sftp client with valid public key must work")
  873. }
  874. }
  875. user.Password = "invalid password"
  876. client, err = getSftpClient(user, false)
  877. if err == nil {
  878. t.Errorf("login with invalid password must fail")
  879. defer client.Close()
  880. }
  881. // testPubKey1 is not authorized
  882. user.PublicKeys = []string{testPubKey1}
  883. user.Password = ""
  884. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  885. if err != nil {
  886. t.Errorf("unable to update user: %v", err)
  887. }
  888. client, err = getSftpClient(user, true)
  889. if err == nil {
  890. t.Errorf("login with invalid public key must fail")
  891. defer client.Close()
  892. }
  893. // login a user with multiple public keys, only the second one is valid
  894. user.PublicKeys = []string{testPubKey1, testPubKey}
  895. user.Password = ""
  896. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  897. if err != nil {
  898. t.Errorf("unable to update user: %v", err)
  899. }
  900. client, err = getSftpClient(user, true)
  901. if err != nil {
  902. t.Errorf("unable to create sftp client: %v", err)
  903. } else {
  904. defer client.Close()
  905. _, err := client.Getwd()
  906. if err != nil {
  907. t.Errorf("sftp client with multiple public key must work if at least one public key is valid")
  908. }
  909. }
  910. _, err = httpd.RemoveUser(user, http.StatusOK)
  911. if err != nil {
  912. t.Errorf("unable to remove user: %v", err)
  913. }
  914. os.RemoveAll(user.GetHomeDir())
  915. }
  916. func TestLoginUserStatus(t *testing.T) {
  917. usePubKey := true
  918. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  919. if err != nil {
  920. t.Errorf("unable to add user: %v", err)
  921. }
  922. client, err := getSftpClient(user, usePubKey)
  923. if err != nil {
  924. t.Errorf("unable to create sftp client: %v", err)
  925. } else {
  926. defer client.Close()
  927. _, err := client.Getwd()
  928. if err != nil {
  929. t.Errorf("sftp client with valid credentials must work")
  930. }
  931. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  932. if err != nil {
  933. t.Errorf("error getting user: %v", err)
  934. }
  935. if user.LastLogin <= 0 {
  936. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  937. }
  938. }
  939. user.Status = 0
  940. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  941. if err != nil {
  942. t.Errorf("unable to update user: %v", err)
  943. }
  944. client, err = getSftpClient(user, usePubKey)
  945. if err == nil {
  946. t.Errorf("login for a disabled user must fail")
  947. defer client.Close()
  948. }
  949. _, err = httpd.RemoveUser(user, http.StatusOK)
  950. if err != nil {
  951. t.Errorf("unable to remove user: %v", err)
  952. }
  953. os.RemoveAll(user.GetHomeDir())
  954. }
  955. func TestLoginUserExpiration(t *testing.T) {
  956. usePubKey := true
  957. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  958. if err != nil {
  959. t.Errorf("unable to add user: %v", err)
  960. }
  961. client, err := getSftpClient(user, usePubKey)
  962. if err != nil {
  963. t.Errorf("unable to create sftp client: %v", err)
  964. } else {
  965. defer client.Close()
  966. _, err := client.Getwd()
  967. if err != nil {
  968. t.Errorf("sftp client with valid credentials must work")
  969. }
  970. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  971. if err != nil {
  972. t.Errorf("error getting user: %v", err)
  973. }
  974. if user.LastLogin <= 0 {
  975. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  976. }
  977. }
  978. user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) - 120000
  979. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  980. if err != nil {
  981. t.Errorf("unable to update user: %v", err)
  982. }
  983. client, err = getSftpClient(user, usePubKey)
  984. if err == nil {
  985. t.Errorf("login for an expired user must fail")
  986. defer client.Close()
  987. }
  988. user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) + 120000
  989. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  990. if err != nil {
  991. t.Errorf("unable to update user: %v", err)
  992. }
  993. client, err = getSftpClient(user, usePubKey)
  994. if err != nil {
  995. t.Errorf("login for a non expired user must succeed: %v", err)
  996. } else {
  997. defer client.Close()
  998. }
  999. _, err = httpd.RemoveUser(user, http.StatusOK)
  1000. if err != nil {
  1001. t.Errorf("unable to remove user: %v", err)
  1002. }
  1003. os.RemoveAll(user.GetHomeDir())
  1004. }
  1005. func TestLoginInvalidFs(t *testing.T) {
  1006. if runtime.GOOS == "windows" {
  1007. t.Skip("this test is not available on Windows")
  1008. }
  1009. config.LoadConfig(configDir, "")
  1010. providerConf := config.GetProviderConf()
  1011. if providerConf.Driver != dataprovider.SQLiteDataProviderName {
  1012. t.Skip("this test require sqlite provider")
  1013. }
  1014. dbPath := providerConf.Name
  1015. if !filepath.IsAbs(dbPath) {
  1016. dbPath = filepath.Join(configDir, dbPath)
  1017. }
  1018. usePubKey := true
  1019. u := getTestUser(usePubKey)
  1020. user, _, err := httpd.AddUser(u, http.StatusOK)
  1021. if err != nil {
  1022. t.Errorf("unable to add user: %v", err)
  1023. }
  1024. // we update the database using sqlite3 CLI since we cannot add an user with an invalid config
  1025. time.Sleep(200 * time.Millisecond)
  1026. updateUserQuery := fmt.Sprintf("UPDATE users SET filesystem='{\"provider\":1}' WHERE id=%v", user.ID)
  1027. cmd := exec.Command("sqlite3", dbPath, updateUserQuery)
  1028. out, err := cmd.CombinedOutput()
  1029. if err != nil {
  1030. t.Errorf("unexpected error: %v, cmd out: %v", err, string(out))
  1031. }
  1032. time.Sleep(200 * time.Millisecond)
  1033. _, err = getSftpClient(user, usePubKey)
  1034. if err == nil {
  1035. t.Error("login must fail, the user has an invalid filesystem config")
  1036. }
  1037. _, err = httpd.RemoveUser(user, http.StatusOK)
  1038. if err != nil {
  1039. t.Errorf("unable to remove user: %v", err)
  1040. }
  1041. os.RemoveAll(user.GetHomeDir())
  1042. }
  1043. func TestLoginWithIPFilters(t *testing.T) {
  1044. usePubKey := true
  1045. u := getTestUser(usePubKey)
  1046. u.Filters.DeniedIP = []string{"192.167.0.0/24", "172.18.0.0/16"}
  1047. u.Filters.AllowedIP = []string{}
  1048. user, _, err := httpd.AddUser(u, http.StatusOK)
  1049. if err != nil {
  1050. t.Errorf("unable to add user: %v", err)
  1051. }
  1052. client, err := getSftpClient(user, usePubKey)
  1053. if err != nil {
  1054. t.Errorf("unable to create sftp client: %v", err)
  1055. } else {
  1056. defer client.Close()
  1057. _, err := client.Getwd()
  1058. if err != nil {
  1059. t.Errorf("sftp client with valid credentials must work")
  1060. }
  1061. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1062. if err != nil {
  1063. t.Errorf("error getting user: %v", err)
  1064. }
  1065. if user.LastLogin <= 0 {
  1066. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  1067. }
  1068. }
  1069. user.Filters.AllowedIP = []string{"127.0.0.0/8"}
  1070. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1071. if err != nil {
  1072. t.Errorf("unable to update user: %v", err)
  1073. }
  1074. client, err = getSftpClient(user, usePubKey)
  1075. if err != nil {
  1076. t.Errorf("login from an allowed IP must succeed: %v", err)
  1077. } else {
  1078. defer client.Close()
  1079. }
  1080. user.Filters.AllowedIP = []string{"172.19.0.0/16"}
  1081. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1082. if err != nil {
  1083. t.Errorf("unable to update user: %v", err)
  1084. }
  1085. client, err = getSftpClient(user, usePubKey)
  1086. if err == nil {
  1087. t.Errorf("login from an not allowed IP must fail")
  1088. client.Close()
  1089. }
  1090. _, err = httpd.RemoveUser(user, http.StatusOK)
  1091. if err != nil {
  1092. t.Errorf("unable to remove user: %v", err)
  1093. }
  1094. os.RemoveAll(user.GetHomeDir())
  1095. }
  1096. func TestLoginAfterUserUpdateEmptyPwd(t *testing.T) {
  1097. usePubKey := false
  1098. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1099. if err != nil {
  1100. t.Errorf("unable to add user: %v", err)
  1101. }
  1102. user.Password = ""
  1103. user.PublicKeys = []string{}
  1104. // password and public key should remain unchanged
  1105. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1106. if err != nil {
  1107. t.Errorf("unable to update 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. _, err := client.Getwd()
  1115. if err != nil {
  1116. t.Errorf("unable to get working dir: %v", err)
  1117. }
  1118. _, err = client.ReadDir(".")
  1119. if err != nil {
  1120. t.Errorf("unable to read remote dir: %v", err)
  1121. }
  1122. }
  1123. _, err = httpd.RemoveUser(user, http.StatusOK)
  1124. if err != nil {
  1125. t.Errorf("unable to remove user: %v", err)
  1126. }
  1127. os.RemoveAll(user.GetHomeDir())
  1128. }
  1129. func TestLoginAfterUserUpdateEmptyPubKey(t *testing.T) {
  1130. usePubKey := true
  1131. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1132. if err != nil {
  1133. t.Errorf("unable to add user: %v", err)
  1134. }
  1135. user.Password = ""
  1136. user.PublicKeys = []string{}
  1137. // password and public key should remain unchanged
  1138. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1139. if err != nil {
  1140. t.Errorf("unable to update user: %v", err)
  1141. }
  1142. client, err := getSftpClient(user, usePubKey)
  1143. if err != nil {
  1144. t.Errorf("unable to create sftp client: %v", err)
  1145. } else {
  1146. defer client.Close()
  1147. _, err := client.Getwd()
  1148. if err != nil {
  1149. t.Errorf("unable to get working dir: %v", err)
  1150. }
  1151. _, err = client.ReadDir(".")
  1152. if err != nil {
  1153. t.Errorf("unable to read remote dir: %v", err)
  1154. }
  1155. }
  1156. _, err = httpd.RemoveUser(user, http.StatusOK)
  1157. if err != nil {
  1158. t.Errorf("unable to remove user: %v", err)
  1159. }
  1160. os.RemoveAll(user.GetHomeDir())
  1161. }
  1162. func TestLoginKeyboardInteractiveAuth(t *testing.T) {
  1163. if runtime.GOOS == "windows" {
  1164. t.Skip("this test is not available on Windows")
  1165. }
  1166. user, _, err := httpd.AddUser(getTestUser(false), http.StatusOK)
  1167. if err != nil {
  1168. t.Errorf("unable to add user: %v", err)
  1169. }
  1170. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  1171. client, err := getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1172. if err != nil {
  1173. t.Errorf("unable to create sftp client: %v", err)
  1174. } else {
  1175. defer client.Close()
  1176. _, err := client.Getwd()
  1177. if err != nil {
  1178. t.Errorf("unable to get working dir: %v", err)
  1179. }
  1180. _, err = client.ReadDir(".")
  1181. if err != nil {
  1182. t.Errorf("unable to read remote dir: %v", err)
  1183. }
  1184. }
  1185. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, -1), 0755)
  1186. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1187. if err == nil {
  1188. t.Error("keyboard interactive auth must fail the script returned -1")
  1189. }
  1190. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, true, 1), 0755)
  1191. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1192. if err == nil {
  1193. t.Error("keyboard interactive auth must fail the script returned bad json")
  1194. }
  1195. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 5, true, 1), 0755)
  1196. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1197. if err == nil {
  1198. t.Error("keyboard interactive auth must fail the script returned bad json")
  1199. }
  1200. _, err = httpd.RemoveUser(user, http.StatusOK)
  1201. if err != nil {
  1202. t.Errorf("unable to remove user: %v", err)
  1203. }
  1204. os.RemoveAll(user.GetHomeDir())
  1205. }
  1206. func TestLoginExternalAuthPwdAndPubKey(t *testing.T) {
  1207. if runtime.GOOS == "windows" {
  1208. t.Skip("this test is not available on Windows")
  1209. }
  1210. usePubKey := true
  1211. u := getTestUser(usePubKey)
  1212. u.QuotaFiles = 1000
  1213. dataProvider := dataprovider.GetProvider()
  1214. dataprovider.Close(dataProvider)
  1215. config.LoadConfig(configDir, "")
  1216. providerConf := config.GetProviderConf()
  1217. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1218. providerConf.ExternalAuthProgram = extAuthPath
  1219. providerConf.ExternalAuthScope = 0
  1220. err := dataprovider.Initialize(providerConf, configDir)
  1221. if err != nil {
  1222. t.Errorf("error initializing data provider")
  1223. }
  1224. httpd.SetDataProvider(dataprovider.GetProvider())
  1225. sftpd.SetDataProvider(dataprovider.GetProvider())
  1226. client, err := getSftpClient(u, usePubKey)
  1227. if err != nil {
  1228. t.Errorf("unable to create sftp client: %v", err)
  1229. } else {
  1230. defer client.Close()
  1231. testFileName := "test_file.dat"
  1232. testFilePath := filepath.Join(homeBasePath, testFileName)
  1233. testFileSize := int64(65535)
  1234. err = createTestFile(testFilePath, testFileSize)
  1235. if err != nil {
  1236. t.Errorf("unable to create test file: %v", err)
  1237. }
  1238. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1239. if err != nil {
  1240. t.Errorf("file upload error: %v", err)
  1241. }
  1242. os.Remove(testFilePath)
  1243. }
  1244. u.Username = defaultUsername + "1"
  1245. client, err = getSftpClient(u, usePubKey)
  1246. if err == nil {
  1247. t.Error("external auth login with invalid user must fail")
  1248. }
  1249. usePubKey = false
  1250. u = getTestUser(usePubKey)
  1251. u.PublicKeys = []string{}
  1252. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1253. client, err = getSftpClient(u, usePubKey)
  1254. if err != nil {
  1255. t.Errorf("unable to create sftp client: %v", err)
  1256. } else {
  1257. defer client.Close()
  1258. _, err := client.Getwd()
  1259. if err != nil {
  1260. t.Errorf("unable to get working dir: %v", err)
  1261. }
  1262. }
  1263. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1264. if err != nil {
  1265. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1266. }
  1267. if len(users) != 1 {
  1268. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1269. }
  1270. user := users[0]
  1271. if len(user.PublicKeys) != 0 {
  1272. t.Errorf("number of public keys mismatch, expected: 0, actual: %v", len(user.PublicKeys))
  1273. }
  1274. if user.UsedQuotaSize == 0 {
  1275. t.Error("quota size must be > 0")
  1276. }
  1277. _, err = httpd.RemoveUser(user, http.StatusOK)
  1278. if err != nil {
  1279. t.Errorf("unable to remove: %v", err)
  1280. }
  1281. os.RemoveAll(user.GetHomeDir())
  1282. dataProvider = dataprovider.GetProvider()
  1283. dataprovider.Close(dataProvider)
  1284. config.LoadConfig(configDir, "")
  1285. providerConf = config.GetProviderConf()
  1286. err = dataprovider.Initialize(providerConf, configDir)
  1287. if err != nil {
  1288. t.Errorf("error initializing data provider")
  1289. }
  1290. httpd.SetDataProvider(dataprovider.GetProvider())
  1291. sftpd.SetDataProvider(dataprovider.GetProvider())
  1292. os.Remove(extAuthPath)
  1293. }
  1294. func TestLoginExternalAuthPwd(t *testing.T) {
  1295. if runtime.GOOS == "windows" {
  1296. t.Skip("this test is not available on Windows")
  1297. }
  1298. usePubKey := false
  1299. u := getTestUser(usePubKey)
  1300. dataProvider := dataprovider.GetProvider()
  1301. dataprovider.Close(dataProvider)
  1302. config.LoadConfig(configDir, "")
  1303. providerConf := config.GetProviderConf()
  1304. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1305. providerConf.ExternalAuthProgram = extAuthPath
  1306. providerConf.ExternalAuthScope = 1
  1307. err := dataprovider.Initialize(providerConf, configDir)
  1308. if err != nil {
  1309. t.Errorf("error initializing data provider")
  1310. }
  1311. httpd.SetDataProvider(dataprovider.GetProvider())
  1312. sftpd.SetDataProvider(dataprovider.GetProvider())
  1313. client, err := getSftpClient(u, usePubKey)
  1314. if err != nil {
  1315. t.Errorf("unable to create sftp client: %v", err)
  1316. } else {
  1317. defer client.Close()
  1318. _, err := client.Getwd()
  1319. if err != nil {
  1320. t.Errorf("unable to get working dir: %v", err)
  1321. }
  1322. }
  1323. u.Username = defaultUsername + "1"
  1324. client, err = getSftpClient(u, usePubKey)
  1325. if err == nil {
  1326. t.Error("external auth login with invalid user must fail")
  1327. }
  1328. usePubKey = true
  1329. u = getTestUser(usePubKey)
  1330. client, err = getSftpClient(u, usePubKey)
  1331. if err == nil {
  1332. t.Error("external auth login with valid user but invalid auth scope must fail")
  1333. }
  1334. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1335. if err != nil {
  1336. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1337. }
  1338. if len(users) != 1 {
  1339. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1340. }
  1341. user := users[0]
  1342. _, err = httpd.RemoveUser(user, http.StatusOK)
  1343. if err != nil {
  1344. t.Errorf("unable to remove: %v", err)
  1345. }
  1346. os.RemoveAll(user.GetHomeDir())
  1347. dataProvider = dataprovider.GetProvider()
  1348. dataprovider.Close(dataProvider)
  1349. config.LoadConfig(configDir, "")
  1350. providerConf = config.GetProviderConf()
  1351. err = dataprovider.Initialize(providerConf, configDir)
  1352. if err != nil {
  1353. t.Errorf("error initializing data provider")
  1354. }
  1355. httpd.SetDataProvider(dataprovider.GetProvider())
  1356. sftpd.SetDataProvider(dataprovider.GetProvider())
  1357. os.Remove(extAuthPath)
  1358. }
  1359. func TestLoginExternalAuthPubKey(t *testing.T) {
  1360. if runtime.GOOS == "windows" {
  1361. t.Skip("this test is not available on Windows")
  1362. }
  1363. usePubKey := true
  1364. u := getTestUser(usePubKey)
  1365. dataProvider := dataprovider.GetProvider()
  1366. dataprovider.Close(dataProvider)
  1367. config.LoadConfig(configDir, "")
  1368. providerConf := config.GetProviderConf()
  1369. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1370. providerConf.ExternalAuthProgram = extAuthPath
  1371. providerConf.ExternalAuthScope = 2
  1372. err := dataprovider.Initialize(providerConf, configDir)
  1373. if err != nil {
  1374. t.Errorf("error initializing data provider")
  1375. }
  1376. httpd.SetDataProvider(dataprovider.GetProvider())
  1377. sftpd.SetDataProvider(dataprovider.GetProvider())
  1378. client, err := getSftpClient(u, usePubKey)
  1379. if err != nil {
  1380. t.Errorf("unable to create sftp client: %v", err)
  1381. } else {
  1382. defer client.Close()
  1383. _, err := client.Getwd()
  1384. if err != nil {
  1385. t.Errorf("unable to get working dir: %v", err)
  1386. }
  1387. }
  1388. u.Username = defaultUsername + "1"
  1389. client, err = getSftpClient(u, usePubKey)
  1390. if err == nil {
  1391. t.Error("external auth login with invalid user must fail")
  1392. }
  1393. usePubKey = false
  1394. u = getTestUser(usePubKey)
  1395. client, err = getSftpClient(u, usePubKey)
  1396. if err == nil {
  1397. t.Error("external auth login with valid user but invalid auth scope must fail")
  1398. }
  1399. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1400. if err != nil {
  1401. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1402. }
  1403. if len(users) != 1 {
  1404. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1405. }
  1406. user := users[0]
  1407. _, err = httpd.RemoveUser(user, http.StatusOK)
  1408. if err != nil {
  1409. t.Errorf("unable to remove: %v", err)
  1410. }
  1411. os.RemoveAll(user.GetHomeDir())
  1412. dataProvider = dataprovider.GetProvider()
  1413. dataprovider.Close(dataProvider)
  1414. config.LoadConfig(configDir, "")
  1415. providerConf = config.GetProviderConf()
  1416. err = dataprovider.Initialize(providerConf, configDir)
  1417. if err != nil {
  1418. t.Errorf("error initializing data provider")
  1419. }
  1420. httpd.SetDataProvider(dataprovider.GetProvider())
  1421. sftpd.SetDataProvider(dataprovider.GetProvider())
  1422. os.Remove(extAuthPath)
  1423. }
  1424. func TestLoginExternalAuthInteractive(t *testing.T) {
  1425. if runtime.GOOS == "windows" {
  1426. t.Skip("this test is not available on Windows")
  1427. }
  1428. usePubKey := false
  1429. u := getTestUser(usePubKey)
  1430. dataProvider := dataprovider.GetProvider()
  1431. dataprovider.Close(dataProvider)
  1432. config.LoadConfig(configDir, "")
  1433. providerConf := config.GetProviderConf()
  1434. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1435. providerConf.ExternalAuthProgram = extAuthPath
  1436. providerConf.ExternalAuthScope = 4
  1437. err := dataprovider.Initialize(providerConf, configDir)
  1438. if err != nil {
  1439. t.Errorf("error initializing data provider")
  1440. }
  1441. httpd.SetDataProvider(dataprovider.GetProvider())
  1442. sftpd.SetDataProvider(dataprovider.GetProvider())
  1443. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  1444. client, err := getKeyboardInteractiveSftpClient(u, []string{"1", "2"})
  1445. if err != nil {
  1446. t.Errorf("unable to create sftp client: %v", err)
  1447. } else {
  1448. defer client.Close()
  1449. _, err := client.Getwd()
  1450. if err != nil {
  1451. t.Errorf("unable to get working dir: %v", err)
  1452. }
  1453. }
  1454. u.Username = defaultUsername + "1"
  1455. client, err = getKeyboardInteractiveSftpClient(u, []string{"1", "2"})
  1456. if err == nil {
  1457. t.Error("external auth login with invalid user must fail")
  1458. }
  1459. usePubKey = true
  1460. u = getTestUser(usePubKey)
  1461. client, err = getSftpClient(u, usePubKey)
  1462. if err == nil {
  1463. t.Error("external auth login with valid user but invalid auth scope must fail")
  1464. }
  1465. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1466. if err != nil {
  1467. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1468. }
  1469. if len(users) != 1 {
  1470. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1471. }
  1472. user := users[0]
  1473. _, err = httpd.RemoveUser(user, http.StatusOK)
  1474. if err != nil {
  1475. t.Errorf("unable to remove: %v", err)
  1476. }
  1477. os.RemoveAll(user.GetHomeDir())
  1478. dataProvider = dataprovider.GetProvider()
  1479. dataprovider.Close(dataProvider)
  1480. config.LoadConfig(configDir, "")
  1481. providerConf = config.GetProviderConf()
  1482. err = dataprovider.Initialize(providerConf, configDir)
  1483. if err != nil {
  1484. t.Errorf("error initializing data provider")
  1485. }
  1486. httpd.SetDataProvider(dataprovider.GetProvider())
  1487. sftpd.SetDataProvider(dataprovider.GetProvider())
  1488. os.Remove(extAuthPath)
  1489. }
  1490. func TestLoginExternalAuthErrors(t *testing.T) {
  1491. if runtime.GOOS == "windows" {
  1492. t.Skip("this test is not available on Windows")
  1493. }
  1494. usePubKey := true
  1495. u := getTestUser(usePubKey)
  1496. dataProvider := dataprovider.GetProvider()
  1497. dataprovider.Close(dataProvider)
  1498. config.LoadConfig(configDir, "")
  1499. providerConf := config.GetProviderConf()
  1500. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, true), 0755)
  1501. providerConf.ExternalAuthProgram = extAuthPath
  1502. providerConf.ExternalAuthScope = 0
  1503. err := dataprovider.Initialize(providerConf, configDir)
  1504. if err != nil {
  1505. t.Errorf("error initializing data provider")
  1506. }
  1507. httpd.SetDataProvider(dataprovider.GetProvider())
  1508. sftpd.SetDataProvider(dataprovider.GetProvider())
  1509. _, err = getSftpClient(u, usePubKey)
  1510. if err == nil {
  1511. t.Error("login must fail, external auth returns a non json response")
  1512. }
  1513. usePubKey = false
  1514. u = getTestUser(usePubKey)
  1515. _, err = getSftpClient(u, usePubKey)
  1516. if err == nil {
  1517. t.Error("login must fail, external auth returns a non json response")
  1518. }
  1519. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1520. if err != nil {
  1521. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1522. }
  1523. if len(users) != 0 {
  1524. t.Errorf("number of users mismatch, expected: 0, actual: %v", len(users))
  1525. }
  1526. dataProvider = dataprovider.GetProvider()
  1527. dataprovider.Close(dataProvider)
  1528. config.LoadConfig(configDir, "")
  1529. providerConf = config.GetProviderConf()
  1530. err = dataprovider.Initialize(providerConf, configDir)
  1531. if err != nil {
  1532. t.Errorf("error initializing data provider")
  1533. }
  1534. httpd.SetDataProvider(dataprovider.GetProvider())
  1535. sftpd.SetDataProvider(dataprovider.GetProvider())
  1536. os.Remove(extAuthPath)
  1537. }
  1538. func TestQuotaDisabledError(t *testing.T) {
  1539. dataProvider := dataprovider.GetProvider()
  1540. dataprovider.Close(dataProvider)
  1541. config.LoadConfig(configDir, "")
  1542. providerConf := config.GetProviderConf()
  1543. providerConf.TrackQuota = 0
  1544. err := dataprovider.Initialize(providerConf, configDir)
  1545. if err != nil {
  1546. t.Errorf("error initializing data provider")
  1547. }
  1548. httpd.SetDataProvider(dataprovider.GetProvider())
  1549. sftpd.SetDataProvider(dataprovider.GetProvider())
  1550. usePubKey := false
  1551. u := getTestUser(usePubKey)
  1552. u.QuotaFiles = 10
  1553. user, _, err := httpd.AddUser(u, http.StatusOK)
  1554. if err != nil {
  1555. t.Errorf("unable to add user: %v", err)
  1556. }
  1557. client, err := getSftpClient(user, usePubKey)
  1558. if err != nil {
  1559. t.Errorf("unable to create sftp client: %v", err)
  1560. } else {
  1561. defer client.Close()
  1562. testFileName := "test_file.dat"
  1563. testFilePath := filepath.Join(homeBasePath, testFileName)
  1564. testFileSize := int64(65535)
  1565. err = createTestFile(testFilePath, testFileSize)
  1566. if err != nil {
  1567. t.Errorf("unable to create test file: %v", err)
  1568. }
  1569. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1570. if err != nil {
  1571. t.Errorf("file upload error: %v", err)
  1572. }
  1573. os.Remove(testFilePath)
  1574. }
  1575. _, err = httpd.RemoveUser(user, http.StatusOK)
  1576. if err != nil {
  1577. t.Errorf("unable to remove: %v", err)
  1578. }
  1579. os.RemoveAll(user.GetHomeDir())
  1580. dataProvider = dataprovider.GetProvider()
  1581. dataprovider.Close(dataProvider)
  1582. config.LoadConfig(configDir, "")
  1583. providerConf = config.GetProviderConf()
  1584. err = dataprovider.Initialize(providerConf, configDir)
  1585. if err != nil {
  1586. t.Errorf("error initializing data provider")
  1587. }
  1588. httpd.SetDataProvider(dataprovider.GetProvider())
  1589. sftpd.SetDataProvider(dataprovider.GetProvider())
  1590. }
  1591. func TestMaxSessions(t *testing.T) {
  1592. usePubKey := false
  1593. u := getTestUser(usePubKey)
  1594. u.Username += "1"
  1595. u.MaxSessions = 1
  1596. user, _, err := httpd.AddUser(u, http.StatusOK)
  1597. if err != nil {
  1598. t.Errorf("unable to add user: %v", err)
  1599. }
  1600. client, err := getSftpClient(user, usePubKey)
  1601. if err != nil {
  1602. t.Errorf("unable to create sftp client: %v", err)
  1603. } else {
  1604. defer client.Close()
  1605. _, err := client.Getwd()
  1606. if err != nil {
  1607. t.Errorf("unable to get working dir: %v", err)
  1608. }
  1609. _, err = client.ReadDir(".")
  1610. if err != nil {
  1611. t.Errorf("unable to read remote dir: %v", err)
  1612. }
  1613. _, err = getSftpClient(user, usePubKey)
  1614. if err == nil {
  1615. t.Errorf("max sessions exceeded, new login should not succeed")
  1616. }
  1617. }
  1618. _, err = httpd.RemoveUser(user, http.StatusOK)
  1619. if err != nil {
  1620. t.Errorf("unable to remove user: %v", err)
  1621. }
  1622. os.RemoveAll(user.GetHomeDir())
  1623. }
  1624. func TestQuotaFileReplace(t *testing.T) {
  1625. usePubKey := false
  1626. u := getTestUser(usePubKey)
  1627. u.QuotaFiles = 1000
  1628. user, _, err := httpd.AddUser(u, http.StatusOK)
  1629. if err != nil {
  1630. t.Errorf("unable to add user: %v", err)
  1631. }
  1632. os.RemoveAll(user.GetHomeDir())
  1633. testFileSize := int64(65535)
  1634. testFileName := "test_file.dat"
  1635. testFilePath := filepath.Join(homeBasePath, testFileName)
  1636. client, err := getSftpClient(user, usePubKey)
  1637. if err != nil {
  1638. t.Errorf("unable to create sftp client: %v", err)
  1639. } else {
  1640. defer client.Close()
  1641. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  1642. expectedQuotaFiles := user.UsedQuotaFiles + 1
  1643. err = createTestFile(testFilePath, testFileSize)
  1644. if err != nil {
  1645. t.Errorf("unable to create test file: %v", err)
  1646. }
  1647. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1648. if err != nil {
  1649. t.Errorf("file upload error: %v", err)
  1650. }
  1651. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1652. if err != nil {
  1653. t.Errorf("error getting user: %v", err)
  1654. }
  1655. // now replace the same file, the quota must not change
  1656. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1657. if err != nil {
  1658. t.Errorf("file upload error: %v", err)
  1659. }
  1660. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1661. if err != nil {
  1662. t.Errorf("error getting user: %v", err)
  1663. }
  1664. if expectedQuotaFiles != user.UsedQuotaFiles {
  1665. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  1666. }
  1667. if expectedQuotaSize != user.UsedQuotaSize {
  1668. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  1669. }
  1670. }
  1671. // now set a quota size restriction and upload the same file, upload should fail for space limit exceeded
  1672. user.QuotaSize = testFileSize - 1
  1673. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1674. if err != nil {
  1675. t.Errorf("error updating user: %v", err)
  1676. }
  1677. client, err = getSftpClient(user, usePubKey)
  1678. if err != nil {
  1679. t.Errorf("unable to create sftp client: %v", err)
  1680. } else {
  1681. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1682. if err == nil {
  1683. t.Errorf("quota size exceeded, file upload must fail")
  1684. }
  1685. err = client.Remove(testFileName)
  1686. if err != nil {
  1687. t.Errorf("error removing uploaded file: %v", err)
  1688. }
  1689. }
  1690. _, err = httpd.RemoveUser(user, http.StatusOK)
  1691. if err != nil {
  1692. t.Errorf("unable to remove user: %v", err)
  1693. }
  1694. os.Remove(testFilePath)
  1695. os.RemoveAll(user.GetHomeDir())
  1696. }
  1697. func TestQuotaScan(t *testing.T) {
  1698. usePubKey := false
  1699. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1700. if err != nil {
  1701. t.Errorf("unable to add user: %v", err)
  1702. }
  1703. testFileSize := int64(65535)
  1704. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  1705. expectedQuotaFiles := user.UsedQuotaFiles + 1
  1706. client, err := getSftpClient(user, usePubKey)
  1707. if err != nil {
  1708. t.Errorf("unable to create sftp client: %v", err)
  1709. } else {
  1710. defer client.Close()
  1711. testFileName := "test_file.dat"
  1712. testFilePath := filepath.Join(homeBasePath, testFileName)
  1713. err = createTestFile(testFilePath, testFileSize)
  1714. if err != nil {
  1715. t.Errorf("unable to create test file: %v", err)
  1716. }
  1717. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1718. if err != nil {
  1719. t.Errorf("file upload error: %v", err)
  1720. }
  1721. os.Remove(testFilePath)
  1722. }
  1723. _, err = httpd.RemoveUser(user, http.StatusOK)
  1724. if err != nil {
  1725. t.Errorf("unable to remove user: %v", err)
  1726. }
  1727. // create user with the same home dir, so there is at least an untracked file
  1728. user, _, err = httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1729. if err != nil {
  1730. t.Errorf("unable to add user: %v", err)
  1731. }
  1732. _, err = httpd.StartQuotaScan(user, http.StatusCreated)
  1733. if err != nil {
  1734. t.Errorf("error starting quota scan: %v", err)
  1735. }
  1736. err = waitQuotaScans()
  1737. if err != nil {
  1738. t.Errorf("error waiting for active quota scans: %v", err)
  1739. }
  1740. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1741. if err != nil {
  1742. t.Errorf("error getting user: %v", err)
  1743. }
  1744. if expectedQuotaFiles != user.UsedQuotaFiles {
  1745. t.Errorf("quota files does not match after scan, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  1746. }
  1747. if expectedQuotaSize != user.UsedQuotaSize {
  1748. t.Errorf("quota size does not match after scan, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  1749. }
  1750. _, err = httpd.RemoveUser(user, http.StatusOK)
  1751. if err != nil {
  1752. t.Errorf("unable to remove user: %v", err)
  1753. }
  1754. os.RemoveAll(user.GetHomeDir())
  1755. }
  1756. func TestMultipleQuotaScans(t *testing.T) {
  1757. if !sftpd.AddQuotaScan(defaultUsername) {
  1758. t.Errorf("add quota failed")
  1759. }
  1760. if sftpd.AddQuotaScan(defaultUsername) {
  1761. t.Errorf("add quota must fail if another scan is already active")
  1762. }
  1763. sftpd.RemoveQuotaScan(defaultUsername)
  1764. activeScans := sftpd.GetQuotaScans()
  1765. if len(activeScans) > 0 {
  1766. t.Errorf("no quota scan must be active: %v", len(activeScans))
  1767. }
  1768. }
  1769. func TestQuotaSize(t *testing.T) {
  1770. usePubKey := false
  1771. testFileSize := int64(65535)
  1772. u := getTestUser(usePubKey)
  1773. u.QuotaFiles = 1
  1774. u.QuotaSize = testFileSize - 1
  1775. user, _, err := httpd.AddUser(u, http.StatusOK)
  1776. if err != nil {
  1777. t.Errorf("unable to add user: %v", err)
  1778. }
  1779. client, err := getSftpClient(user, usePubKey)
  1780. if err != nil {
  1781. t.Errorf("unable to create sftp client: %v", err)
  1782. } else {
  1783. defer client.Close()
  1784. testFileName := "test_file.dat"
  1785. testFilePath := filepath.Join(homeBasePath, testFileName)
  1786. err = createTestFile(testFilePath, testFileSize)
  1787. if err != nil {
  1788. t.Errorf("unable to create test file: %v", err)
  1789. }
  1790. err = sftpUploadFile(testFilePath, testFileName+".quota", testFileSize, client)
  1791. if err != nil {
  1792. t.Errorf("file upload error: %v", err)
  1793. }
  1794. err = sftpUploadFile(testFilePath, testFileName+".quota.1", testFileSize, client)
  1795. if err == nil {
  1796. t.Errorf("user is over quota file upload must fail")
  1797. }
  1798. err = client.Remove(testFileName + ".quota")
  1799. if err != nil {
  1800. t.Errorf("error removing uploaded file: %v", err)
  1801. }
  1802. os.Remove(testFilePath)
  1803. }
  1804. _, err = httpd.RemoveUser(user, http.StatusOK)
  1805. if err != nil {
  1806. t.Errorf("unable to remove user: %v", err)
  1807. }
  1808. os.RemoveAll(user.GetHomeDir())
  1809. }
  1810. func TestBandwidthAndConnections(t *testing.T) {
  1811. usePubKey := false
  1812. testFileSize := int64(131072)
  1813. u := getTestUser(usePubKey)
  1814. u.UploadBandwidth = 30
  1815. u.DownloadBandwidth = 25
  1816. wantedUploadElapsed := 1000 * (testFileSize / 1000) / u.UploadBandwidth
  1817. wantedDownloadElapsed := 1000 * (testFileSize / 1000) / u.DownloadBandwidth
  1818. // 100 ms tolerance
  1819. wantedUploadElapsed -= 100
  1820. wantedDownloadElapsed -= 100
  1821. user, _, err := httpd.AddUser(u, http.StatusOK)
  1822. if err != nil {
  1823. t.Errorf("unable to add user: %v", err)
  1824. }
  1825. client, err := getSftpClient(user, usePubKey)
  1826. if err != nil {
  1827. t.Errorf("unable to create sftp client: %v", err)
  1828. } else {
  1829. defer client.Close()
  1830. testFileName := "test_file.dat"
  1831. testFilePath := filepath.Join(homeBasePath, testFileName)
  1832. err = createTestFile(testFilePath, testFileSize)
  1833. if err != nil {
  1834. t.Errorf("unable to create test file: %v", err)
  1835. }
  1836. startTime := time.Now()
  1837. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1838. if err != nil {
  1839. t.Errorf("file upload error: %v", err)
  1840. }
  1841. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  1842. if elapsed < (wantedUploadElapsed) {
  1843. t.Errorf("upload bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedUploadElapsed)
  1844. }
  1845. startTime = time.Now()
  1846. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  1847. c := sftpDownloadNonBlocking(testFileName, localDownloadPath, testFileSize, client)
  1848. waitForActiveTransfer()
  1849. // wait some additional arbitrary time to wait for transfer activity to happen
  1850. // it is need to reach all the code in CheckIdleConnections
  1851. time.Sleep(100 * time.Millisecond)
  1852. sftpd.CheckIdleConnections()
  1853. err = <-c
  1854. if err != nil {
  1855. t.Errorf("file download error: %v", err)
  1856. }
  1857. elapsed = time.Since(startTime).Nanoseconds() / 1000000
  1858. if elapsed < (wantedDownloadElapsed) {
  1859. t.Errorf("download bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedDownloadElapsed)
  1860. }
  1861. // test disconnection
  1862. c = sftpUploadNonBlocking(testFilePath, testFileName+"_partial", testFileSize, client)
  1863. waitForActiveTransfer()
  1864. time.Sleep(100 * time.Millisecond)
  1865. sftpd.CheckIdleConnections()
  1866. stats := sftpd.GetConnectionsStats()
  1867. for _, stat := range stats {
  1868. sftpd.CloseActiveConnection(stat.ConnectionID)
  1869. }
  1870. err = <-c
  1871. if err == nil {
  1872. t.Errorf("connection closed upload must fail")
  1873. }
  1874. os.Remove(testFilePath)
  1875. os.Remove(localDownloadPath)
  1876. }
  1877. _, err = httpd.RemoveUser(user, http.StatusOK)
  1878. if err != nil {
  1879. t.Errorf("unable to remove user: %v", err)
  1880. }
  1881. os.RemoveAll(user.GetHomeDir())
  1882. }
  1883. func TestMissingFile(t *testing.T) {
  1884. usePubKey := false
  1885. u := getTestUser(usePubKey)
  1886. user, _, err := httpd.AddUser(u, http.StatusOK)
  1887. if err != nil {
  1888. t.Errorf("unable to add user: %v", err)
  1889. }
  1890. client, err := getSftpClient(user, usePubKey)
  1891. if err != nil {
  1892. t.Errorf("unable to create sftp client: %v", err)
  1893. } else {
  1894. defer client.Close()
  1895. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  1896. err = sftpDownloadFile("missing_file", localDownloadPath, 0, client)
  1897. if err == nil {
  1898. t.Errorf("download missing file must fail")
  1899. }
  1900. os.Remove(localDownloadPath)
  1901. }
  1902. _, err = httpd.RemoveUser(user, http.StatusOK)
  1903. if err != nil {
  1904. t.Errorf("unable to remove user: %v", err)
  1905. }
  1906. os.RemoveAll(user.GetHomeDir())
  1907. }
  1908. func TestOpenError(t *testing.T) {
  1909. if runtime.GOOS == "windows" {
  1910. t.Skip("this test is not available on Windows")
  1911. }
  1912. usePubKey := false
  1913. u := getTestUser(usePubKey)
  1914. user, _, err := httpd.AddUser(u, http.StatusOK)
  1915. if err != nil {
  1916. t.Errorf("unable to add user: %v", err)
  1917. }
  1918. os.RemoveAll(user.GetHomeDir())
  1919. client, err := getSftpClient(user, usePubKey)
  1920. if err != nil {
  1921. t.Errorf("unable to create sftp client: %v", err)
  1922. } else {
  1923. defer client.Close()
  1924. os.Chmod(user.GetHomeDir(), 0001)
  1925. _, err = client.ReadDir(".")
  1926. if err == nil {
  1927. t.Errorf("read dir must fail if we have no filesystem read permissions")
  1928. }
  1929. os.Chmod(user.GetHomeDir(), 0755)
  1930. testFileSize := int64(65535)
  1931. testFileName := "test_file.dat"
  1932. testFilePath := filepath.Join(user.GetHomeDir(), testFileName)
  1933. err = createTestFile(testFilePath, testFileSize)
  1934. if err != nil {
  1935. t.Errorf("unable to create test file: %v", err)
  1936. }
  1937. _, err = client.Stat(testFileName)
  1938. if err != nil {
  1939. t.Errorf("file stat error: %v", err)
  1940. }
  1941. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  1942. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  1943. if err != nil {
  1944. t.Errorf("file download error: %v", err)
  1945. }
  1946. os.Chmod(testFilePath, 0001)
  1947. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  1948. if err == nil {
  1949. t.Errorf("file download must fail if we have no filesystem read permissions")
  1950. }
  1951. err = sftpUploadFile(localDownloadPath, testFileName, testFileSize, client)
  1952. if err == nil {
  1953. t.Errorf("upload must fail if we have no filesystem write permissions")
  1954. }
  1955. err = client.Mkdir("test")
  1956. if err != nil {
  1957. t.Errorf("error making dir: %v", err)
  1958. }
  1959. os.Chmod(user.GetHomeDir(), 0000)
  1960. _, err = client.Lstat(testFileName)
  1961. if err == nil {
  1962. t.Errorf("file stat must fail if we have no filesystem read permissions")
  1963. }
  1964. os.Chmod(user.GetHomeDir(), 0755)
  1965. os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0000)
  1966. err = client.Rename(testFileName, path.Join("test", testFileName))
  1967. if err == nil || !strings.Contains(err.Error(), sftp.ErrSSHFxPermissionDenied.Error()) {
  1968. t.Errorf("unexpected error: %v expected: %v", err, sftp.ErrSSHFxPermissionDenied)
  1969. }
  1970. os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0755)
  1971. os.Remove(testFilePath)
  1972. os.Remove(localDownloadPath)
  1973. }
  1974. _, err = httpd.RemoveUser(user, http.StatusOK)
  1975. if err != nil {
  1976. t.Errorf("unable to remove user: %v", err)
  1977. }
  1978. os.RemoveAll(user.GetHomeDir())
  1979. }
  1980. func TestOverwriteDirWithFile(t *testing.T) {
  1981. usePubKey := false
  1982. u := getTestUser(usePubKey)
  1983. user, _, err := httpd.AddUser(u, http.StatusOK)
  1984. if err != nil {
  1985. t.Errorf("unable to add user: %v", err)
  1986. }
  1987. client, err := getSftpClient(user, usePubKey)
  1988. if err != nil {
  1989. t.Errorf("unable to create sftp client: %v", err)
  1990. } else {
  1991. defer client.Close()
  1992. testFileSize := int64(65535)
  1993. testFileName := "test_file.dat"
  1994. testDirName := "test_dir"
  1995. testFilePath := filepath.Join(homeBasePath, testFileName)
  1996. err = createTestFile(testFilePath, testFileSize)
  1997. if err != nil {
  1998. t.Errorf("unable to create test file: %v", err)
  1999. }
  2000. err = client.Mkdir(testDirName)
  2001. if err != nil {
  2002. t.Errorf("mkdir error: %v", err)
  2003. }
  2004. err = sftpUploadFile(testFilePath, testDirName, testFileSize, client)
  2005. if err == nil {
  2006. t.Errorf("copying a file over an existing dir must fail")
  2007. }
  2008. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2009. if err != nil {
  2010. t.Errorf("file upload error: %v", err)
  2011. }
  2012. err = client.Rename(testFileName, testDirName)
  2013. if err == nil {
  2014. t.Errorf("rename a file over an existing dir must fail")
  2015. }
  2016. err = client.RemoveDirectory(testDirName)
  2017. if err != nil {
  2018. t.Errorf("dir remove error: %v", err)
  2019. }
  2020. err = client.Remove(testFileName)
  2021. if err != nil {
  2022. t.Errorf("error removing uploaded file: %v", err)
  2023. }
  2024. os.Remove(testFilePath)
  2025. }
  2026. _, err = httpd.RemoveUser(user, http.StatusOK)
  2027. if err != nil {
  2028. t.Errorf("unable to remove user: %v", err)
  2029. }
  2030. os.RemoveAll(user.GetHomeDir())
  2031. }
  2032. func TestPasswordsHashPbkdf2Sha1(t *testing.T) {
  2033. pbkdf2Pwd := "$pbkdf2-sha1$150000$DveVjgYUD05R$X6ydQZdyMeOvpgND2nqGR/0GGic="
  2034. pbkdf2ClearPwd := "password"
  2035. usePubKey := false
  2036. u := getTestUser(usePubKey)
  2037. u.Password = pbkdf2Pwd
  2038. user, _, err := httpd.AddUser(u, http.StatusOK)
  2039. if err != nil {
  2040. t.Errorf("unable to add user: %v", err)
  2041. }
  2042. user.Password = pbkdf2ClearPwd
  2043. client, err := getSftpClient(user, usePubKey)
  2044. if err != nil {
  2045. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2046. } else {
  2047. defer client.Close()
  2048. _, err = client.Getwd()
  2049. if err != nil {
  2050. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2051. }
  2052. }
  2053. user.Password = pbkdf2Pwd
  2054. _, err = getSftpClient(user, usePubKey)
  2055. if err == nil {
  2056. t.Errorf("login with wrong password must fail")
  2057. }
  2058. _, err = httpd.RemoveUser(user, http.StatusOK)
  2059. if err != nil {
  2060. t.Errorf("unable to remove user: %v", err)
  2061. }
  2062. os.RemoveAll(user.GetHomeDir())
  2063. }
  2064. func TestPasswordsHashPbkdf2Sha256(t *testing.T) {
  2065. pbkdf2Pwd := "$pbkdf2-sha256$150000$E86a9YMX3zC7$R5J62hsSq+pYw00hLLPKBbcGXmq7fj5+/M0IFoYtZbo="
  2066. pbkdf2ClearPwd := "password"
  2067. usePubKey := false
  2068. u := getTestUser(usePubKey)
  2069. u.Password = pbkdf2Pwd
  2070. user, _, err := httpd.AddUser(u, http.StatusOK)
  2071. if err != nil {
  2072. t.Errorf("unable to add user: %v", err)
  2073. }
  2074. user.Password = pbkdf2ClearPwd
  2075. client, err := getSftpClient(user, usePubKey)
  2076. if err != nil {
  2077. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2078. } else {
  2079. defer client.Close()
  2080. _, err = client.Getwd()
  2081. if err != nil {
  2082. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2083. }
  2084. }
  2085. user.Password = pbkdf2Pwd
  2086. _, err = getSftpClient(user, usePubKey)
  2087. if err == nil {
  2088. t.Errorf("login with wrong password must fail")
  2089. }
  2090. _, err = httpd.RemoveUser(user, http.StatusOK)
  2091. if err != nil {
  2092. t.Errorf("unable to remove user: %v", err)
  2093. }
  2094. os.RemoveAll(user.GetHomeDir())
  2095. }
  2096. func TestPasswordsHashPbkdf2Sha512(t *testing.T) {
  2097. pbkdf2Pwd := "$pbkdf2-sha512$150000$dsu7T5R3IaVQ$1hFXPO1ntRBcoWkSLKw+s4sAP09Xtu4Ya7CyxFq64jM9zdUg8eRJVr3NcR2vQgb0W9HHvZaILHsL4Q/Vr6arCg=="
  2098. pbkdf2ClearPwd := "password"
  2099. usePubKey := false
  2100. u := getTestUser(usePubKey)
  2101. u.Password = pbkdf2Pwd
  2102. user, _, err := httpd.AddUser(u, http.StatusOK)
  2103. if err != nil {
  2104. t.Errorf("unable to add user: %v", err)
  2105. }
  2106. user.Password = pbkdf2ClearPwd
  2107. client, err := getSftpClient(user, usePubKey)
  2108. if err != nil {
  2109. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2110. } else {
  2111. defer client.Close()
  2112. _, err = client.Getwd()
  2113. if err != nil {
  2114. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2115. }
  2116. }
  2117. user.Password = pbkdf2Pwd
  2118. _, err = getSftpClient(user, usePubKey)
  2119. if err == nil {
  2120. t.Errorf("login with wrong password must fail")
  2121. }
  2122. _, err = httpd.RemoveUser(user, http.StatusOK)
  2123. if err != nil {
  2124. t.Errorf("unable to remove user: %v", err)
  2125. }
  2126. os.RemoveAll(user.GetHomeDir())
  2127. }
  2128. func TestPasswordsHashBcrypt(t *testing.T) {
  2129. bcryptPwd := "$2a$14$ajq8Q7fbtFRQvXpdCq7Jcuy.Rx1h/L4J60Otx.gyNLbAYctGMJ9tK"
  2130. bcryptClearPwd := "secret"
  2131. usePubKey := false
  2132. u := getTestUser(usePubKey)
  2133. u.Password = bcryptPwd
  2134. user, _, err := httpd.AddUser(u, http.StatusOK)
  2135. if err != nil {
  2136. t.Errorf("unable to add user: %v", err)
  2137. }
  2138. user.Password = bcryptClearPwd
  2139. client, err := getSftpClient(user, usePubKey)
  2140. if err != nil {
  2141. t.Errorf("unable to login with bcrypt password: %v", err)
  2142. } else {
  2143. defer client.Close()
  2144. _, err = client.Getwd()
  2145. if err != nil {
  2146. t.Errorf("unable to get working dir with bcrypt password: %v", err)
  2147. }
  2148. }
  2149. user.Password = bcryptPwd
  2150. _, err = getSftpClient(user, usePubKey)
  2151. if err == nil {
  2152. t.Errorf("login with wrong password must fail")
  2153. }
  2154. _, err = httpd.RemoveUser(user, http.StatusOK)
  2155. if err != nil {
  2156. t.Errorf("unable to remove user: %v", err)
  2157. }
  2158. os.RemoveAll(user.GetHomeDir())
  2159. }
  2160. func TestPasswordsHashSHA512Crypt(t *testing.T) {
  2161. sha512CryptPwd := "$6$459ead56b72e44bc$uog86fUxscjt28BZxqFBE2pp2QD8P/1e98MNF75Z9xJfQvOckZnQ/1YJqiq1XeytPuDieHZvDAMoP7352ELkO1"
  2162. clearPwd := "secret"
  2163. usePubKey := false
  2164. u := getTestUser(usePubKey)
  2165. u.Password = sha512CryptPwd
  2166. user, _, err := httpd.AddUser(u, http.StatusOK)
  2167. if err != nil {
  2168. t.Errorf("unable to add user: %v", err)
  2169. }
  2170. user.Password = clearPwd
  2171. client, err := getSftpClient(user, usePubKey)
  2172. if err != nil {
  2173. t.Errorf("unable to login with sha512 crypt password: %v", err)
  2174. } else {
  2175. defer client.Close()
  2176. _, err = client.Getwd()
  2177. if err != nil {
  2178. t.Errorf("unable to get working dir with sha512 crypt password: %v", err)
  2179. }
  2180. }
  2181. user.Password = sha512CryptPwd
  2182. _, err = getSftpClient(user, usePubKey)
  2183. if err == nil {
  2184. t.Errorf("login with wrong password must fail")
  2185. }
  2186. _, err = httpd.RemoveUser(user, http.StatusOK)
  2187. if err != nil {
  2188. t.Errorf("unable to remove user: %v", err)
  2189. }
  2190. os.RemoveAll(user.GetHomeDir())
  2191. }
  2192. func TestPasswordsHashMD5Crypt(t *testing.T) {
  2193. md5CryptPwd := "$1$b5caebda$VODr/nyhGWgZaY8sJ4x05."
  2194. clearPwd := "password"
  2195. usePubKey := false
  2196. u := getTestUser(usePubKey)
  2197. u.Password = md5CryptPwd
  2198. user, _, err := httpd.AddUser(u, http.StatusOK)
  2199. if err != nil {
  2200. t.Errorf("unable to add user: %v", err)
  2201. }
  2202. user.Password = clearPwd
  2203. client, err := getSftpClient(user, usePubKey)
  2204. if err != nil {
  2205. t.Errorf("unable to login with md5 crypt password: %v", err)
  2206. } else {
  2207. defer client.Close()
  2208. _, err = client.Getwd()
  2209. if err != nil {
  2210. t.Errorf("unable to get working dir with md5 crypt password: %v", err)
  2211. }
  2212. }
  2213. user.Password = md5CryptPwd
  2214. _, err = getSftpClient(user, usePubKey)
  2215. if err == nil {
  2216. t.Errorf("login with wrong password must fail")
  2217. }
  2218. _, err = httpd.RemoveUser(user, http.StatusOK)
  2219. if err != nil {
  2220. t.Errorf("unable to remove user: %v", err)
  2221. }
  2222. os.RemoveAll(user.GetHomeDir())
  2223. }
  2224. func TestPasswordsHashMD5CryptApr1(t *testing.T) {
  2225. md5CryptPwd := "$apr1$OBWLeSme$WoJbB736e7kKxMBIAqilb1"
  2226. clearPwd := "password"
  2227. usePubKey := false
  2228. u := getTestUser(usePubKey)
  2229. u.Password = md5CryptPwd
  2230. user, _, err := httpd.AddUser(u, http.StatusOK)
  2231. if err != nil {
  2232. t.Errorf("unable to add user: %v", err)
  2233. }
  2234. user.Password = clearPwd
  2235. client, err := getSftpClient(user, usePubKey)
  2236. if err != nil {
  2237. t.Errorf("unable to login with md5 crypt password: %v", err)
  2238. } else {
  2239. defer client.Close()
  2240. _, err = client.Getwd()
  2241. if err != nil {
  2242. t.Errorf("unable to get working dir with md5 crypt password: %v", err)
  2243. }
  2244. }
  2245. user.Password = md5CryptPwd
  2246. _, err = getSftpClient(user, usePubKey)
  2247. if err == nil {
  2248. t.Errorf("login with wrong password must fail")
  2249. }
  2250. _, err = httpd.RemoveUser(user, http.StatusOK)
  2251. if err != nil {
  2252. t.Errorf("unable to remove user: %v", err)
  2253. }
  2254. os.RemoveAll(user.GetHomeDir())
  2255. }
  2256. func TestPermList(t *testing.T) {
  2257. usePubKey := true
  2258. u := getTestUser(usePubKey)
  2259. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  2260. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2261. dataprovider.PermChown, dataprovider.PermChtimes}
  2262. user, _, err := httpd.AddUser(u, http.StatusOK)
  2263. if err != nil {
  2264. t.Errorf("unable to add user: %v", err)
  2265. }
  2266. client, err := getSftpClient(user, usePubKey)
  2267. if err != nil {
  2268. t.Errorf("unable to create sftp client: %v", err)
  2269. } else {
  2270. defer client.Close()
  2271. _, err = client.ReadDir(".")
  2272. if err == nil {
  2273. t.Errorf("read remote dir without permission should not succeed")
  2274. }
  2275. _, err = client.Stat("test_file")
  2276. if err == nil {
  2277. t.Errorf("stat remote file without permission should not succeed")
  2278. }
  2279. }
  2280. _, err = httpd.RemoveUser(user, http.StatusOK)
  2281. if err != nil {
  2282. t.Errorf("unable to remove user: %v", err)
  2283. }
  2284. os.RemoveAll(user.GetHomeDir())
  2285. }
  2286. func TestPermDownload(t *testing.T) {
  2287. usePubKey := true
  2288. u := getTestUser(usePubKey)
  2289. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  2290. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2291. dataprovider.PermChown, dataprovider.PermChtimes}
  2292. user, _, err := httpd.AddUser(u, http.StatusOK)
  2293. if err != nil {
  2294. t.Errorf("unable to add user: %v", err)
  2295. }
  2296. client, err := getSftpClient(user, usePubKey)
  2297. if err != nil {
  2298. t.Errorf("unable to create sftp client: %v", err)
  2299. } else {
  2300. defer client.Close()
  2301. testFileName := "test_file.dat"
  2302. testFilePath := filepath.Join(homeBasePath, testFileName)
  2303. testFileSize := int64(65535)
  2304. err = createTestFile(testFilePath, testFileSize)
  2305. if err != nil {
  2306. t.Errorf("unable to create test file: %v", err)
  2307. }
  2308. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2309. if err != nil {
  2310. t.Errorf("file upload error: %v", err)
  2311. }
  2312. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2313. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2314. if err == nil {
  2315. t.Errorf("file download without permission should not succeed")
  2316. }
  2317. err = client.Remove(testFileName)
  2318. if err != nil {
  2319. t.Errorf("error removing uploaded file: %v", err)
  2320. }
  2321. os.Remove(testFilePath)
  2322. os.Remove(localDownloadPath)
  2323. }
  2324. _, err = httpd.RemoveUser(user, http.StatusOK)
  2325. if err != nil {
  2326. t.Errorf("unable to remove user: %v", err)
  2327. }
  2328. os.RemoveAll(user.GetHomeDir())
  2329. }
  2330. func TestPermUpload(t *testing.T) {
  2331. usePubKey := false
  2332. u := getTestUser(usePubKey)
  2333. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermDelete, dataprovider.PermRename,
  2334. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2335. dataprovider.PermChown, dataprovider.PermChtimes}
  2336. user, _, err := httpd.AddUser(u, http.StatusOK)
  2337. if err != nil {
  2338. t.Errorf("unable to add user: %v", err)
  2339. }
  2340. client, err := getSftpClient(user, usePubKey)
  2341. if err != nil {
  2342. t.Errorf("unable to create sftp client: %v", err)
  2343. } else {
  2344. defer client.Close()
  2345. testFileName := "test_file.dat"
  2346. testFilePath := filepath.Join(homeBasePath, testFileName)
  2347. testFileSize := int64(65535)
  2348. err = createTestFile(testFilePath, testFileSize)
  2349. if err != nil {
  2350. t.Errorf("unable to create test file: %v", err)
  2351. }
  2352. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2353. if err == nil {
  2354. t.Errorf("file upload without permission should not succeed")
  2355. }
  2356. os.Remove(testFilePath)
  2357. }
  2358. _, err = httpd.RemoveUser(user, http.StatusOK)
  2359. if err != nil {
  2360. t.Errorf("unable to remove user: %v", err)
  2361. }
  2362. os.RemoveAll(user.GetHomeDir())
  2363. }
  2364. func TestPermOverwrite(t *testing.T) {
  2365. usePubKey := false
  2366. u := getTestUser(usePubKey)
  2367. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2368. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermChmod,
  2369. dataprovider.PermChown, dataprovider.PermChtimes}
  2370. user, _, err := httpd.AddUser(u, http.StatusOK)
  2371. if err != nil {
  2372. t.Errorf("unable to add user: %v", err)
  2373. }
  2374. client, err := getSftpClient(user, usePubKey)
  2375. if err != nil {
  2376. t.Errorf("unable to create sftp client: %v", err)
  2377. } else {
  2378. defer client.Close()
  2379. testFileName := "test_file.dat"
  2380. testFilePath := filepath.Join(homeBasePath, testFileName)
  2381. testFileSize := int64(65535)
  2382. err = createTestFile(testFilePath, testFileSize)
  2383. if err != nil {
  2384. t.Errorf("unable to create test file: %v", err)
  2385. }
  2386. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2387. if err != nil {
  2388. t.Errorf("error uploading file: %v", err)
  2389. }
  2390. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2391. if err == nil {
  2392. t.Errorf("file overwrite without permission should not succeed")
  2393. }
  2394. os.Remove(testFilePath)
  2395. }
  2396. _, err = httpd.RemoveUser(user, http.StatusOK)
  2397. if err != nil {
  2398. t.Errorf("unable to remove user: %v", err)
  2399. }
  2400. os.RemoveAll(user.GetHomeDir())
  2401. }
  2402. func TestPermDelete(t *testing.T) {
  2403. usePubKey := false
  2404. u := getTestUser(usePubKey)
  2405. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermRename,
  2406. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2407. dataprovider.PermChown, dataprovider.PermChtimes}
  2408. user, _, err := httpd.AddUser(u, http.StatusOK)
  2409. if err != nil {
  2410. t.Errorf("unable to add user: %v", err)
  2411. }
  2412. client, err := getSftpClient(user, usePubKey)
  2413. if err != nil {
  2414. t.Errorf("unable to create sftp client: %v", err)
  2415. } else {
  2416. defer client.Close()
  2417. testFileName := "test_file.dat"
  2418. testFilePath := filepath.Join(homeBasePath, testFileName)
  2419. testFileSize := int64(65535)
  2420. err = createTestFile(testFilePath, testFileSize)
  2421. if err != nil {
  2422. t.Errorf("unable to create test file: %v", err)
  2423. }
  2424. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2425. if err != nil {
  2426. t.Errorf("file upload error: %v", err)
  2427. }
  2428. err = client.Remove(testFileName)
  2429. if err == nil {
  2430. t.Errorf("delete without permission should not succeed")
  2431. }
  2432. os.Remove(testFilePath)
  2433. }
  2434. _, err = httpd.RemoveUser(user, http.StatusOK)
  2435. if err != nil {
  2436. t.Errorf("unable to remove user: %v", err)
  2437. }
  2438. os.RemoveAll(user.GetHomeDir())
  2439. }
  2440. func TestPermRename(t *testing.T) {
  2441. usePubKey := false
  2442. u := getTestUser(usePubKey)
  2443. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2444. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2445. dataprovider.PermChown, dataprovider.PermChtimes}
  2446. user, _, err := httpd.AddUser(u, http.StatusOK)
  2447. if err != nil {
  2448. t.Errorf("unable to add user: %v", err)
  2449. }
  2450. client, err := getSftpClient(user, usePubKey)
  2451. if err != nil {
  2452. t.Errorf("unable to create sftp client: %v", err)
  2453. } else {
  2454. defer client.Close()
  2455. testFileName := "test_file.dat"
  2456. testFilePath := filepath.Join(homeBasePath, testFileName)
  2457. testFileSize := int64(65535)
  2458. err = createTestFile(testFilePath, testFileSize)
  2459. if err != nil {
  2460. t.Errorf("unable to create test file: %v", err)
  2461. }
  2462. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2463. if err != nil {
  2464. t.Errorf("file upload error: %v", err)
  2465. }
  2466. err = client.Rename(testFileName, testFileName+".rename")
  2467. if err == nil {
  2468. t.Errorf("rename without permission should not succeed")
  2469. }
  2470. err = client.Remove(testFileName)
  2471. if err != nil {
  2472. t.Errorf("error removing uploaded file: %v", err)
  2473. }
  2474. os.Remove(testFilePath)
  2475. }
  2476. _, err = httpd.RemoveUser(user, http.StatusOK)
  2477. if err != nil {
  2478. t.Errorf("unable to remove user: %v", err)
  2479. }
  2480. os.RemoveAll(user.GetHomeDir())
  2481. }
  2482. func TestPermCreateDirs(t *testing.T) {
  2483. usePubKey := false
  2484. u := getTestUser(usePubKey)
  2485. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2486. dataprovider.PermRename, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2487. dataprovider.PermChown, dataprovider.PermChtimes}
  2488. user, _, err := httpd.AddUser(u, http.StatusOK)
  2489. if err != nil {
  2490. t.Errorf("unable to add user: %v", err)
  2491. }
  2492. client, err := getSftpClient(user, usePubKey)
  2493. if err != nil {
  2494. t.Errorf("unable to create sftp client: %v", err)
  2495. } else {
  2496. defer client.Close()
  2497. err = client.Mkdir("testdir")
  2498. if err == nil {
  2499. t.Errorf("mkdir without permission should not succeed")
  2500. }
  2501. }
  2502. _, err = httpd.RemoveUser(user, http.StatusOK)
  2503. if err != nil {
  2504. t.Errorf("unable to remove user: %v", err)
  2505. }
  2506. os.RemoveAll(user.GetHomeDir())
  2507. }
  2508. func TestPermSymlink(t *testing.T) {
  2509. usePubKey := false
  2510. u := getTestUser(usePubKey)
  2511. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2512. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown,
  2513. dataprovider.PermChtimes}
  2514. user, _, err := httpd.AddUser(u, http.StatusOK)
  2515. if err != nil {
  2516. t.Errorf("unable to add user: %v", err)
  2517. }
  2518. client, err := getSftpClient(user, usePubKey)
  2519. if err != nil {
  2520. t.Errorf("unable to create sftp client: %v", err)
  2521. } else {
  2522. defer client.Close()
  2523. testFileName := "test_file.dat"
  2524. testFilePath := filepath.Join(homeBasePath, testFileName)
  2525. testFileSize := int64(65535)
  2526. err = createTestFile(testFilePath, testFileSize)
  2527. if err != nil {
  2528. t.Errorf("unable to create test file: %v", err)
  2529. }
  2530. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2531. if err != nil {
  2532. t.Errorf("file upload error: %v", err)
  2533. }
  2534. err = client.Symlink(testFilePath, testFilePath+".symlink")
  2535. if err == nil {
  2536. t.Errorf("symlink without permission should not succeed")
  2537. }
  2538. err = client.Remove(testFileName)
  2539. if err != nil {
  2540. t.Errorf("error removing uploaded file: %v", err)
  2541. }
  2542. os.Remove(testFilePath)
  2543. }
  2544. _, err = httpd.RemoveUser(user, http.StatusOK)
  2545. if err != nil {
  2546. t.Errorf("unable to remove user: %v", err)
  2547. }
  2548. os.RemoveAll(user.GetHomeDir())
  2549. }
  2550. func TestPermChmod(t *testing.T) {
  2551. usePubKey := false
  2552. u := getTestUser(usePubKey)
  2553. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2554. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2555. dataprovider.PermChown, dataprovider.PermChtimes}
  2556. user, _, err := httpd.AddUser(u, http.StatusOK)
  2557. if err != nil {
  2558. t.Errorf("unable to add user: %v", err)
  2559. }
  2560. client, err := getSftpClient(user, usePubKey)
  2561. if err != nil {
  2562. t.Errorf("unable to create sftp client: %v", err)
  2563. } else {
  2564. defer client.Close()
  2565. testFileName := "test_file.dat"
  2566. testFilePath := filepath.Join(homeBasePath, testFileName)
  2567. testFileSize := int64(65535)
  2568. err = createTestFile(testFilePath, testFileSize)
  2569. if err != nil {
  2570. t.Errorf("unable to create test file: %v", err)
  2571. }
  2572. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2573. if err != nil {
  2574. t.Errorf("file upload error: %v", err)
  2575. }
  2576. err = client.Chmod(testFileName, 0666)
  2577. if err == nil {
  2578. t.Errorf("chmod without permission should not succeed")
  2579. }
  2580. err = client.Remove(testFileName)
  2581. if err != nil {
  2582. t.Errorf("error removing uploaded file: %v", err)
  2583. }
  2584. os.Remove(testFilePath)
  2585. }
  2586. _, err = httpd.RemoveUser(user, http.StatusOK)
  2587. if err != nil {
  2588. t.Errorf("unable to remove user: %v", err)
  2589. }
  2590. os.RemoveAll(user.GetHomeDir())
  2591. }
  2592. func TestPermChown(t *testing.T) {
  2593. usePubKey := false
  2594. u := getTestUser(usePubKey)
  2595. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2596. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2597. dataprovider.PermChmod, dataprovider.PermChtimes}
  2598. user, _, err := httpd.AddUser(u, http.StatusOK)
  2599. if err != nil {
  2600. t.Errorf("unable to add user: %v", err)
  2601. }
  2602. client, err := getSftpClient(user, usePubKey)
  2603. if err != nil {
  2604. t.Errorf("unable to create sftp client: %v", err)
  2605. } else {
  2606. defer client.Close()
  2607. testFileName := "test_file.dat"
  2608. testFilePath := filepath.Join(homeBasePath, testFileName)
  2609. testFileSize := int64(65535)
  2610. err = createTestFile(testFilePath, testFileSize)
  2611. if err != nil {
  2612. t.Errorf("unable to create test file: %v", err)
  2613. }
  2614. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2615. if err != nil {
  2616. t.Errorf("file upload error: %v", err)
  2617. }
  2618. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  2619. if err == nil {
  2620. t.Errorf("chown without permission should not succeed")
  2621. }
  2622. err = client.Remove(testFileName)
  2623. if err != nil {
  2624. t.Errorf("error removing uploaded file: %v", err)
  2625. }
  2626. os.Remove(testFilePath)
  2627. }
  2628. _, err = httpd.RemoveUser(user, http.StatusOK)
  2629. if err != nil {
  2630. t.Errorf("unable to remove user: %v", err)
  2631. }
  2632. os.RemoveAll(user.GetHomeDir())
  2633. }
  2634. func TestPermChtimes(t *testing.T) {
  2635. usePubKey := false
  2636. u := getTestUser(usePubKey)
  2637. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2638. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2639. dataprovider.PermChmod, dataprovider.PermChown}
  2640. user, _, err := httpd.AddUser(u, http.StatusOK)
  2641. if err != nil {
  2642. t.Errorf("unable to add user: %v", err)
  2643. }
  2644. client, err := getSftpClient(user, usePubKey)
  2645. if err != nil {
  2646. t.Errorf("unable to create sftp client: %v", err)
  2647. } else {
  2648. defer client.Close()
  2649. testFileName := "test_file.dat"
  2650. testFilePath := filepath.Join(homeBasePath, testFileName)
  2651. testFileSize := int64(65535)
  2652. err = createTestFile(testFilePath, testFileSize)
  2653. if err != nil {
  2654. t.Errorf("unable to create test file: %v", err)
  2655. }
  2656. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2657. if err != nil {
  2658. t.Errorf("file upload error: %v", err)
  2659. }
  2660. err = client.Chtimes(testFileName, time.Now(), time.Now())
  2661. if err == nil {
  2662. t.Errorf("chtimes without permission should not succeed")
  2663. }
  2664. err = client.Remove(testFileName)
  2665. if err != nil {
  2666. t.Errorf("error removing uploaded file: %v", err)
  2667. }
  2668. os.Remove(testFilePath)
  2669. }
  2670. _, err = httpd.RemoveUser(user, http.StatusOK)
  2671. if err != nil {
  2672. t.Errorf("unable to remove user: %v", err)
  2673. }
  2674. os.RemoveAll(user.GetHomeDir())
  2675. }
  2676. func TestSubDirsUploads(t *testing.T) {
  2677. usePubKey := true
  2678. u := getTestUser(usePubKey)
  2679. u.Permissions["/"] = []string{dataprovider.PermAny}
  2680. u.Permissions["/subdir"] = []string{dataprovider.PermChtimes, dataprovider.PermDownload}
  2681. user, _, err := httpd.AddUser(u, http.StatusOK)
  2682. if err != nil {
  2683. t.Errorf("unable to add user: %v", err)
  2684. }
  2685. client, err := getSftpClient(user, usePubKey)
  2686. if err != nil {
  2687. t.Errorf("unable to create sftp client: %v", err)
  2688. } else {
  2689. defer client.Close()
  2690. err = client.Mkdir("subdir")
  2691. if err != nil {
  2692. t.Errorf("unexpected mkdir error: %v", err)
  2693. }
  2694. testFileName := "test_file.dat"
  2695. testFileNameSub := "/subdir/test_file_dat"
  2696. testFilePath := filepath.Join(homeBasePath, testFileName)
  2697. testFileSize := int64(65535)
  2698. err = createTestFile(testFilePath, testFileSize)
  2699. if err != nil {
  2700. t.Errorf("unable to create test file: %v", err)
  2701. }
  2702. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2703. if err != nil {
  2704. t.Errorf("file upload error: %v", err)
  2705. }
  2706. err = sftpUploadFile(testFilePath, testFileNameSub, testFileSize, client)
  2707. if !strings.Contains(err.Error(), "Permission Denied") {
  2708. t.Errorf("unexpected upload error: %v", err)
  2709. }
  2710. err = client.Symlink(testFileName, testFileNameSub+".link")
  2711. if !strings.Contains(err.Error(), "Permission Denied") {
  2712. t.Errorf("unexpected upload error: %v", err)
  2713. }
  2714. err = client.Symlink(testFileName, testFileName+".link")
  2715. if err != nil {
  2716. t.Errorf("symlink error: %v", err)
  2717. }
  2718. err = client.Rename(testFileName, testFileNameSub+".rename")
  2719. if !strings.Contains(err.Error(), "Permission Denied") {
  2720. t.Errorf("unexpected rename error: %v", err)
  2721. }
  2722. err = client.Rename(testFileName, testFileName+".rename")
  2723. if err != nil {
  2724. t.Errorf("rename error: %v", err)
  2725. }
  2726. err = client.Remove(testFileNameSub)
  2727. if !strings.Contains(err.Error(), "Permission Denied") {
  2728. t.Errorf("unexpected upload error: %v", err)
  2729. }
  2730. err = client.Remove(testFileName + ".rename")
  2731. if err != nil {
  2732. t.Errorf("remove error: %v", err)
  2733. }
  2734. os.Remove(testFilePath)
  2735. }
  2736. httpd.RemoveUser(user, http.StatusOK)
  2737. os.RemoveAll(user.GetHomeDir())
  2738. }
  2739. func TestSubDirsOverwrite(t *testing.T) {
  2740. usePubKey := true
  2741. u := getTestUser(usePubKey)
  2742. u.Permissions["/"] = []string{dataprovider.PermAny}
  2743. u.Permissions["/subdir"] = []string{dataprovider.PermOverwrite, dataprovider.PermListItems}
  2744. user, _, err := httpd.AddUser(u, http.StatusOK)
  2745. if err != nil {
  2746. t.Errorf("unable to add user: %v", err)
  2747. }
  2748. client, err := getSftpClient(user, usePubKey)
  2749. if err != nil {
  2750. t.Errorf("unable to create sftp client: %v", err)
  2751. } else {
  2752. defer client.Close()
  2753. testFileName := "/subdir/test_file.dat"
  2754. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  2755. testFileSFTPPath := filepath.Join(u.GetHomeDir(), "subdir", "test_file.dat")
  2756. testFileSize := int64(65535)
  2757. err = createTestFile(testFilePath, testFileSize)
  2758. if err != nil {
  2759. t.Errorf("unable to create test file: %v", err)
  2760. }
  2761. err = createTestFile(testFileSFTPPath, 16384)
  2762. if err != nil {
  2763. t.Errorf("unable to create test file: %v", err)
  2764. }
  2765. err = sftpUploadFile(testFilePath, testFileName+".new", testFileSize, client)
  2766. if !strings.Contains(err.Error(), "Permission Denied") {
  2767. t.Errorf("unexpected upload error: %v", err)
  2768. }
  2769. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2770. if err != nil {
  2771. t.Errorf("unexpected overwrite error: %v", err)
  2772. }
  2773. os.Remove(testFilePath)
  2774. }
  2775. httpd.RemoveUser(user, http.StatusOK)
  2776. os.RemoveAll(user.GetHomeDir())
  2777. }
  2778. func TestSubDirsDownloads(t *testing.T) {
  2779. usePubKey := true
  2780. u := getTestUser(usePubKey)
  2781. u.Permissions["/"] = []string{dataprovider.PermAny}
  2782. u.Permissions["/subdir"] = []string{dataprovider.PermChmod, dataprovider.PermUpload, dataprovider.PermListItems}
  2783. user, _, err := httpd.AddUser(u, http.StatusOK)
  2784. if err != nil {
  2785. t.Errorf("unable to add user: %v", err)
  2786. }
  2787. client, err := getSftpClient(user, usePubKey)
  2788. if err != nil {
  2789. t.Errorf("unable to create sftp client: %v", err)
  2790. } else {
  2791. defer client.Close()
  2792. err = client.Mkdir("subdir")
  2793. if err != nil {
  2794. t.Errorf("unexpected mkdir error: %v", err)
  2795. }
  2796. testFileName := "/subdir/test_file.dat"
  2797. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  2798. testFileSize := int64(65535)
  2799. err = createTestFile(testFilePath, testFileSize)
  2800. if err != nil {
  2801. t.Errorf("unable to create test file: %v", err)
  2802. }
  2803. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2804. if err != nil {
  2805. t.Errorf("file upload error: %v", err)
  2806. }
  2807. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2808. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2809. if !strings.Contains(err.Error(), "Permission Denied") {
  2810. t.Errorf("unexpected upload error: %v", err)
  2811. }
  2812. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2813. if !strings.Contains(err.Error(), "Permission Denied") {
  2814. t.Errorf("unexpected overwrite error: %v", err)
  2815. }
  2816. err = client.Chtimes(testFileName, time.Now(), time.Now())
  2817. if !strings.Contains(err.Error(), "Permission Denied") {
  2818. t.Errorf("unexpected chtimes error: %v", err)
  2819. }
  2820. err = client.Rename(testFileName, testFileName+".rename")
  2821. if !strings.Contains(err.Error(), "Permission Denied") {
  2822. t.Errorf("unexpected rename error: %v", err)
  2823. }
  2824. err = client.Symlink(testFileName, testFileName+".link")
  2825. if !strings.Contains(err.Error(), "Permission Denied") {
  2826. t.Errorf("unexpected symlink error: %v", err)
  2827. }
  2828. err = client.Remove(testFileName)
  2829. if !strings.Contains(err.Error(), "Permission Denied") {
  2830. t.Errorf("unexpected remove error: %v", err)
  2831. }
  2832. os.Remove(localDownloadPath)
  2833. os.Remove(testFilePath)
  2834. }
  2835. httpd.RemoveUser(user, http.StatusOK)
  2836. os.RemoveAll(user.GetHomeDir())
  2837. }
  2838. func TestPermsSubDirsSetstat(t *testing.T) {
  2839. // for setstat we check the parent dir permission if the requested path is a dir
  2840. // otherwise the path permission
  2841. usePubKey := true
  2842. u := getTestUser(usePubKey)
  2843. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermCreateDirs}
  2844. u.Permissions["/subdir"] = []string{dataprovider.PermAny}
  2845. user, _, err := httpd.AddUser(u, http.StatusOK)
  2846. if err != nil {
  2847. t.Errorf("unable to add user: %v", err)
  2848. }
  2849. client, err := getSftpClient(user, usePubKey)
  2850. if err != nil {
  2851. t.Errorf("unable to create sftp client: %v", err)
  2852. } else {
  2853. defer client.Close()
  2854. err = client.Mkdir("subdir")
  2855. if err != nil {
  2856. t.Errorf("unexpected mkdir error: %v", err)
  2857. }
  2858. testFileName := "/subdir/test_file.dat"
  2859. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  2860. testFileSize := int64(65535)
  2861. err = createTestFile(testFilePath, testFileSize)
  2862. if err != nil {
  2863. t.Errorf("unable to create test file: %v", err)
  2864. }
  2865. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2866. if err != nil {
  2867. t.Errorf("file upload error: %v", err)
  2868. }
  2869. err = client.Chtimes("/subdir/", time.Now(), time.Now())
  2870. if !strings.Contains(err.Error(), "Permission Denied") {
  2871. t.Errorf("unexpected chtimes error: %v", err)
  2872. }
  2873. err = client.Chtimes("subdir/", time.Now(), time.Now())
  2874. if !strings.Contains(err.Error(), "Permission Denied") {
  2875. t.Errorf("unexpected chtimes error: %v", err)
  2876. }
  2877. err = client.Chtimes(testFileName, time.Now(), time.Now())
  2878. if err != nil {
  2879. t.Errorf("unexpected chtimes error: %v", err)
  2880. }
  2881. os.Remove(testFilePath)
  2882. }
  2883. httpd.RemoveUser(user, http.StatusOK)
  2884. os.RemoveAll(user.GetHomeDir())
  2885. }
  2886. func TestPermsSubDirsCommands(t *testing.T) {
  2887. usePubKey := true
  2888. u := getTestUser(usePubKey)
  2889. u.Permissions["/"] = []string{dataprovider.PermAny}
  2890. u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  2891. user, _, err := httpd.AddUser(u, http.StatusOK)
  2892. if err != nil {
  2893. t.Errorf("unable to add user: %v", err)
  2894. }
  2895. client, err := getSftpClient(user, usePubKey)
  2896. if err != nil {
  2897. t.Errorf("unable to create sftp client: %v", err)
  2898. } else {
  2899. defer client.Close()
  2900. client.Mkdir("subdir")
  2901. acmodTime := time.Now()
  2902. err = client.Chtimes("/subdir", acmodTime, acmodTime)
  2903. if err != nil {
  2904. t.Errorf("unexpected chtimes error: %v", err)
  2905. }
  2906. _, err = client.Stat("/subdir")
  2907. if err != nil {
  2908. t.Errorf("unexpected stat error: %v", err)
  2909. }
  2910. _, err = client.ReadDir("/")
  2911. if err != nil {
  2912. t.Errorf("unexpected readdir error: %v", err)
  2913. }
  2914. _, err = client.ReadDir("/subdir")
  2915. if !strings.Contains(err.Error(), "Permission Denied") {
  2916. t.Errorf("unexpected error: %v", err)
  2917. }
  2918. err = client.RemoveDirectory("/subdir/dir")
  2919. if !strings.Contains(err.Error(), "Permission Denied") {
  2920. t.Errorf("unexpected error: %v", err)
  2921. }
  2922. err = client.Mkdir("/subdir/dir")
  2923. if !strings.Contains(err.Error(), "Permission Denied") {
  2924. t.Errorf("unexpected error: %v", err)
  2925. }
  2926. client.Mkdir("/otherdir")
  2927. err = client.Rename("/otherdir", "/subdir/otherdir")
  2928. if !strings.Contains(err.Error(), "Permission Denied") {
  2929. t.Errorf("unexpected error: %v", err)
  2930. }
  2931. err = client.Symlink("/otherdir", "/subdir/otherdir")
  2932. if !strings.Contains(err.Error(), "Permission Denied") {
  2933. t.Errorf("unexpected error: %v", err)
  2934. }
  2935. err = client.Symlink("/otherdir", "/otherdir_link")
  2936. if err != nil {
  2937. t.Errorf("unexpected rename dir error: %v", err)
  2938. }
  2939. err = client.Rename("/otherdir", "/otherdir1")
  2940. if err != nil {
  2941. t.Errorf("unexpected rename dir error: %v", err)
  2942. }
  2943. err = client.RemoveDirectory("/subdir")
  2944. if err != nil {
  2945. t.Errorf("unexpected remove dir error: %v", err)
  2946. }
  2947. }
  2948. httpd.RemoveUser(user, http.StatusOK)
  2949. os.RemoveAll(user.GetHomeDir())
  2950. }
  2951. func TestRootDirCommands(t *testing.T) {
  2952. usePubKey := true
  2953. u := getTestUser(usePubKey)
  2954. u.Permissions["/"] = []string{dataprovider.PermAny}
  2955. u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  2956. user, _, err := httpd.AddUser(u, http.StatusOK)
  2957. if err != nil {
  2958. t.Errorf("unable to add user: %v", err)
  2959. }
  2960. client, err := getSftpClient(user, usePubKey)
  2961. if err != nil {
  2962. t.Errorf("unable to create sftp client: %v", err)
  2963. } else {
  2964. defer client.Close()
  2965. err = client.Rename("/", "rootdir")
  2966. if !strings.Contains(err.Error(), "Permission Denied") {
  2967. t.Errorf("unexpected error renaming root dir: %v", err)
  2968. }
  2969. err = client.Symlink("/", "rootdir")
  2970. if !strings.Contains(err.Error(), "Permission Denied") {
  2971. t.Errorf("unexpected error symlinking root dir: %v", err)
  2972. }
  2973. err = client.RemoveDirectory("/")
  2974. if !strings.Contains(err.Error(), "Permission Denied") {
  2975. t.Errorf("unexpected error removing root dir: %v", err)
  2976. }
  2977. }
  2978. httpd.RemoveUser(user, http.StatusOK)
  2979. os.RemoveAll(user.GetHomeDir())
  2980. }
  2981. func TestRelativePaths(t *testing.T) {
  2982. user := getTestUser(true)
  2983. var path, rel string
  2984. filesystems := []vfs.Fs{vfs.NewOsFs("", user.GetHomeDir())}
  2985. keyPrefix := strings.TrimPrefix(user.GetHomeDir(), "/") + "/"
  2986. s3config := vfs.S3FsConfig{
  2987. KeyPrefix: keyPrefix,
  2988. }
  2989. s3fs, _ := vfs.NewS3Fs("", user.GetHomeDir(), s3config)
  2990. gcsConfig := vfs.GCSFsConfig{
  2991. KeyPrefix: keyPrefix,
  2992. }
  2993. gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig)
  2994. if runtime.GOOS != "windows" {
  2995. filesystems = append(filesystems, s3fs, gcsfs)
  2996. }
  2997. for _, fs := range filesystems {
  2998. path = filepath.Join(user.HomeDir, "/")
  2999. rel = fs.GetRelativePath(path)
  3000. if rel != "/" {
  3001. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3002. }
  3003. path = filepath.Join(user.HomeDir, "//")
  3004. rel = fs.GetRelativePath(path)
  3005. if rel != "/" {
  3006. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3007. }
  3008. path = filepath.Join(user.HomeDir, "../..")
  3009. rel = fs.GetRelativePath(path)
  3010. if rel != "/" {
  3011. t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name())
  3012. }
  3013. path = filepath.Join(user.HomeDir, "../../../../../")
  3014. rel = fs.GetRelativePath(path)
  3015. if rel != "/" {
  3016. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3017. }
  3018. path = filepath.Join(user.HomeDir, "/..")
  3019. rel = fs.GetRelativePath(path)
  3020. if rel != "/" {
  3021. t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name())
  3022. }
  3023. path = filepath.Join(user.HomeDir, "/../../../..")
  3024. rel = fs.GetRelativePath(path)
  3025. if rel != "/" {
  3026. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3027. }
  3028. path = filepath.Join(user.HomeDir, "")
  3029. rel = fs.GetRelativePath(path)
  3030. if rel != "/" {
  3031. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3032. }
  3033. path = filepath.Join(user.HomeDir, ".")
  3034. rel = fs.GetRelativePath(path)
  3035. if rel != "/" {
  3036. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3037. }
  3038. path = filepath.Join(user.HomeDir, "somedir")
  3039. rel = fs.GetRelativePath(path)
  3040. if rel != "/somedir" {
  3041. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3042. }
  3043. path = filepath.Join(user.HomeDir, "/somedir/subdir")
  3044. rel = fs.GetRelativePath(path)
  3045. if rel != "/somedir/subdir" {
  3046. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3047. }
  3048. }
  3049. }
  3050. func TestResolvePaths(t *testing.T) {
  3051. user := getTestUser(true)
  3052. var path, resolved string
  3053. var err error
  3054. filesystems := []vfs.Fs{vfs.NewOsFs("", user.GetHomeDir())}
  3055. keyPrefix := strings.TrimPrefix(user.GetHomeDir(), "/") + "/"
  3056. s3config := vfs.S3FsConfig{
  3057. KeyPrefix: keyPrefix,
  3058. }
  3059. os.MkdirAll(user.GetHomeDir(), 0777)
  3060. s3fs, _ := vfs.NewS3Fs("", user.GetHomeDir(), s3config)
  3061. gcsConfig := vfs.GCSFsConfig{
  3062. KeyPrefix: keyPrefix,
  3063. }
  3064. gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig)
  3065. if runtime.GOOS != "windows" {
  3066. filesystems = append(filesystems, s3fs, gcsfs)
  3067. }
  3068. for _, fs := range filesystems {
  3069. path = "/"
  3070. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3071. if resolved != fs.Join(user.GetHomeDir(), "/") {
  3072. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3073. }
  3074. path = "."
  3075. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3076. if resolved != fs.Join(user.GetHomeDir(), "/") {
  3077. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3078. }
  3079. path = "test/sub"
  3080. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3081. if resolved != fs.Join(user.GetHomeDir(), "/test/sub") {
  3082. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3083. }
  3084. path = "../test/sub"
  3085. resolved, err = fs.ResolvePath(filepath.ToSlash(path))
  3086. if vfs.IsLocalOsFs(fs) {
  3087. if err == nil {
  3088. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3089. }
  3090. } else {
  3091. if resolved != fs.Join(user.GetHomeDir(), "/test/sub") && err == nil {
  3092. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3093. }
  3094. }
  3095. path = "../../../test/../sub"
  3096. resolved, err = fs.ResolvePath(filepath.ToSlash(path))
  3097. if vfs.IsLocalOsFs(fs) {
  3098. if err == nil {
  3099. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3100. }
  3101. } else {
  3102. if resolved != fs.Join(user.GetHomeDir(), "/sub") && err == nil {
  3103. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3104. }
  3105. }
  3106. }
  3107. os.RemoveAll(user.GetHomeDir())
  3108. }
  3109. func TestUserPerms(t *testing.T) {
  3110. user := getTestUser(true)
  3111. user.Permissions = make(map[string][]string)
  3112. user.Permissions["/"] = []string{dataprovider.PermListItems}
  3113. user.Permissions["/p"] = []string{dataprovider.PermDelete}
  3114. user.Permissions["/p/1"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  3115. user.Permissions["/p/2"] = []string{dataprovider.PermCreateDirs}
  3116. user.Permissions["/p/3"] = []string{dataprovider.PermChmod}
  3117. user.Permissions["/p/3/4"] = []string{dataprovider.PermChtimes}
  3118. user.Permissions["/tmp"] = []string{dataprovider.PermRename}
  3119. if !user.HasPerm(dataprovider.PermListItems, "/") {
  3120. t.Error("expected permission not found")
  3121. }
  3122. if !user.HasPerm(dataprovider.PermListItems, ".") {
  3123. t.Error("expected permission not found")
  3124. }
  3125. if !user.HasPerm(dataprovider.PermListItems, "") {
  3126. t.Error("expected permission not found")
  3127. }
  3128. if !user.HasPerm(dataprovider.PermListItems, "../") {
  3129. t.Error("expected permission not found")
  3130. }
  3131. // path p and /p are the same
  3132. if !user.HasPerm(dataprovider.PermDelete, "/p") {
  3133. t.Error("expected permission not found")
  3134. }
  3135. if !user.HasPerm(dataprovider.PermDownload, "/p/1") {
  3136. t.Error("expected permission not found")
  3137. }
  3138. if !user.HasPerm(dataprovider.PermCreateDirs, "p/2") {
  3139. t.Error("expected permission not found")
  3140. }
  3141. if !user.HasPerm(dataprovider.PermChmod, "/p/3") {
  3142. t.Error("expected permission not found")
  3143. }
  3144. if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/") {
  3145. t.Error("expected permission not found")
  3146. }
  3147. if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/../4") {
  3148. t.Error("expected permission not found")
  3149. }
  3150. // undefined paths have permissions of the nearest path
  3151. if !user.HasPerm(dataprovider.PermListItems, "/p34") {
  3152. t.Error("expected permission not found")
  3153. }
  3154. if !user.HasPerm(dataprovider.PermListItems, "/p34/p1/file.dat") {
  3155. t.Error("expected permission not found")
  3156. }
  3157. if !user.HasPerm(dataprovider.PermChtimes, "/p/3/4/5/6") {
  3158. t.Error("expected permission not found")
  3159. }
  3160. if !user.HasPerm(dataprovider.PermDownload, "/p/1/test/file.dat") {
  3161. t.Error("expected permission not found")
  3162. }
  3163. }
  3164. func TestUserFiltersIPMaskConditions(t *testing.T) {
  3165. user := getTestUser(true)
  3166. // with no filter login must be allowed even if the remoteIP is invalid
  3167. if !user.IsLoginAllowed("192.168.1.5") {
  3168. t.Error("unexpected login denied")
  3169. }
  3170. if !user.IsLoginAllowed("invalid") {
  3171. t.Error("unexpected login denied")
  3172. }
  3173. user.Filters.DeniedIP = append(user.Filters.DeniedIP, "192.168.1.0/24")
  3174. if user.IsLoginAllowed("192.168.1.5") {
  3175. t.Error("unexpected login allowed")
  3176. }
  3177. if !user.IsLoginAllowed("192.168.2.6") {
  3178. t.Error("unexpected login denied")
  3179. }
  3180. user.Filters.AllowedIP = append(user.Filters.AllowedIP, "192.168.1.5/32")
  3181. // if the same ip/mask is both denied and allowed then login must be denied
  3182. if user.IsLoginAllowed("192.168.1.5") {
  3183. t.Error("unexpected login allowed")
  3184. }
  3185. if user.IsLoginAllowed("192.168.3.6") {
  3186. t.Error("unexpected login allowed")
  3187. }
  3188. user.Filters.DeniedIP = []string{}
  3189. if !user.IsLoginAllowed("192.168.1.5") {
  3190. t.Error("unexpected login denied")
  3191. }
  3192. if user.IsLoginAllowed("192.168.1.6") {
  3193. t.Error("unexpected login allowed")
  3194. }
  3195. user.Filters.DeniedIP = []string{"192.168.0.0/16", "172.16.0.0/16"}
  3196. user.Filters.AllowedIP = []string{}
  3197. if user.IsLoginAllowed("192.168.5.255") {
  3198. t.Error("unexpected login allowed")
  3199. }
  3200. if user.IsLoginAllowed("172.16.1.2") {
  3201. t.Error("unexpected login allowed")
  3202. }
  3203. if !user.IsLoginAllowed("172.18.2.1") {
  3204. t.Error("unexpected login denied")
  3205. }
  3206. user.Filters.AllowedIP = []string{"10.4.4.0/24"}
  3207. if user.IsLoginAllowed("10.5.4.2") {
  3208. t.Error("unexpected login allowed")
  3209. }
  3210. if !user.IsLoginAllowed("10.4.4.2") {
  3211. t.Error("unexpected login denied")
  3212. }
  3213. if !user.IsLoginAllowed("invalid") {
  3214. t.Error("unexpected login denied")
  3215. }
  3216. }
  3217. func TestSSHCommands(t *testing.T) {
  3218. usePubKey := false
  3219. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3220. if err != nil {
  3221. t.Errorf("unable to add user: %v", err)
  3222. }
  3223. _, err = runSSHCommand("ls", user, usePubKey)
  3224. if err == nil {
  3225. t.Errorf("unsupported ssh command must fail")
  3226. }
  3227. _, err = runSSHCommand("cd", user, usePubKey)
  3228. if err != nil {
  3229. t.Errorf("unexpected error for ssh cd command: %v", err)
  3230. }
  3231. out, err := runSSHCommand("pwd", user, usePubKey)
  3232. if err != nil {
  3233. t.Errorf("unexpected error: %v", err)
  3234. t.Fail()
  3235. }
  3236. if string(out) != "/\n" {
  3237. t.Errorf("invalid response for ssh pwd command: %v", string(out))
  3238. }
  3239. out, err = runSSHCommand("md5sum", user, usePubKey)
  3240. if err != nil {
  3241. t.Errorf("unexpected error: %v", err)
  3242. t.Fail()
  3243. }
  3244. // echo -n '' | md5sum
  3245. if !strings.Contains(string(out), "d41d8cd98f00b204e9800998ecf8427e") {
  3246. t.Errorf("invalid md5sum: %v", string(out))
  3247. }
  3248. out, err = runSSHCommand("sha1sum", user, usePubKey)
  3249. if err != nil {
  3250. t.Errorf("unexpected error: %v", err)
  3251. t.Fail()
  3252. }
  3253. if !strings.Contains(string(out), "da39a3ee5e6b4b0d3255bfef95601890afd80709") {
  3254. t.Errorf("invalid sha1sum: %v", string(out))
  3255. }
  3256. out, err = runSSHCommand("sha256sum", user, usePubKey)
  3257. if err != nil {
  3258. t.Errorf("unexpected error: %v", err)
  3259. t.Fail()
  3260. }
  3261. if !strings.Contains(string(out), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") {
  3262. t.Errorf("invalid sha256sum: %v", string(out))
  3263. }
  3264. out, err = runSSHCommand("sha384sum", user, usePubKey)
  3265. if err != nil {
  3266. t.Errorf("unexpected error: %v", err)
  3267. t.Fail()
  3268. }
  3269. if !strings.Contains(string(out), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") {
  3270. t.Errorf("invalid sha384sum: %v", string(out))
  3271. }
  3272. _, err = httpd.RemoveUser(user, http.StatusOK)
  3273. if err != nil {
  3274. t.Errorf("unable to remove user: %v", err)
  3275. }
  3276. }
  3277. func TestSSHFileHash(t *testing.T) {
  3278. usePubKey := true
  3279. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3280. if err != nil {
  3281. t.Errorf("unable to add user: %v", err)
  3282. }
  3283. client, err := getSftpClient(user, usePubKey)
  3284. if err != nil {
  3285. t.Errorf("unable to create sftp client: %v", err)
  3286. } else {
  3287. defer client.Close()
  3288. testFileName := "test_file.dat"
  3289. testFilePath := filepath.Join(homeBasePath, testFileName)
  3290. testFileSize := int64(65535)
  3291. err = createTestFile(testFilePath, testFileSize)
  3292. if err != nil {
  3293. t.Errorf("unable to create test file: %v", err)
  3294. }
  3295. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3296. if err != nil {
  3297. t.Errorf("file upload error: %v", err)
  3298. }
  3299. user.Permissions = make(map[string][]string)
  3300. user.Permissions["/"] = []string{dataprovider.PermUpload}
  3301. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3302. if err != nil {
  3303. t.Errorf("unable to update user: %v", err)
  3304. }
  3305. _, err = runSSHCommand("sha512sum "+testFileName, user, usePubKey)
  3306. if err == nil {
  3307. t.Errorf("hash command with no list permission must fail")
  3308. }
  3309. user.Permissions["/"] = []string{dataprovider.PermAny}
  3310. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3311. if err != nil {
  3312. t.Errorf("unable to update user: %v", err)
  3313. }
  3314. initialHash, err := computeHashForFile(sha512.New(), testFilePath)
  3315. if err != nil {
  3316. t.Errorf("error computing file hash: %v", err)
  3317. }
  3318. out, err := runSSHCommand("sha512sum "+testFileName, user, usePubKey)
  3319. if err != nil {
  3320. t.Errorf("unexpected error: %v", err)
  3321. t.Fail()
  3322. }
  3323. if !strings.Contains(string(out), initialHash) {
  3324. t.Errorf("invalid sha512sum: %v", string(out))
  3325. }
  3326. _, err = runSSHCommand("sha512sum invalid_path", user, usePubKey)
  3327. if err == nil {
  3328. t.Errorf("hash for an invalid path must fail")
  3329. }
  3330. os.Remove(testFilePath)
  3331. }
  3332. _, err = httpd.RemoveUser(user, http.StatusOK)
  3333. if err != nil {
  3334. t.Errorf("unable to remove user: %v", err)
  3335. }
  3336. os.RemoveAll(user.GetHomeDir())
  3337. }
  3338. func TestBasicGitCommands(t *testing.T) {
  3339. if len(gitPath) == 0 || len(sshPath) == 0 {
  3340. t.Skip("git and/or ssh command not found, unable to execute this test")
  3341. }
  3342. usePubKey := true
  3343. u := getTestUser(usePubKey)
  3344. user, _, err := httpd.AddUser(u, http.StatusOK)
  3345. if err != nil {
  3346. t.Errorf("unable to add user: %v", err)
  3347. }
  3348. repoName := "testrepo"
  3349. clonePath := filepath.Join(homeBasePath, repoName)
  3350. os.RemoveAll(user.GetHomeDir())
  3351. os.RemoveAll(filepath.Join(homeBasePath, repoName))
  3352. out, err := initGitRepo(filepath.Join(user.HomeDir, repoName))
  3353. if err != nil {
  3354. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3355. }
  3356. out, err = cloneGitRepo(homeBasePath, "/"+repoName, user.Username)
  3357. if err != nil {
  3358. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3359. }
  3360. out, err = addFileToGitRepo(clonePath, 128)
  3361. if err != nil {
  3362. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3363. }
  3364. user.QuotaFiles = 100000
  3365. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3366. if err != nil {
  3367. t.Errorf("unable to update user: %v", err)
  3368. }
  3369. out, err = pushToGitRepo(clonePath)
  3370. if err != nil {
  3371. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3372. printLatestLogs(10)
  3373. }
  3374. err = waitQuotaScans()
  3375. if err != nil {
  3376. t.Errorf("error waiting for active quota scans: %v", err)
  3377. }
  3378. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3379. if err != nil {
  3380. t.Errorf("unable to get user: %v", err)
  3381. }
  3382. user.QuotaSize = user.UsedQuotaSize - 1
  3383. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3384. if err != nil {
  3385. t.Errorf("unable to update user: %v", err)
  3386. }
  3387. out, err = pushToGitRepo(clonePath)
  3388. if err == nil {
  3389. t.Errorf("git push must fail if quota is exceeded, out: %v", string(out))
  3390. }
  3391. _, err = httpd.RemoveUser(user, http.StatusOK)
  3392. if err != nil {
  3393. t.Errorf("unable to remove user: %v", err)
  3394. }
  3395. os.RemoveAll(user.GetHomeDir())
  3396. os.RemoveAll(clonePath)
  3397. }
  3398. func TestGitErrors(t *testing.T) {
  3399. if len(gitPath) == 0 || len(sshPath) == 0 {
  3400. t.Skip("git and/or ssh command not found, unable to execute this test")
  3401. }
  3402. usePubKey := true
  3403. u := getTestUser(usePubKey)
  3404. user, _, err := httpd.AddUser(u, http.StatusOK)
  3405. if err != nil {
  3406. t.Errorf("unable to add user: %v", err)
  3407. }
  3408. repoName := "testrepo"
  3409. clonePath := filepath.Join(homeBasePath, repoName)
  3410. os.RemoveAll(user.GetHomeDir())
  3411. os.RemoveAll(filepath.Join(homeBasePath, repoName))
  3412. out, err := cloneGitRepo(homeBasePath, "/"+repoName, user.Username)
  3413. if err == nil {
  3414. t.Errorf("cloning a missing repo must fail, out: %v", string(out))
  3415. }
  3416. _, err = httpd.RemoveUser(user, http.StatusOK)
  3417. if err != nil {
  3418. t.Errorf("unable to remove user: %v", err)
  3419. }
  3420. os.RemoveAll(user.GetHomeDir())
  3421. os.RemoveAll(clonePath)
  3422. }
  3423. // Start SCP tests
  3424. func TestSCPBasicHandling(t *testing.T) {
  3425. if len(scpPath) == 0 {
  3426. t.Skip("scp command not found, unable to execute this test")
  3427. }
  3428. usePubKey := true
  3429. u := getTestUser(usePubKey)
  3430. u.QuotaSize = 6553600
  3431. user, _, err := httpd.AddUser(u, http.StatusOK)
  3432. if err != nil {
  3433. t.Errorf("unable to add user: %v", err)
  3434. }
  3435. testFileName := "test_file.dat"
  3436. testFilePath := filepath.Join(homeBasePath, testFileName)
  3437. testFileSize := int64(131074)
  3438. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  3439. expectedQuotaFiles := user.UsedQuotaFiles + 1
  3440. err = createTestFile(testFilePath, testFileSize)
  3441. if err != nil {
  3442. t.Errorf("unable to create test file: %v", err)
  3443. }
  3444. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  3445. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3446. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3447. // test to download a missing file
  3448. err = scpDownload(localPath, remoteDownPath, false, false)
  3449. if err == nil {
  3450. t.Errorf("downloading a missing file via scp must fail")
  3451. }
  3452. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3453. if err != nil {
  3454. t.Errorf("error uploading file via scp: %v", err)
  3455. }
  3456. err = scpDownload(localPath, remoteDownPath, false, false)
  3457. if err != nil {
  3458. t.Errorf("error downloading file via scp: %v", err)
  3459. }
  3460. fi, err := os.Stat(localPath)
  3461. if err != nil {
  3462. t.Errorf("stat for the downloaded file must succeed")
  3463. } else {
  3464. if fi.Size() != testFileSize {
  3465. t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v",
  3466. fi.Size(), testFileSize)
  3467. }
  3468. }
  3469. os.Remove(localPath)
  3470. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3471. if err != nil {
  3472. t.Errorf("error getting user: %v", err)
  3473. }
  3474. if expectedQuotaFiles != user.UsedQuotaFiles {
  3475. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  3476. }
  3477. if expectedQuotaSize != user.UsedQuotaSize {
  3478. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  3479. }
  3480. err = os.RemoveAll(user.GetHomeDir())
  3481. if err != nil {
  3482. t.Errorf("error removing uploaded files")
  3483. }
  3484. _, err = httpd.RemoveUser(user, http.StatusOK)
  3485. if err != nil {
  3486. t.Errorf("unable to remove user: %v", err)
  3487. }
  3488. os.Remove(testFilePath)
  3489. }
  3490. func TestSCPUploadFileOverwrite(t *testing.T) {
  3491. if len(scpPath) == 0 {
  3492. t.Skip("scp command not found, unable to execute this test")
  3493. }
  3494. usePubKey := true
  3495. u := getTestUser(usePubKey)
  3496. u.QuotaFiles = 1000
  3497. user, _, err := httpd.AddUser(u, http.StatusOK)
  3498. if err != nil {
  3499. t.Errorf("unable to add user: %v", err)
  3500. }
  3501. os.RemoveAll(user.GetHomeDir())
  3502. testFileName := "test_file.dat"
  3503. testFilePath := filepath.Join(homeBasePath, testFileName)
  3504. testFileSize := int64(32760)
  3505. err = createTestFile(testFilePath, testFileSize)
  3506. if err != nil {
  3507. t.Errorf("unable to create test file: %v", err)
  3508. }
  3509. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3510. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3511. if err != nil {
  3512. t.Errorf("error uploading file via scp: %v", err)
  3513. }
  3514. // test a new upload that must overwrite the existing file
  3515. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3516. if err != nil {
  3517. t.Errorf("error uploading existing file via scp: %v", err)
  3518. }
  3519. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3520. if err != nil {
  3521. t.Errorf("error getting user: %v", err)
  3522. }
  3523. if user.UsedQuotaSize != testFileSize || user.UsedQuotaFiles != 1 {
  3524. t.Errorf("update quota error on file overwrite, actual size: %v, expected: %v actual files: %v, expected: 1",
  3525. user.UsedQuotaSize, testFileSize, user.UsedQuotaFiles)
  3526. }
  3527. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3528. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3529. err = scpDownload(localPath, remoteDownPath, false, false)
  3530. if err != nil {
  3531. t.Errorf("error downloading file via scp: %v", err)
  3532. }
  3533. fi, err := os.Stat(localPath)
  3534. if err != nil {
  3535. t.Errorf("stat for the downloaded file must succeed")
  3536. } else {
  3537. if fi.Size() != testFileSize {
  3538. t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v",
  3539. fi.Size(), testFileSize)
  3540. }
  3541. }
  3542. os.Remove(localPath)
  3543. os.Remove(testFilePath)
  3544. err = os.RemoveAll(user.GetHomeDir())
  3545. if err != nil {
  3546. t.Errorf("error removing uploaded files")
  3547. }
  3548. _, err = httpd.RemoveUser(user, http.StatusOK)
  3549. if err != nil {
  3550. t.Errorf("unable to remove user: %v", err)
  3551. }
  3552. }
  3553. func TestSCPRecursive(t *testing.T) {
  3554. if len(scpPath) == 0 {
  3555. t.Skip("scp command not found, unable to execute this test")
  3556. }
  3557. usePubKey := true
  3558. u := getTestUser(usePubKey)
  3559. user, _, err := httpd.AddUser(u, http.StatusOK)
  3560. if err != nil {
  3561. t.Errorf("unable to add user: %v", err)
  3562. }
  3563. testFileName := "test_file.dat"
  3564. testBaseDirName := "test_dir"
  3565. testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName)
  3566. testBaseDirDownName := "test_dir_down"
  3567. testBaseDirDownPath := filepath.Join(homeBasePath, testBaseDirDownName)
  3568. testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName)
  3569. testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName)
  3570. testFileSize := int64(131074)
  3571. createTestFile(testFilePath, testFileSize)
  3572. createTestFile(testFilePath1, testFileSize)
  3573. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testBaseDirName))
  3574. // test to download a missing dir
  3575. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true)
  3576. if err == nil {
  3577. t.Errorf("downloading a missing dir via scp must fail")
  3578. }
  3579. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  3580. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  3581. if err != nil {
  3582. t.Errorf("error uploading dir via scp: %v", err)
  3583. }
  3584. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true)
  3585. if err != nil {
  3586. t.Errorf("error downloading dir via scp: %v", err)
  3587. }
  3588. // test download without passing -r
  3589. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, false)
  3590. if err == nil {
  3591. t.Errorf("recursive download without -r must fail")
  3592. }
  3593. fi, err := os.Stat(filepath.Join(testBaseDirDownPath, testFileName))
  3594. if err != nil {
  3595. t.Errorf("error downloading file using scp recursive: %v", err)
  3596. } else {
  3597. if fi.Size() != testFileSize {
  3598. t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize)
  3599. }
  3600. }
  3601. fi, err = os.Stat(filepath.Join(testBaseDirDownPath, testBaseDirName, testFileName))
  3602. if err != nil {
  3603. t.Errorf("error downloading file using scp recursive: %v", err)
  3604. } else {
  3605. if fi.Size() != testFileSize {
  3606. t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize)
  3607. }
  3608. }
  3609. // upload to a non existent dir
  3610. remoteUpPath = fmt.Sprintf("%[email protected]:%v", user.Username, "/non_existent_dir")
  3611. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  3612. if err == nil {
  3613. t.Errorf("uploading via scp to a non existent dir must fail")
  3614. }
  3615. os.RemoveAll(testBaseDirPath)
  3616. os.RemoveAll(testBaseDirDownPath)
  3617. err = os.RemoveAll(user.GetHomeDir())
  3618. if err != nil {
  3619. t.Errorf("error removing uploaded files")
  3620. }
  3621. _, err = httpd.RemoveUser(user, http.StatusOK)
  3622. if err != nil {
  3623. t.Errorf("unable to remove user: %v", err)
  3624. }
  3625. }
  3626. func TestSCPPermsSubDirs(t *testing.T) {
  3627. if len(scpPath) == 0 {
  3628. t.Skip("scp command not found, unable to execute this test")
  3629. }
  3630. usePubKey := true
  3631. u := getTestUser(usePubKey)
  3632. u.Permissions["/"] = []string{dataprovider.PermAny}
  3633. u.Permissions["/somedir"] = []string{dataprovider.PermListItems, dataprovider.PermUpload}
  3634. user, _, err := httpd.AddUser(u, http.StatusOK)
  3635. if err != nil {
  3636. t.Errorf("unable to add user: %v", err)
  3637. }
  3638. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3639. subPath := filepath.Join(user.GetHomeDir(), "somedir")
  3640. testFileSize := int64(65535)
  3641. os.MkdirAll(subPath, 0777)
  3642. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/somedir")
  3643. err = scpDownload(localPath, remoteDownPath, false, true)
  3644. if err == nil {
  3645. t.Error("download a dir with no permissions must fail")
  3646. }
  3647. os.Remove(subPath)
  3648. err = createTestFile(subPath, testFileSize)
  3649. if err != nil {
  3650. t.Errorf("unable to create test file: %v", err)
  3651. }
  3652. err = scpDownload(localPath, remoteDownPath, false, false)
  3653. if err != nil {
  3654. t.Errorf("unexpected download error: %v", err)
  3655. }
  3656. os.Chmod(subPath, 0001)
  3657. err = scpDownload(localPath, remoteDownPath, false, false)
  3658. if err == nil {
  3659. t.Error("download a file with no system permissions must fail")
  3660. }
  3661. os.Chmod(subPath, 0755)
  3662. os.Remove(localPath)
  3663. os.RemoveAll(user.GetHomeDir())
  3664. _, err = httpd.RemoveUser(user, http.StatusOK)
  3665. if err != nil {
  3666. t.Errorf("unable to remove user: %v", err)
  3667. }
  3668. }
  3669. func TestSCPPermCreateDirs(t *testing.T) {
  3670. if len(scpPath) == 0 {
  3671. t.Skip("scp command not found, unable to execute this test")
  3672. }
  3673. usePubKey := true
  3674. u := getTestUser(usePubKey)
  3675. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  3676. user, _, err := httpd.AddUser(u, http.StatusOK)
  3677. if err != nil {
  3678. t.Errorf("unable to add user: %v", err)
  3679. }
  3680. testFileName := "test_file.dat"
  3681. testFilePath := filepath.Join(homeBasePath, testFileName)
  3682. testFileSize := int64(32760)
  3683. testBaseDirName := "test_dir"
  3684. testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName)
  3685. testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testFileName)
  3686. err = createTestFile(testFilePath, testFileSize)
  3687. if err != nil {
  3688. t.Errorf("unable to create test file: %v", err)
  3689. }
  3690. err = createTestFile(testFilePath1, testFileSize)
  3691. if err != nil {
  3692. t.Errorf("unable to create test file: %v", err)
  3693. }
  3694. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp/")
  3695. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3696. if err == nil {
  3697. t.Errorf("scp upload must fail, the user cannot create files in a missing dir")
  3698. }
  3699. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  3700. if err == nil {
  3701. t.Errorf("scp upload must fail, the user cannot create new dirs")
  3702. }
  3703. err = os.Remove(testFilePath)
  3704. if err != nil {
  3705. t.Errorf("error removing test file")
  3706. }
  3707. os.RemoveAll(testBaseDirPath)
  3708. err = os.RemoveAll(user.GetHomeDir())
  3709. if err != nil {
  3710. t.Errorf("error removing uploaded files")
  3711. }
  3712. _, err = httpd.RemoveUser(user, http.StatusOK)
  3713. if err != nil {
  3714. t.Errorf("unable to remove user: %v", err)
  3715. }
  3716. }
  3717. func TestSCPPermUpload(t *testing.T) {
  3718. if len(scpPath) == 0 {
  3719. t.Skip("scp command not found, unable to execute this test")
  3720. }
  3721. usePubKey := true
  3722. u := getTestUser(usePubKey)
  3723. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermCreateDirs}
  3724. user, _, err := httpd.AddUser(u, http.StatusOK)
  3725. if err != nil {
  3726. t.Errorf("unable to add user: %v", err)
  3727. }
  3728. testFileName := "test_file.dat"
  3729. testFilePath := filepath.Join(homeBasePath, testFileName)
  3730. testFileSize := int64(65536)
  3731. err = createTestFile(testFilePath, testFileSize)
  3732. if err != nil {
  3733. t.Errorf("unable to create test file: %v", err)
  3734. }
  3735. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp")
  3736. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3737. if err == nil {
  3738. t.Errorf("scp upload must fail, the user cannot upload")
  3739. }
  3740. err = os.Remove(testFilePath)
  3741. if err != nil {
  3742. t.Errorf("error removing test file")
  3743. }
  3744. err = os.RemoveAll(user.GetHomeDir())
  3745. if err != nil {
  3746. t.Errorf("error removing uploaded files")
  3747. }
  3748. _, err = httpd.RemoveUser(user, http.StatusOK)
  3749. if err != nil {
  3750. t.Errorf("unable to remove user: %v", err)
  3751. }
  3752. }
  3753. func TestSCPPermOverwrite(t *testing.T) {
  3754. if len(scpPath) == 0 {
  3755. t.Skip("scp command not found, unable to execute this test")
  3756. }
  3757. usePubKey := true
  3758. u := getTestUser(usePubKey)
  3759. u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs}
  3760. user, _, err := httpd.AddUser(u, http.StatusOK)
  3761. if err != nil {
  3762. t.Errorf("unable to add user: %v", err)
  3763. }
  3764. testFileName := "test_file.dat"
  3765. testFilePath := filepath.Join(homeBasePath, testFileName)
  3766. testFileSize := int64(65536)
  3767. err = createTestFile(testFilePath, testFileSize)
  3768. if err != nil {
  3769. t.Errorf("unable to create test file: %v", err)
  3770. }
  3771. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp")
  3772. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3773. if err != nil {
  3774. t.Errorf("scp upload error: %v", err)
  3775. }
  3776. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3777. if err == nil {
  3778. t.Errorf("scp upload must fail, the user cannot ovewrite existing files")
  3779. }
  3780. err = os.Remove(testFilePath)
  3781. if err != nil {
  3782. t.Errorf("error removing test file")
  3783. }
  3784. err = os.RemoveAll(user.GetHomeDir())
  3785. if err != nil {
  3786. t.Errorf("error removing uploaded files")
  3787. }
  3788. _, err = httpd.RemoveUser(user, http.StatusOK)
  3789. if err != nil {
  3790. t.Errorf("unable to remove user: %v", err)
  3791. }
  3792. }
  3793. func TestSCPPermDownload(t *testing.T) {
  3794. if len(scpPath) == 0 {
  3795. t.Skip("scp command not found, unable to execute this test")
  3796. }
  3797. usePubKey := true
  3798. u := getTestUser(usePubKey)
  3799. u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs}
  3800. user, _, err := httpd.AddUser(u, http.StatusOK)
  3801. if err != nil {
  3802. t.Errorf("unable to add user: %v", err)
  3803. }
  3804. testFileName := "test_file.dat"
  3805. testFilePath := filepath.Join(homeBasePath, testFileName)
  3806. testFileSize := int64(65537)
  3807. err = createTestFile(testFilePath, testFileSize)
  3808. if err != nil {
  3809. t.Errorf("unable to create test file: %v", err)
  3810. }
  3811. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  3812. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3813. if err != nil {
  3814. t.Errorf("error uploading existing file via scp: %v", err)
  3815. }
  3816. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3817. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3818. err = scpDownload(localPath, remoteDownPath, false, false)
  3819. if err == nil {
  3820. t.Errorf("scp download must fail, the user cannot download")
  3821. }
  3822. err = os.Remove(testFilePath)
  3823. if err != nil {
  3824. t.Errorf("error removing test file")
  3825. }
  3826. err = os.RemoveAll(user.GetHomeDir())
  3827. if err != nil {
  3828. t.Errorf("error removing uploaded files")
  3829. }
  3830. _, err = httpd.RemoveUser(user, http.StatusOK)
  3831. if err != nil {
  3832. t.Errorf("unable to remove user: %v", err)
  3833. }
  3834. }
  3835. func TestSCPQuotaSize(t *testing.T) {
  3836. if len(scpPath) == 0 {
  3837. t.Skip("scp command not found, unable to execute this test")
  3838. }
  3839. usePubKey := true
  3840. testFileSize := int64(65535)
  3841. u := getTestUser(usePubKey)
  3842. u.QuotaFiles = 1
  3843. u.QuotaSize = testFileSize - 1
  3844. user, _, err := httpd.AddUser(u, http.StatusOK)
  3845. if err != nil {
  3846. t.Errorf("unable to add user: %v", err)
  3847. }
  3848. testFileName := "test_file.dat"
  3849. testFilePath := filepath.Join(homeBasePath, testFileName)
  3850. err = createTestFile(testFilePath, testFileSize)
  3851. if err != nil {
  3852. t.Errorf("unable to create test file: %v", err)
  3853. }
  3854. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3855. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3856. if err != nil {
  3857. t.Errorf("error uploading existing file via scp: %v", err)
  3858. }
  3859. err = scpUpload(testFilePath, remoteUpPath+".quota", true, false)
  3860. if err == nil {
  3861. t.Errorf("user is over quota scp upload must fail")
  3862. }
  3863. err = os.Remove(testFilePath)
  3864. if err != nil {
  3865. t.Errorf("error removing test file")
  3866. }
  3867. err = os.RemoveAll(user.GetHomeDir())
  3868. if err != nil {
  3869. t.Errorf("error removing uploaded files")
  3870. }
  3871. _, err = httpd.RemoveUser(user, http.StatusOK)
  3872. if err != nil {
  3873. t.Errorf("unable to remove user: %v", err)
  3874. }
  3875. }
  3876. func TestSCPEscapeHomeDir(t *testing.T) {
  3877. if len(scpPath) == 0 {
  3878. t.Skip("scp command not found, unable to execute this test")
  3879. }
  3880. usePubKey := true
  3881. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3882. if err != nil {
  3883. t.Errorf("unable to add user: %v", err)
  3884. }
  3885. os.MkdirAll(user.GetHomeDir(), 0777)
  3886. testDir := "testDir"
  3887. linkPath := filepath.Join(homeBasePath, defaultUsername, testDir)
  3888. err = os.Symlink(homeBasePath, linkPath)
  3889. if err != nil {
  3890. t.Errorf("error making local symlink: %v", err)
  3891. }
  3892. testFileName := "test_file.dat"
  3893. testFilePath := filepath.Join(homeBasePath, testFileName)
  3894. testFileSize := int64(65535)
  3895. err = createTestFile(testFilePath, testFileSize)
  3896. if err != nil {
  3897. t.Errorf("unable to create test file: %v", err)
  3898. }
  3899. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDir, testDir))
  3900. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3901. if err == nil {
  3902. t.Errorf("uploading to a dir with a symlink outside home dir must fail")
  3903. }
  3904. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testDir, testFileName))
  3905. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3906. err = scpDownload(localPath, remoteDownPath, false, false)
  3907. if err == nil {
  3908. t.Errorf("scp download must fail, the requested file has a symlink outside user home")
  3909. }
  3910. remoteDownPath = fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testDir))
  3911. err = scpDownload(homeBasePath, remoteDownPath, false, true)
  3912. if err == nil {
  3913. t.Errorf("scp download must fail, the requested dir is a symlink outside user home")
  3914. }
  3915. err = os.Remove(testFilePath)
  3916. if err != nil {
  3917. t.Errorf("error removing test file")
  3918. }
  3919. err = os.RemoveAll(user.GetHomeDir())
  3920. if err != nil {
  3921. t.Errorf("error removing uploaded files")
  3922. }
  3923. _, err = httpd.RemoveUser(user, http.StatusOK)
  3924. if err != nil {
  3925. t.Errorf("unable to remove user: %v", err)
  3926. }
  3927. }
  3928. func TestSCPUploadPaths(t *testing.T) {
  3929. if len(scpPath) == 0 {
  3930. t.Skip("scp command not found, unable to execute this test")
  3931. }
  3932. usePubKey := true
  3933. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3934. if err != nil {
  3935. t.Errorf("unable to add user: %v", err)
  3936. }
  3937. testFileName := "test_file.dat"
  3938. testFilePath := filepath.Join(homeBasePath, testFileName)
  3939. testFileSize := int64(65535)
  3940. testDirName := "testDir"
  3941. testDirPath := filepath.Join(user.GetHomeDir(), testDirName)
  3942. os.MkdirAll(testDirPath, 0777)
  3943. err = createTestFile(testFilePath, testFileSize)
  3944. if err != nil {
  3945. t.Errorf("unable to create test file: %v", err)
  3946. }
  3947. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, testDirName)
  3948. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDirName, testFileName))
  3949. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3950. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3951. if err != nil {
  3952. t.Errorf("scp upload error: %v", err)
  3953. }
  3954. err = scpDownload(localPath, remoteDownPath, false, false)
  3955. if err != nil {
  3956. t.Errorf("scp download error: %v", err)
  3957. }
  3958. // upload a file to a missing dir
  3959. remoteUpPath = fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDirName, testDirName, testFileName))
  3960. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3961. if err == nil {
  3962. t.Errorf("scp upload to a missing dir must fail")
  3963. }
  3964. err = os.RemoveAll(user.GetHomeDir())
  3965. if err != nil {
  3966. t.Errorf("error removing uploaded files")
  3967. }
  3968. os.Remove(localPath)
  3969. _, err = httpd.RemoveUser(user, http.StatusOK)
  3970. if err != nil {
  3971. t.Errorf("unable to remove user: %v", err)
  3972. }
  3973. }
  3974. func TestSCPOverwriteDirWithFile(t *testing.T) {
  3975. if len(scpPath) == 0 {
  3976. t.Skip("scp command not found, unable to execute this test")
  3977. }
  3978. usePubKey := true
  3979. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3980. if err != nil {
  3981. t.Errorf("unable to add user: %v", err)
  3982. }
  3983. testFileName := "test_file.dat"
  3984. testFilePath := filepath.Join(homeBasePath, testFileName)
  3985. testFileSize := int64(65535)
  3986. testDirPath := filepath.Join(user.GetHomeDir(), testFileName)
  3987. os.MkdirAll(testDirPath, 0777)
  3988. err = createTestFile(testFilePath, testFileSize)
  3989. if err != nil {
  3990. t.Errorf("unable to create test file: %v", err)
  3991. }
  3992. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  3993. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3994. if err == nil {
  3995. t.Errorf("copying a file over an existing dir must fail")
  3996. }
  3997. err = os.RemoveAll(user.GetHomeDir())
  3998. if err != nil {
  3999. t.Errorf("error removing uploaded files")
  4000. }
  4001. _, err = httpd.RemoveUser(user, http.StatusOK)
  4002. if err != nil {
  4003. t.Errorf("unable to remove user: %v", err)
  4004. }
  4005. }
  4006. func TestSCPRemoteToRemote(t *testing.T) {
  4007. if len(scpPath) == 0 {
  4008. t.Skip("scp command not found, unable to execute this test")
  4009. }
  4010. usePubKey := true
  4011. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  4012. if err != nil {
  4013. t.Errorf("unable to add user: %v", err)
  4014. }
  4015. u := getTestUser(usePubKey)
  4016. u.Username += "1"
  4017. u.HomeDir += "1"
  4018. user1, _, err := httpd.AddUser(u, http.StatusOK)
  4019. if err != nil {
  4020. t.Errorf("unable to add user: %v", err)
  4021. }
  4022. testFileName := "test_file.dat"
  4023. testFilePath := filepath.Join(homeBasePath, testFileName)
  4024. testFileSize := int64(65535)
  4025. err = createTestFile(testFilePath, testFileSize)
  4026. if err != nil {
  4027. t.Errorf("unable to create test file: %v", err)
  4028. }
  4029. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4030. remote1UpPath := fmt.Sprintf("%[email protected]:%v", user1.Username, path.Join("/", testFileName))
  4031. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4032. if err != nil {
  4033. t.Errorf("scp upload error: %v", err)
  4034. }
  4035. err = scpUpload(remoteUpPath, remote1UpPath, false, true)
  4036. if err != nil {
  4037. t.Errorf("scp upload remote to remote error: %v", err)
  4038. }
  4039. err = os.RemoveAll(user.GetHomeDir())
  4040. if err != nil {
  4041. t.Errorf("error removing uploaded files")
  4042. }
  4043. _, err = httpd.RemoveUser(user, http.StatusOK)
  4044. if err != nil {
  4045. t.Errorf("unable to remove user: %v", err)
  4046. }
  4047. err = os.RemoveAll(user1.GetHomeDir())
  4048. if err != nil {
  4049. t.Errorf("error removing uploaded files for user1")
  4050. }
  4051. _, err = httpd.RemoveUser(user1, http.StatusOK)
  4052. if err != nil {
  4053. t.Errorf("unable to remove user1: %v", err)
  4054. }
  4055. }
  4056. func TestSCPErrors(t *testing.T) {
  4057. if len(scpPath) == 0 {
  4058. t.Skip("scp command not found, unable to execute this test")
  4059. }
  4060. u := getTestUser(true)
  4061. user, _, err := httpd.AddUser(u, http.StatusOK)
  4062. if err != nil {
  4063. t.Errorf("unable to add user: %v", err)
  4064. }
  4065. testFileSize := int64(524288)
  4066. testFileName := "test_file.dat"
  4067. testFilePath := filepath.Join(homeBasePath, testFileName)
  4068. err = createTestFile(testFilePath, testFileSize)
  4069. if err != nil {
  4070. t.Errorf("unable to create test file: %v", err)
  4071. }
  4072. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4073. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4074. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4075. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4076. if err != nil {
  4077. t.Errorf("error uploading file via scp: %v", err)
  4078. }
  4079. user.UploadBandwidth = 512
  4080. user.DownloadBandwidth = 512
  4081. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  4082. if err != nil {
  4083. t.Errorf("unable to update user: %v", err)
  4084. }
  4085. cmd := getScpDownloadCommand(localPath, remoteDownPath, false, false)
  4086. go func() {
  4087. if cmd.Run() == nil {
  4088. t.Errorf("SCP download must fail")
  4089. }
  4090. }()
  4091. waitForActiveTransfer()
  4092. // wait some additional arbitrary time to wait for transfer activity to happen
  4093. // it is need to reach all the code in CheckIdleConnections
  4094. time.Sleep(100 * time.Millisecond)
  4095. cmd.Process.Kill()
  4096. waitForNoActiveTransfer()
  4097. cmd = getScpUploadCommand(testFilePath, remoteUpPath, false, false)
  4098. go func() {
  4099. if cmd.Run() == nil {
  4100. t.Errorf("SCP upload must fail")
  4101. }
  4102. }()
  4103. waitForActiveTransfer()
  4104. // wait some additional arbitrary time to wait for transfer activity to happen
  4105. // it is need to reach all the code in CheckIdleConnections
  4106. time.Sleep(100 * time.Millisecond)
  4107. cmd.Process.Kill()
  4108. waitForNoActiveTransfer()
  4109. err = os.Remove(testFilePath)
  4110. if err != nil {
  4111. t.Errorf("error removing test file")
  4112. }
  4113. os.Remove(localPath)
  4114. err = os.RemoveAll(user.GetHomeDir())
  4115. if err != nil {
  4116. t.Errorf("error removing uploaded files")
  4117. }
  4118. _, err = httpd.RemoveUser(user, http.StatusOK)
  4119. if err != nil {
  4120. t.Errorf("unable to remove user: %v", err)
  4121. }
  4122. }
  4123. // End SCP tests
  4124. func waitTCPListening(address string) {
  4125. for {
  4126. conn, err := net.Dial("tcp", address)
  4127. if err != nil {
  4128. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  4129. time.Sleep(100 * time.Millisecond)
  4130. continue
  4131. }
  4132. logger.InfoToConsole("tcp server %v now listening\n", address)
  4133. defer conn.Close()
  4134. break
  4135. }
  4136. }
  4137. func getTestUser(usePubKey bool) dataprovider.User {
  4138. user := dataprovider.User{
  4139. Username: defaultUsername,
  4140. Password: defaultPassword,
  4141. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  4142. Status: 1,
  4143. ExpirationDate: 0,
  4144. }
  4145. user.Permissions = make(map[string][]string)
  4146. user.Permissions["/"] = allPerms
  4147. if usePubKey {
  4148. user.PublicKeys = []string{testPubKey}
  4149. user.Password = ""
  4150. }
  4151. return user
  4152. }
  4153. func runSSHCommand(command string, user dataprovider.User, usePubKey bool) ([]byte, error) {
  4154. var sshSession *ssh.Session
  4155. var output []byte
  4156. config := &ssh.ClientConfig{
  4157. User: defaultUsername,
  4158. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4159. return nil
  4160. },
  4161. }
  4162. if usePubKey {
  4163. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  4164. if err != nil {
  4165. return output, err
  4166. }
  4167. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  4168. } else {
  4169. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  4170. }
  4171. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  4172. if err != nil {
  4173. return output, err
  4174. }
  4175. defer conn.Close()
  4176. sshSession, err = conn.NewSession()
  4177. if err != nil {
  4178. return output, err
  4179. }
  4180. var stdout, stderr bytes.Buffer
  4181. sshSession.Stdout = &stdout
  4182. sshSession.Stderr = &stderr
  4183. err = sshSession.Run(command)
  4184. if err != nil {
  4185. return nil, fmt.Errorf("failed to run command %v: %v", command, stderr.Bytes())
  4186. }
  4187. return stdout.Bytes(), err
  4188. }
  4189. func getSftpClient(user dataprovider.User, usePubKey bool) (*sftp.Client, error) {
  4190. var sftpClient *sftp.Client
  4191. config := &ssh.ClientConfig{
  4192. User: user.Username,
  4193. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4194. return nil
  4195. },
  4196. }
  4197. if usePubKey {
  4198. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  4199. if err != nil {
  4200. return nil, err
  4201. }
  4202. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  4203. } else {
  4204. if len(user.Password) > 0 {
  4205. config.Auth = []ssh.AuthMethod{ssh.Password(user.Password)}
  4206. } else {
  4207. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  4208. }
  4209. }
  4210. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  4211. if err != nil {
  4212. return sftpClient, err
  4213. }
  4214. sftpClient, err = sftp.NewClient(conn)
  4215. return sftpClient, err
  4216. }
  4217. func getKeyboardInteractiveSftpClient(user dataprovider.User, answers []string) (*sftp.Client, error) {
  4218. var sftpClient *sftp.Client
  4219. config := &ssh.ClientConfig{
  4220. User: user.Username,
  4221. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4222. return nil
  4223. },
  4224. Auth: []ssh.AuthMethod{
  4225. ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {
  4226. return answers, nil
  4227. }),
  4228. },
  4229. }
  4230. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  4231. if err != nil {
  4232. return sftpClient, err
  4233. }
  4234. sftpClient, err = sftp.NewClient(conn)
  4235. return sftpClient, err
  4236. }
  4237. func createTestFile(path string, size int64) error {
  4238. baseDir := filepath.Dir(path)
  4239. if _, err := os.Stat(baseDir); os.IsNotExist(err) {
  4240. os.MkdirAll(baseDir, 0777)
  4241. }
  4242. content := make([]byte, size)
  4243. _, err := rand.Read(content)
  4244. if err != nil {
  4245. return err
  4246. }
  4247. return ioutil.WriteFile(path, content, 0666)
  4248. }
  4249. func appendToTestFile(path string, size int64) error {
  4250. content := make([]byte, size)
  4251. _, err := rand.Read(content)
  4252. if err != nil {
  4253. return err
  4254. }
  4255. f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0666)
  4256. if err != nil {
  4257. return err
  4258. }
  4259. written, err := io.Copy(f, bytes.NewReader(content))
  4260. if err != nil {
  4261. return err
  4262. }
  4263. if int64(written) != size {
  4264. return fmt.Errorf("write error, written: %v/%v", written, size)
  4265. }
  4266. return nil
  4267. }
  4268. func sftpUploadFile(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) error {
  4269. srcFile, err := os.Open(localSourcePath)
  4270. if err != nil {
  4271. return err
  4272. }
  4273. defer srcFile.Close()
  4274. destFile, err := client.Create(remoteDestPath)
  4275. if err != nil {
  4276. return err
  4277. }
  4278. _, err = io.Copy(destFile, srcFile)
  4279. if err != nil {
  4280. destFile.Close()
  4281. return err
  4282. }
  4283. // we need to close the file to trigger the close method on server
  4284. // we cannot defer closing or Lstat will fail for uploads in atomic mode
  4285. destFile.Close()
  4286. if expectedSize > 0 {
  4287. fi, err := client.Stat(remoteDestPath)
  4288. if err != nil {
  4289. return err
  4290. }
  4291. if fi.Size() != expectedSize {
  4292. return fmt.Errorf("uploaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4293. }
  4294. }
  4295. return err
  4296. }
  4297. func sftpUploadResumeFile(localSourcePath string, remoteDestPath string, expectedSize int64, invalidOffset bool,
  4298. client *sftp.Client) error {
  4299. srcFile, err := os.Open(localSourcePath)
  4300. if err != nil {
  4301. return err
  4302. }
  4303. defer srcFile.Close()
  4304. fi, err := client.Lstat(remoteDestPath)
  4305. if err != nil {
  4306. return err
  4307. }
  4308. if !invalidOffset {
  4309. _, err = srcFile.Seek(fi.Size(), 0)
  4310. if err != nil {
  4311. return err
  4312. }
  4313. }
  4314. destFile, err := client.OpenFile(remoteDestPath, os.O_WRONLY|os.O_APPEND)
  4315. if err != nil {
  4316. return err
  4317. }
  4318. if !invalidOffset {
  4319. _, err = destFile.Seek(fi.Size(), 0)
  4320. if err != nil {
  4321. return err
  4322. }
  4323. }
  4324. _, err = io.Copy(destFile, srcFile)
  4325. if err != nil {
  4326. destFile.Close()
  4327. return err
  4328. }
  4329. // we need to close the file to trigger the close method on server
  4330. // we cannot defer closing or Lstat will fail for upload atomic mode
  4331. destFile.Close()
  4332. if expectedSize > 0 {
  4333. fi, err := client.Lstat(remoteDestPath)
  4334. if err != nil {
  4335. return err
  4336. }
  4337. if fi.Size() != expectedSize {
  4338. return fmt.Errorf("uploaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4339. }
  4340. }
  4341. return err
  4342. }
  4343. func sftpDownloadFile(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) error {
  4344. downloadDest, err := os.Create(localDestPath)
  4345. if err != nil {
  4346. return err
  4347. }
  4348. defer downloadDest.Close()
  4349. sftpSrcFile, err := client.Open(remoteSourcePath)
  4350. if err != nil {
  4351. return err
  4352. }
  4353. defer sftpSrcFile.Close()
  4354. _, err = io.Copy(downloadDest, sftpSrcFile)
  4355. if err != nil {
  4356. return err
  4357. }
  4358. err = downloadDest.Sync()
  4359. if err != nil {
  4360. return err
  4361. }
  4362. if expectedSize > 0 {
  4363. fi, err := downloadDest.Stat()
  4364. if err != nil {
  4365. return err
  4366. }
  4367. if fi.Size() != expectedSize {
  4368. return fmt.Errorf("downloaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4369. }
  4370. }
  4371. return err
  4372. }
  4373. func sftpUploadNonBlocking(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  4374. c := make(chan error)
  4375. go func() {
  4376. c <- sftpUploadFile(localSourcePath, remoteDestPath, expectedSize, client)
  4377. }()
  4378. return c
  4379. }
  4380. func sftpDownloadNonBlocking(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  4381. c := make(chan error)
  4382. go func() {
  4383. c <- sftpDownloadFile(remoteSourcePath, localDestPath, expectedSize, client)
  4384. }()
  4385. return c
  4386. }
  4387. func scpUpload(localPath, remotePath string, preserveTime, remoteToRemote bool) error {
  4388. cmd := getScpUploadCommand(localPath, remotePath, preserveTime, remoteToRemote)
  4389. return cmd.Run()
  4390. }
  4391. func scpDownload(localPath, remotePath string, preserveTime, recursive bool) error {
  4392. cmd := getScpDownloadCommand(localPath, remotePath, preserveTime, recursive)
  4393. return cmd.Run()
  4394. }
  4395. func getScpDownloadCommand(localPath, remotePath string, preserveTime, recursive bool) *exec.Cmd {
  4396. var args []string
  4397. if preserveTime {
  4398. args = append(args, "-p")
  4399. }
  4400. if recursive {
  4401. args = append(args, "-r")
  4402. }
  4403. args = append(args, "-P")
  4404. args = append(args, "2022")
  4405. args = append(args, "-o")
  4406. args = append(args, "StrictHostKeyChecking=no")
  4407. args = append(args, "-i")
  4408. args = append(args, privateKeyPath)
  4409. args = append(args, remotePath)
  4410. args = append(args, localPath)
  4411. return exec.Command(scpPath, args...)
  4412. }
  4413. func getScpUploadCommand(localPath, remotePath string, preserveTime, remoteToRemote bool) *exec.Cmd {
  4414. var args []string
  4415. if remoteToRemote {
  4416. args = append(args, "-3")
  4417. }
  4418. if preserveTime {
  4419. args = append(args, "-p")
  4420. }
  4421. fi, err := os.Stat(localPath)
  4422. if err == nil {
  4423. if fi.IsDir() {
  4424. args = append(args, "-r")
  4425. }
  4426. }
  4427. args = append(args, "-P")
  4428. args = append(args, "2022")
  4429. args = append(args, "-o")
  4430. args = append(args, "StrictHostKeyChecking=no")
  4431. args = append(args, "-i")
  4432. args = append(args, privateKeyPath)
  4433. args = append(args, localPath)
  4434. args = append(args, remotePath)
  4435. return exec.Command(scpPath, args...)
  4436. }
  4437. func computeHashForFile(hasher hash.Hash, path string) (string, error) {
  4438. hash := ""
  4439. f, err := os.Open(path)
  4440. if err != nil {
  4441. return hash, err
  4442. }
  4443. defer f.Close()
  4444. _, err = io.Copy(hasher, f)
  4445. if err == nil {
  4446. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  4447. }
  4448. return hash, err
  4449. }
  4450. func waitForNoActiveTransfer() {
  4451. for len(sftpd.GetConnectionsStats()) > 0 {
  4452. time.Sleep(100 * time.Millisecond)
  4453. }
  4454. }
  4455. func waitForActiveTransfer() {
  4456. stats := sftpd.GetConnectionsStats()
  4457. for len(stats) < 1 {
  4458. stats = sftpd.GetConnectionsStats()
  4459. }
  4460. activeTransferFound := false
  4461. for !activeTransferFound {
  4462. stats = sftpd.GetConnectionsStats()
  4463. if len(stats) == 0 {
  4464. break
  4465. }
  4466. for _, stat := range stats {
  4467. if len(stat.Transfers) > 0 {
  4468. activeTransferFound = true
  4469. }
  4470. }
  4471. }
  4472. }
  4473. func waitQuotaScans() error {
  4474. time.Sleep(100 * time.Millisecond)
  4475. scans, _, err := httpd.GetQuotaScans(http.StatusOK)
  4476. if err != nil {
  4477. return err
  4478. }
  4479. for len(scans) > 0 {
  4480. time.Sleep(100 * time.Millisecond)
  4481. scans, _, err = httpd.GetQuotaScans(http.StatusOK)
  4482. if err != nil {
  4483. return err
  4484. }
  4485. }
  4486. return nil
  4487. }
  4488. func initGitRepo(path string) ([]byte, error) {
  4489. os.MkdirAll(path, 0777)
  4490. args := []string{"init", "--bare"}
  4491. cmd := exec.Command(gitPath, args...)
  4492. cmd.Dir = path
  4493. return cmd.CombinedOutput()
  4494. }
  4495. func pushToGitRepo(repoPath string) ([]byte, error) {
  4496. cmd := exec.Command(gitPath, "push")
  4497. cmd.Dir = repoPath
  4498. cmd.Env = append(os.Environ(),
  4499. fmt.Sprintf("GIT_SSH=%v", gitWrapPath))
  4500. return cmd.CombinedOutput()
  4501. }
  4502. func cloneGitRepo(basePath, remotePath, username string) ([]byte, error) {
  4503. remoteUrl := fmt.Sprintf("ssh://%[email protected]:2022%v", username, remotePath)
  4504. args := []string{"clone", remoteUrl}
  4505. cmd := exec.Command(gitPath, args...)
  4506. cmd.Dir = basePath
  4507. cmd.Env = append(os.Environ(),
  4508. fmt.Sprintf("GIT_SSH=%v", gitWrapPath))
  4509. return cmd.CombinedOutput()
  4510. }
  4511. func addFileToGitRepo(repoPath string, fileSize int64) ([]byte, error) {
  4512. path := filepath.Join(repoPath, "test")
  4513. err := createTestFile(path, fileSize)
  4514. if err != nil {
  4515. return []byte(""), err
  4516. }
  4517. cmd := exec.Command(gitPath, "config", "user.email", "[email protected]")
  4518. cmd.Dir = repoPath
  4519. out, err := cmd.CombinedOutput()
  4520. if err != nil {
  4521. return out, err
  4522. }
  4523. cmd = exec.Command(gitPath, "config", "user.name", "testuser")
  4524. cmd.Dir = repoPath
  4525. out, err = cmd.CombinedOutput()
  4526. if err != nil {
  4527. return out, err
  4528. }
  4529. cmd = exec.Command(gitPath, "add", "test")
  4530. cmd.Dir = repoPath
  4531. out, err = cmd.CombinedOutput()
  4532. if err != nil {
  4533. return out, err
  4534. }
  4535. cmd = exec.Command(gitPath, "commit", "-am", "test")
  4536. cmd.Dir = repoPath
  4537. return cmd.CombinedOutput()
  4538. }
  4539. func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJsonResponse bool, result int) []byte {
  4540. content := []byte("#!/bin/sh\n\n")
  4541. q, _ := json.Marshal(questions)
  4542. echos := []bool{}
  4543. for index := range questions {
  4544. echos = append(echos, index%2 == 0)
  4545. }
  4546. e, _ := json.Marshal(echos)
  4547. if nonJsonResponse {
  4548. content = append(content, []byte(fmt.Sprintf("echo 'questions: %v echos: %v\n", string(q), string(e)))...)
  4549. } else {
  4550. content = append(content, []byte(fmt.Sprintf("echo '{\"questions\":%v,\"echos\":%v}'\n", string(q), string(e)))...)
  4551. }
  4552. for index := range questions {
  4553. content = append(content, []byte(fmt.Sprintf("read ANSWER%v\n", index))...)
  4554. }
  4555. if sleepTime > 0 {
  4556. content = append(content, []byte(fmt.Sprintf("sleep %v\n", sleepTime))...)
  4557. }
  4558. content = append(content, []byte(fmt.Sprintf("echo '{\"auth_result\":%v}'\n", result))...)
  4559. return content
  4560. }
  4561. func getExtAuthScriptContent(user dataprovider.User, sleepTime int, nonJsonResponse bool) []byte {
  4562. extAuthContent := []byte("#!/bin/sh\n\n")
  4563. u, _ := json.Marshal(user)
  4564. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("if test \"$SFTPGO_AUTHD_USERNAME\" = \"%v\"; then\n", user.Username))...)
  4565. if nonJsonResponse {
  4566. extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...)
  4567. } else {
  4568. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("echo '%v'\n", string(u)))...)
  4569. }
  4570. extAuthContent = append(extAuthContent, []byte("else\n")...)
  4571. if nonJsonResponse {
  4572. extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...)
  4573. } else {
  4574. extAuthContent = append(extAuthContent, []byte("echo '{\"username\":\"\"}'\n")...)
  4575. }
  4576. extAuthContent = append(extAuthContent, []byte("fi\n")...)
  4577. if sleepTime > 0 {
  4578. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("sleep %v\n", sleepTime))...)
  4579. }
  4580. return extAuthContent
  4581. }
  4582. func printLatestLogs(maxNumberOfLines int) {
  4583. var lines []string
  4584. f, err := os.Open(logFilePath)
  4585. if err != nil {
  4586. return
  4587. }
  4588. defer f.Close()
  4589. scanner := bufio.NewScanner(f)
  4590. for scanner.Scan() {
  4591. lines = append(lines, scanner.Text()+"\r\n")
  4592. for len(lines) > maxNumberOfLines {
  4593. lines = lines[1:]
  4594. }
  4595. }
  4596. if scanner.Err() != nil {
  4597. logger.WarnToConsole("Unable to print latest logs: %v", scanner.Err())
  4598. return
  4599. }
  4600. for _, line := range lines {
  4601. logger.DebugToConsole(line)
  4602. }
  4603. }