sftpd_test.go 162 KB

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