dataprovider.go 160 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package dataprovider provides data access.
  15. // It abstracts different data providers using a common API.
  16. package dataprovider
  17. import (
  18. "bufio"
  19. "bytes"
  20. "context"
  21. "crypto/md5"
  22. "crypto/rsa"
  23. "crypto/sha1"
  24. "crypto/sha256"
  25. "crypto/sha512"
  26. "crypto/subtle"
  27. "crypto/x509"
  28. "encoding/base64"
  29. "encoding/hex"
  30. "encoding/json"
  31. "encoding/pem"
  32. "errors"
  33. "fmt"
  34. "hash"
  35. "io"
  36. "net"
  37. "net/http"
  38. "net/url"
  39. "os"
  40. "os/exec"
  41. "path"
  42. "path/filepath"
  43. "regexp"
  44. "runtime"
  45. "strconv"
  46. "strings"
  47. "sync"
  48. "sync/atomic"
  49. "time"
  50. "github.com/GehirnInc/crypt"
  51. "github.com/GehirnInc/crypt/apr1_crypt"
  52. "github.com/GehirnInc/crypt/md5_crypt"
  53. "github.com/GehirnInc/crypt/sha256_crypt"
  54. "github.com/GehirnInc/crypt/sha512_crypt"
  55. "github.com/alexedwards/argon2id"
  56. "github.com/go-chi/render"
  57. "github.com/rs/xid"
  58. "github.com/sftpgo/sdk"
  59. passwordvalidator "github.com/wagslane/go-password-validator"
  60. "golang.org/x/crypto/bcrypt"
  61. "golang.org/x/crypto/pbkdf2"
  62. "golang.org/x/crypto/ssh"
  63. "github.com/drakkan/sftpgo/v2/internal/command"
  64. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  65. "github.com/drakkan/sftpgo/v2/internal/kms"
  66. "github.com/drakkan/sftpgo/v2/internal/logger"
  67. "github.com/drakkan/sftpgo/v2/internal/mfa"
  68. "github.com/drakkan/sftpgo/v2/internal/plugin"
  69. "github.com/drakkan/sftpgo/v2/internal/util"
  70. "github.com/drakkan/sftpgo/v2/internal/vfs"
  71. )
  72. const (
  73. // SQLiteDataProviderName defines the name for SQLite database provider
  74. SQLiteDataProviderName = "sqlite"
  75. // PGSQLDataProviderName defines the name for PostgreSQL database provider
  76. PGSQLDataProviderName = "postgresql"
  77. // MySQLDataProviderName defines the name for MySQL database provider
  78. MySQLDataProviderName = "mysql"
  79. // BoltDataProviderName defines the name for bbolt key/value store provider
  80. BoltDataProviderName = "bolt"
  81. // MemoryDataProviderName defines the name for memory provider
  82. MemoryDataProviderName = "memory"
  83. // CockroachDataProviderName defines the for CockroachDB provider
  84. CockroachDataProviderName = "cockroachdb"
  85. // DumpVersion defines the version for the dump.
  86. // For restore/load we support the current version and the previous one
  87. DumpVersion = 16
  88. argonPwdPrefix = "$argon2id$"
  89. bcryptPwdPrefix = "$2a$"
  90. pbkdf2SHA1Prefix = "$pbkdf2-sha1$"
  91. pbkdf2SHA256Prefix = "$pbkdf2-sha256$"
  92. pbkdf2SHA512Prefix = "$pbkdf2-sha512$"
  93. pbkdf2SHA256B64SaltPrefix = "$pbkdf2-b64salt-sha256$"
  94. md5cryptPwdPrefix = "$1$"
  95. md5cryptApr1PwdPrefix = "$apr1$"
  96. sha256cryptPwdPrefix = "$5$"
  97. sha512cryptPwdPrefix = "$6$"
  98. yescryptPwdPrefix = "$y$"
  99. md5DigestPwdPrefix = "{MD5}"
  100. sha256DigestPwdPrefix = "{SHA256}"
  101. sha512DigestPwdPrefix = "{SHA512}"
  102. trackQuotaDisabledError = "please enable track_quota in your configuration to use this method"
  103. operationAdd = "add"
  104. operationUpdate = "update"
  105. operationDelete = "delete"
  106. sqlPrefixValidChars = "abcdefghijklmnopqrstuvwxyz_0123456789"
  107. maxHookResponseSize = 1048576 // 1MB
  108. iso8601UTCFormat = "2006-01-02T15:04:05Z"
  109. )
  110. // Supported algorithms for hashing passwords.
  111. // These algorithms can be used when SFTPGo hashes a plain text password
  112. const (
  113. HashingAlgoBcrypt = "bcrypt"
  114. HashingAlgoArgon2ID = "argon2id"
  115. )
  116. // ordering constants
  117. const (
  118. OrderASC = "ASC"
  119. OrderDESC = "DESC"
  120. )
  121. const (
  122. protocolSSH = "SSH"
  123. protocolFTP = "FTP"
  124. protocolWebDAV = "DAV"
  125. protocolHTTP = "HTTP"
  126. )
  127. // Dump scopes
  128. const (
  129. DumpScopeUsers = "users"
  130. DumpScopeFolders = "folders"
  131. DumpScopeGroups = "groups"
  132. DumpScopeAdmins = "admins"
  133. DumpScopeAPIKeys = "api_keys"
  134. DumpScopeShares = "shares"
  135. DumpScopeActions = "actions"
  136. DumpScopeRules = "rules"
  137. DumpScopeRoles = "roles"
  138. DumpScopeIPLists = "ip_lists"
  139. DumpScopeConfigs = "configs"
  140. )
  141. const (
  142. fieldUsername = 1
  143. fieldName = 2
  144. fieldIPNet = 3
  145. )
  146. var (
  147. // SupportedProviders defines the supported data providers
  148. SupportedProviders = []string{SQLiteDataProviderName, PGSQLDataProviderName, MySQLDataProviderName,
  149. BoltDataProviderName, MemoryDataProviderName, CockroachDataProviderName}
  150. // ValidPerms defines all the valid permissions for a user
  151. ValidPerms = []string{PermAny, PermListItems, PermDownload, PermUpload, PermOverwrite, PermCreateDirs, PermRename,
  152. PermRenameFiles, PermRenameDirs, PermDelete, PermDeleteFiles, PermDeleteDirs, PermCopy, PermCreateSymlinks,
  153. PermChmod, PermChown, PermChtimes}
  154. // ValidLoginMethods defines all the valid login methods
  155. ValidLoginMethods = []string{SSHLoginMethodPublicKey, LoginMethodPassword, SSHLoginMethodPassword,
  156. SSHLoginMethodKeyboardInteractive, SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt,
  157. LoginMethodTLSCertificate, LoginMethodTLSCertificateAndPwd}
  158. // SSHMultiStepsLoginMethods defines the supported Multi-Step Authentications
  159. SSHMultiStepsLoginMethods = []string{SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt}
  160. // ErrNoAuthTried defines the error for connection closed before authentication
  161. ErrNoAuthTried = errors.New("no auth tried")
  162. // ErrNotImplemented defines the error for features not supported for a particular data provider
  163. ErrNotImplemented = errors.New("feature not supported with the configured data provider")
  164. // ValidProtocols defines all the valid protcols
  165. ValidProtocols = []string{protocolSSH, protocolFTP, protocolWebDAV, protocolHTTP}
  166. // MFAProtocols defines the supported protocols for multi-factor authentication
  167. MFAProtocols = []string{protocolHTTP, protocolSSH, protocolFTP}
  168. // ErrNoInitRequired defines the error returned by InitProvider if no inizialization/update is required
  169. ErrNoInitRequired = errors.New("the data provider is up to date")
  170. // ErrInvalidCredentials defines the error to return if the supplied credentials are invalid
  171. ErrInvalidCredentials = errors.New("invalid credentials")
  172. // ErrLoginNotAllowedFromIP defines the error to return if login is denied from the current IP
  173. ErrLoginNotAllowedFromIP = errors.New("login is not allowed from this IP")
  174. // ErrDuplicatedKey occurs when there is a unique key constraint violation
  175. ErrDuplicatedKey = errors.New("duplicated key not allowed")
  176. // ErrForeignKeyViolated occurs when there is a foreign key constraint violation
  177. ErrForeignKeyViolated = errors.New("violates foreign key constraint")
  178. tz = ""
  179. isAdminCreated atomic.Bool
  180. validTLSUsernames = []string{string(sdk.TLSUsernameNone), string(sdk.TLSUsernameCN)}
  181. config Config
  182. provider Provider
  183. sqlPlaceholders []string
  184. internalHashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix}
  185. hashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix, pbkdf2SHA1Prefix, pbkdf2SHA256Prefix,
  186. pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix, md5cryptPwdPrefix, md5cryptApr1PwdPrefix, md5DigestPwdPrefix,
  187. sha256DigestPwdPrefix, sha512DigestPwdPrefix, sha256cryptPwdPrefix, sha512cryptPwdPrefix, yescryptPwdPrefix}
  188. pbkdfPwdPrefixes = []string{pbkdf2SHA1Prefix, pbkdf2SHA256Prefix, pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix}
  189. pbkdfPwdB64SaltPrefixes = []string{pbkdf2SHA256B64SaltPrefix}
  190. unixPwdPrefixes = []string{md5cryptPwdPrefix, md5cryptApr1PwdPrefix, sha256cryptPwdPrefix, sha512cryptPwdPrefix,
  191. yescryptPwdPrefix}
  192. digestPwdPrefixes = []string{md5DigestPwdPrefix, sha256DigestPwdPrefix, sha512DigestPwdPrefix}
  193. sharedProviders = []string{PGSQLDataProviderName, MySQLDataProviderName, CockroachDataProviderName}
  194. logSender = "dataprovider"
  195. sqlTableUsers string
  196. sqlTableFolders string
  197. sqlTableUsersFoldersMapping string
  198. sqlTableAdmins string
  199. sqlTableAPIKeys string
  200. sqlTableShares string
  201. sqlTableDefenderHosts string
  202. sqlTableDefenderEvents string
  203. sqlTableActiveTransfers string
  204. sqlTableGroups string
  205. sqlTableUsersGroupsMapping string
  206. sqlTableAdminsGroupsMapping string
  207. sqlTableGroupsFoldersMapping string
  208. sqlTableSharedSessions string
  209. sqlTableEventsActions string
  210. sqlTableEventsRules string
  211. sqlTableRulesActionsMapping string
  212. sqlTableTasks string
  213. sqlTableNodes string
  214. sqlTableRoles string
  215. sqlTableIPLists string
  216. sqlTableConfigs string
  217. sqlTableSchemaVersion string
  218. argon2Params *argon2id.Params
  219. lastLoginMinDelay = 10 * time.Minute
  220. usernameRegex = regexp.MustCompile("^[a-zA-Z0-9-_.~]+$")
  221. tempPath string
  222. allowSelfConnections int
  223. fnReloadRules FnReloadRules
  224. fnRemoveRule FnRemoveRule
  225. fnHandleRuleForProviderEvent FnHandleRuleForProviderEvent
  226. )
  227. func initSQLTables() {
  228. sqlTableUsers = "users"
  229. sqlTableFolders = "folders"
  230. sqlTableUsersFoldersMapping = "users_folders_mapping"
  231. sqlTableAdmins = "admins"
  232. sqlTableAPIKeys = "api_keys"
  233. sqlTableShares = "shares"
  234. sqlTableDefenderHosts = "defender_hosts"
  235. sqlTableDefenderEvents = "defender_events"
  236. sqlTableActiveTransfers = "active_transfers"
  237. sqlTableGroups = "groups"
  238. sqlTableUsersGroupsMapping = "users_groups_mapping"
  239. sqlTableGroupsFoldersMapping = "groups_folders_mapping"
  240. sqlTableAdminsGroupsMapping = "admins_groups_mapping"
  241. sqlTableSharedSessions = "shared_sessions"
  242. sqlTableEventsActions = "events_actions"
  243. sqlTableEventsRules = "events_rules"
  244. sqlTableRulesActionsMapping = "rules_actions_mapping"
  245. sqlTableTasks = "tasks"
  246. sqlTableNodes = "nodes"
  247. sqlTableRoles = "roles"
  248. sqlTableIPLists = "ip_lists"
  249. sqlTableConfigs = "configurations"
  250. sqlTableSchemaVersion = "schema_version"
  251. }
  252. // FnReloadRules defined the callback to reload event rules
  253. type FnReloadRules func()
  254. // FnRemoveRule defines the callback to remove an event rule
  255. type FnRemoveRule func(name string)
  256. // FnHandleRuleForProviderEvent define the callback to handle event rules for provider events
  257. type FnHandleRuleForProviderEvent func(operation, executor, ip, objectType, objectName, role string, object plugin.Renderer)
  258. // SetEventRulesCallbacks sets the event rules callbacks
  259. func SetEventRulesCallbacks(reload FnReloadRules, remove FnRemoveRule, handle FnHandleRuleForProviderEvent) {
  260. fnReloadRules = reload
  261. fnRemoveRule = remove
  262. fnHandleRuleForProviderEvent = handle
  263. }
  264. type schemaVersion struct {
  265. Version int
  266. }
  267. // BcryptOptions defines the options for bcrypt password hashing
  268. type BcryptOptions struct {
  269. Cost int `json:"cost" mapstructure:"cost"`
  270. }
  271. // Argon2Options defines the options for argon2 password hashing
  272. type Argon2Options struct {
  273. Memory uint32 `json:"memory" mapstructure:"memory"`
  274. Iterations uint32 `json:"iterations" mapstructure:"iterations"`
  275. Parallelism uint8 `json:"parallelism" mapstructure:"parallelism"`
  276. }
  277. // PasswordHashing defines the configuration for password hashing
  278. type PasswordHashing struct {
  279. BcryptOptions BcryptOptions `json:"bcrypt_options" mapstructure:"bcrypt_options"`
  280. Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"`
  281. // Algorithm to use for hashing passwords. Available algorithms: argon2id, bcrypt. Default: bcrypt
  282. Algo string `json:"algo" mapstructure:"algo"`
  283. }
  284. // PasswordValidationRules defines the password validation rules
  285. type PasswordValidationRules struct {
  286. // MinEntropy defines the minimum password entropy.
  287. // 0 means disabled, any password will be accepted.
  288. // Take a look at the following link for more details
  289. // https://github.com/wagslane/go-password-validator#what-entropy-value-should-i-use
  290. MinEntropy float64 `json:"min_entropy" mapstructure:"min_entropy"`
  291. }
  292. // PasswordValidation defines the password validation rules for admins and protocol users
  293. type PasswordValidation struct {
  294. // Password validation rules for SFTPGo admin users
  295. Admins PasswordValidationRules `json:"admins" mapstructure:"admins"`
  296. // Password validation rules for SFTPGo protocol users
  297. Users PasswordValidationRules `json:"users" mapstructure:"users"`
  298. }
  299. type wrappedFolder struct {
  300. Folder vfs.BaseVirtualFolder
  301. }
  302. func (w *wrappedFolder) RenderAsJSON(reload bool) ([]byte, error) {
  303. if reload {
  304. folder, err := provider.getFolderByName(w.Folder.Name)
  305. if err != nil {
  306. providerLog(logger.LevelError, "unable to reload folder before rendering as json: %v", err)
  307. return nil, err
  308. }
  309. folder.PrepareForRendering()
  310. return json.Marshal(folder)
  311. }
  312. w.Folder.PrepareForRendering()
  313. return json.Marshal(w.Folder)
  314. }
  315. // ObjectsActions defines the action to execute on user create, update, delete for the specified objects
  316. type ObjectsActions struct {
  317. // Valid values are add, update, delete. Empty slice to disable
  318. ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
  319. // Valid values are user, admin, api_key
  320. ExecuteFor []string `json:"execute_for" mapstructure:"execute_for"`
  321. // Absolute path to an external program or an HTTP URL
  322. Hook string `json:"hook" mapstructure:"hook"`
  323. }
  324. // ProviderStatus defines the provider status
  325. type ProviderStatus struct {
  326. Driver string `json:"driver"`
  327. IsActive bool `json:"is_active"`
  328. Error string `json:"error"`
  329. }
  330. // Config defines the provider configuration
  331. type Config struct {
  332. // Driver name, must be one of the SupportedProviders
  333. Driver string `json:"driver" mapstructure:"driver"`
  334. // Database name. For driver sqlite this can be the database name relative to the config dir
  335. // or the absolute path to the SQLite database.
  336. Name string `json:"name" mapstructure:"name"`
  337. // Database host. For postgresql and cockroachdb driver you can specify multiple hosts separated by commas
  338. Host string `json:"host" mapstructure:"host"`
  339. // Database port
  340. Port int `json:"port" mapstructure:"port"`
  341. // Database username
  342. Username string `json:"username" mapstructure:"username"`
  343. // Database password
  344. Password string `json:"password" mapstructure:"password"`
  345. // Used for drivers mysql and postgresql.
  346. // 0 disable SSL/TLS connections.
  347. // 1 require ssl.
  348. // 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql.
  349. // 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql.
  350. SSLMode int `json:"sslmode" mapstructure:"sslmode"`
  351. // Used for drivers mysql, postgresql and cockroachdb. Set to true to disable SNI
  352. DisableSNI bool `json:"disable_sni" mapstructure:"disable_sni"`
  353. // TargetSessionAttrs is a postgresql and cockroachdb specific option.
  354. // It determines whether the session must have certain properties to be acceptable.
  355. // It's typically used in combination with multiple host names to select the first
  356. // acceptable alternative among several hosts
  357. TargetSessionAttrs string `json:"target_session_attrs" mapstructure:"target_session_attrs"`
  358. // Path to the root certificate authority used to verify that the server certificate was signed by a trusted CA
  359. RootCert string `json:"root_cert" mapstructure:"root_cert"`
  360. // Path to the client certificate for two-way TLS authentication
  361. ClientCert string `json:"client_cert" mapstructure:"client_cert"`
  362. // Path to the client key for two-way TLS authentication
  363. ClientKey string `json:"client_key" mapstructure:"client_key"`
  364. // Custom database connection string.
  365. // If not empty this connection string will be used instead of build one using the previous parameters
  366. ConnectionString string `json:"connection_string" mapstructure:"connection_string"`
  367. // prefix for SQL tables
  368. SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"`
  369. // Set the preferred way to track users quota between the following choices:
  370. // 0, disable quota tracking. REST API to scan user dir and update quota will do nothing
  371. // 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions
  372. // 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions
  373. // and for virtual folders.
  374. // With this configuration the "quota scan" REST API can still be used to periodically update space usage
  375. // for users without quota restrictions
  376. TrackQuota int `json:"track_quota" mapstructure:"track_quota"`
  377. // Sets the maximum number of open connections for mysql and postgresql driver.
  378. // Default 0 (unlimited)
  379. PoolSize int `json:"pool_size" mapstructure:"pool_size"`
  380. // Users default base directory.
  381. // If no home dir is defined while adding a new user, and this value is
  382. // a valid absolute path, then the user home dir will be automatically
  383. // defined as the path obtained joining the base dir and the username
  384. UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"`
  385. // Actions to execute on objects add, update, delete.
  386. // The supported objects are user, admin, api_key.
  387. // Update action will not be fired for internal updates such as the last login or the user quota fields.
  388. Actions ObjectsActions `json:"actions" mapstructure:"actions"`
  389. // Absolute path to an external program or an HTTP URL to invoke for users authentication.
  390. // Leave empty to use builtin authentication.
  391. // If the authentication succeed the user will be automatically added/updated inside the defined data provider.
  392. // Actions defined for user added/updated will not be executed in this case.
  393. // This method is slower than built-in authentication methods, but it's very flexible as anyone can
  394. // easily write his own authentication hooks.
  395. ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"`
  396. // ExternalAuthScope defines the scope for the external authentication hook.
  397. // - 0 means all supported authentication scopes, the external hook will be executed for password,
  398. // public key, keyboard interactive authentication and TLS certificates
  399. // - 1 means passwords only
  400. // - 2 means public keys only
  401. // - 4 means keyboard interactive only
  402. // - 8 means TLS certificates only
  403. // you can combine the scopes, for example 3 means password and public key, 5 password and keyboard
  404. // interactive and so on
  405. ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"`
  406. // Absolute path to an external program or an HTTP URL to invoke just before the user login.
  407. // This program/URL allows to modify or create the user trying to login.
  408. // It is useful if you have users with dynamic fields to update just before the login.
  409. // Please note that if you want to create a new user, the pre-login hook response must
  410. // include all the mandatory user fields.
  411. //
  412. // The pre-login hook must finish within 30 seconds.
  413. //
  414. // If an error happens while executing the "PreLoginHook" then login will be denied.
  415. // PreLoginHook and ExternalAuthHook are mutally exclusive.
  416. // Leave empty to disable.
  417. PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"`
  418. // Absolute path to an external program or an HTTP URL to invoke after the user login.
  419. // Based on the configured scope you can choose if notify failed or successful logins
  420. // or both
  421. PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"`
  422. // PostLoginScope defines the scope for the post-login hook.
  423. // - 0 means notify both failed and successful logins
  424. // - 1 means notify failed logins
  425. // - 2 means notify successful logins
  426. PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"`
  427. // Absolute path to an external program or an HTTP URL to invoke just before password
  428. // authentication. This hook allows you to externally check the provided password,
  429. // its main use case is to allow to easily support things like password+OTP for protocols
  430. // without keyboard interactive support such as FTP and WebDAV. You can ask your users
  431. // to login using a string consisting of a fixed password and a One Time Token, you
  432. // can verify the token inside the hook and ask to SFTPGo to verify the fixed part.
  433. CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"`
  434. // CheckPasswordScope defines the scope for the check password hook.
  435. // - 0 means all protocols
  436. // - 1 means SSH
  437. // - 2 means FTP
  438. // - 4 means WebDAV
  439. // you can combine the scopes, for example 6 means FTP and WebDAV
  440. CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"`
  441. // Defines how the database will be initialized/updated:
  442. // - 0 means automatically
  443. // - 1 means manually using the initprovider sub-command
  444. UpdateMode int `json:"update_mode" mapstructure:"update_mode"`
  445. // PasswordHashing defines the configuration for password hashing
  446. PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"`
  447. // PasswordValidation defines the password validation rules
  448. PasswordValidation PasswordValidation `json:"password_validation" mapstructure:"password_validation"`
  449. // Verifying argon2 passwords has a high memory and computational cost,
  450. // by enabling, in memory, password caching you reduce this cost.
  451. PasswordCaching bool `json:"password_caching" mapstructure:"password_caching"`
  452. // DelayedQuotaUpdate defines the number of seconds to accumulate quota updates.
  453. // If there are a lot of close uploads, accumulating quota updates can save you many
  454. // queries to the data provider.
  455. // If you want to track quotas, a scheduled quota update is recommended in any case, the stored
  456. // quota size may be incorrect for several reasons, such as an unexpected shutdown, temporary provider
  457. // failures, file copied outside of SFTPGo, and so on.
  458. // 0 means immediate quota update.
  459. DelayedQuotaUpdate int `json:"delayed_quota_update" mapstructure:"delayed_quota_update"`
  460. // If enabled, a default admin user with username "admin" and password "password" will be created
  461. // on first start.
  462. // You can also create the first admin user by using the web interface or by loading initial data.
  463. CreateDefaultAdmin bool `json:"create_default_admin" mapstructure:"create_default_admin"`
  464. // Rules for usernames and folder names:
  465. // - 0 means no rules
  466. // - 1 means you can use any UTF-8 character. The names are used in URIs for REST API and Web admin.
  467. // By default only unreserved URI characters are allowed: ALPHA / DIGIT / "-" / "." / "_" / "~".
  468. // - 2 means names are converted to lowercase before saving/matching and so case
  469. // insensitive matching is possible
  470. // - 4 means trimming trailing and leading white spaces before saving/matching
  471. // Rules can be combined, for example 3 means both converting to lowercase and allowing any UTF-8 character.
  472. // Enabling these options for existing installations could be backward incompatible, some users
  473. // could be unable to login, for example existing users with mixed cases in their usernames.
  474. // You have to ensure that all existing users respect the defined rules.
  475. NamingRules int `json:"naming_rules" mapstructure:"naming_rules"`
  476. // If the data provider is shared across multiple SFTPGo instances, set this parameter to 1.
  477. // MySQL, PostgreSQL and CockroachDB can be shared, this setting is ignored for other data
  478. // providers. For shared data providers, SFTPGo periodically reloads the latest updated users,
  479. // based on the "updated_at" field, and updates its internal caches if users are updated from
  480. // a different instance. This check, if enabled, is executed every 10 minutes.
  481. // For shared data providers, active transfers are persisted in the database and thus
  482. // quota checks between ongoing transfers will work cross multiple instances
  483. IsShared int `json:"is_shared" mapstructure:"is_shared"`
  484. // Node defines the configuration for this cluster node.
  485. // Ignored if the provider is not shared/shareable
  486. Node NodeConfig `json:"node" mapstructure:"node"`
  487. // Path to the backup directory. This can be an absolute path or a path relative to the config dir
  488. BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
  489. }
  490. // GetShared returns the provider share mode.
  491. // This method is called before the provider is initialized
  492. func (c *Config) GetShared() int {
  493. if !util.Contains(sharedProviders, c.Driver) {
  494. return 0
  495. }
  496. return c.IsShared
  497. }
  498. func (c *Config) convertName(name string) string {
  499. if c.NamingRules <= 1 {
  500. return name
  501. }
  502. if c.NamingRules&2 != 0 {
  503. name = strings.ToLower(name)
  504. }
  505. if c.NamingRules&4 != 0 {
  506. name = strings.TrimSpace(name)
  507. }
  508. return name
  509. }
  510. // IsDefenderSupported returns true if the configured provider supports the defender
  511. func (c *Config) IsDefenderSupported() bool {
  512. switch c.Driver {
  513. case MySQLDataProviderName, PGSQLDataProviderName, CockroachDataProviderName:
  514. return true
  515. default:
  516. return false
  517. }
  518. }
  519. func (c *Config) requireCustomTLSForMySQL() bool {
  520. if config.DisableSNI {
  521. return config.SSLMode != 0
  522. }
  523. if config.RootCert != "" && util.IsFileInputValid(config.RootCert) {
  524. return config.SSLMode != 0
  525. }
  526. if config.ClientCert != "" && config.ClientKey != "" && util.IsFileInputValid(config.ClientCert) &&
  527. util.IsFileInputValid(config.ClientKey) {
  528. return config.SSLMode != 0
  529. }
  530. return false
  531. }
  532. func (c *Config) doBackup() (string, error) {
  533. now := time.Now().UTC()
  534. outputFile := filepath.Join(c.BackupsPath, fmt.Sprintf("backup_%s_%d.json", now.Weekday(), now.Hour()))
  535. providerLog(logger.LevelDebug, "starting backup to file %q", outputFile)
  536. err := os.MkdirAll(filepath.Dir(outputFile), 0700)
  537. if err != nil {
  538. providerLog(logger.LevelError, "unable to create backup dir %q: %v", outputFile, err)
  539. return outputFile, fmt.Errorf("unable to create backup dir: %w", err)
  540. }
  541. backup, err := DumpData(nil)
  542. if err != nil {
  543. providerLog(logger.LevelError, "unable to execute backup: %v", err)
  544. return outputFile, fmt.Errorf("unable to dump backup data: %w", err)
  545. }
  546. dump, err := json.Marshal(backup)
  547. if err != nil {
  548. providerLog(logger.LevelError, "unable to marshal backup as JSON: %v", err)
  549. return outputFile, fmt.Errorf("unable to marshal backup data as JSON: %w", err)
  550. }
  551. err = os.WriteFile(outputFile, dump, 0600)
  552. if err != nil {
  553. providerLog(logger.LevelError, "unable to save backup: %v", err)
  554. return outputFile, fmt.Errorf("unable to save backup: %w", err)
  555. }
  556. providerLog(logger.LevelDebug, "backup saved to %q", outputFile)
  557. return outputFile, nil
  558. }
  559. // SetTZ sets the configured timezone.
  560. func SetTZ(val string) {
  561. tz = val
  562. }
  563. // UseLocalTime returns true if local time should be used instead of UTC.
  564. func UseLocalTime() bool {
  565. return tz == "local"
  566. }
  567. // ExecuteBackup executes a backup
  568. func ExecuteBackup() (string, error) {
  569. return config.doBackup()
  570. }
  571. // ConvertName converts the given name based on the configured rules
  572. func ConvertName(name string) string {
  573. return config.convertName(name)
  574. }
  575. // ActiveTransfer defines an active protocol transfer
  576. type ActiveTransfer struct {
  577. ID int64
  578. Type int
  579. ConnID string
  580. Username string
  581. FolderName string
  582. IP string
  583. TruncatedSize int64
  584. CurrentULSize int64
  585. CurrentDLSize int64
  586. CreatedAt int64
  587. UpdatedAt int64
  588. }
  589. // TransferQuota stores the allowed transfer quota fields
  590. type TransferQuota struct {
  591. ULSize int64
  592. DLSize int64
  593. TotalSize int64
  594. AllowedULSize int64
  595. AllowedDLSize int64
  596. AllowedTotalSize int64
  597. }
  598. // HasSizeLimits returns true if any size limit is set
  599. func (q *TransferQuota) HasSizeLimits() bool {
  600. return q.AllowedDLSize > 0 || q.AllowedULSize > 0 || q.AllowedTotalSize > 0
  601. }
  602. // HasUploadSpace returns true if there is transfer upload space available
  603. func (q *TransferQuota) HasUploadSpace() bool {
  604. if q.TotalSize <= 0 && q.ULSize <= 0 {
  605. return true
  606. }
  607. if q.TotalSize > 0 {
  608. return q.AllowedTotalSize > 0
  609. }
  610. return q.AllowedULSize > 0
  611. }
  612. // HasDownloadSpace returns true if there is transfer download space available
  613. func (q *TransferQuota) HasDownloadSpace() bool {
  614. if q.TotalSize <= 0 && q.DLSize <= 0 {
  615. return true
  616. }
  617. if q.TotalSize > 0 {
  618. return q.AllowedTotalSize > 0
  619. }
  620. return q.AllowedDLSize > 0
  621. }
  622. // DefenderEntry defines a defender entry
  623. type DefenderEntry struct {
  624. ID int64 `json:"-"`
  625. IP string `json:"ip"`
  626. Score int `json:"score,omitempty"`
  627. BanTime time.Time `json:"ban_time,omitempty"`
  628. }
  629. // GetID returns an unique ID for a defender entry
  630. func (d *DefenderEntry) GetID() string {
  631. return hex.EncodeToString([]byte(d.IP))
  632. }
  633. // GetBanTime returns the ban time for a defender entry as string
  634. func (d *DefenderEntry) GetBanTime() string {
  635. if d.BanTime.IsZero() {
  636. return ""
  637. }
  638. return d.BanTime.UTC().Format(time.RFC3339)
  639. }
  640. // MarshalJSON returns the JSON encoding of a DefenderEntry.
  641. func (d *DefenderEntry) MarshalJSON() ([]byte, error) {
  642. return json.Marshal(&struct {
  643. ID string `json:"id"`
  644. IP string `json:"ip"`
  645. Score int `json:"score,omitempty"`
  646. BanTime string `json:"ban_time,omitempty"`
  647. }{
  648. ID: d.GetID(),
  649. IP: d.IP,
  650. Score: d.Score,
  651. BanTime: d.GetBanTime(),
  652. })
  653. }
  654. // BackupData defines the structure for the backup/restore files
  655. type BackupData struct {
  656. Users []User `json:"users"`
  657. Groups []Group `json:"groups"`
  658. Folders []vfs.BaseVirtualFolder `json:"folders"`
  659. Admins []Admin `json:"admins"`
  660. APIKeys []APIKey `json:"api_keys"`
  661. Shares []Share `json:"shares"`
  662. EventActions []BaseEventAction `json:"event_actions"`
  663. EventRules []EventRule `json:"event_rules"`
  664. Roles []Role `json:"roles"`
  665. IPLists []IPListEntry `json:"ip_lists"`
  666. Configs *Configs `json:"configs"`
  667. Version int `json:"version"`
  668. }
  669. // HasFolder returns true if the folder with the given name is included
  670. func (d *BackupData) HasFolder(name string) bool {
  671. for _, folder := range d.Folders {
  672. if folder.Name == name {
  673. return true
  674. }
  675. }
  676. return false
  677. }
  678. type checkPasswordRequest struct {
  679. Username string `json:"username"`
  680. IP string `json:"ip"`
  681. Password string `json:"password"`
  682. Protocol string `json:"protocol"`
  683. }
  684. type checkPasswordResponse struct {
  685. // 0 KO, 1 OK, 2 partial success, -1 not executed
  686. Status int `json:"status"`
  687. // for status = 2 this is the password to check against the one stored
  688. // inside the SFTPGo data provider
  689. ToVerify string `json:"to_verify"`
  690. }
  691. // GetQuotaTracking returns the configured mode for user's quota tracking
  692. func GetQuotaTracking() int {
  693. return config.TrackQuota
  694. }
  695. // HasUsersBaseDir returns true if users base dir is set
  696. func HasUsersBaseDir() bool {
  697. return config.UsersBaseDir != ""
  698. }
  699. // Provider defines the interface that data providers must implement.
  700. type Provider interface {
  701. validateUserAndPass(username, password, ip, protocol string) (User, error)
  702. validateUserAndPubKey(username string, pubKey []byte, isSSHCert bool) (User, string, error)
  703. validateUserAndTLSCert(username, protocol string, tlsCert *x509.Certificate) (User, error)
  704. updateQuota(username string, filesAdd int, sizeAdd int64, reset bool) error
  705. updateTransferQuota(username string, uploadSize, downloadSize int64, reset bool) error
  706. getUsedQuota(username string) (int, int64, int64, int64, error)
  707. userExists(username, role string) (User, error)
  708. addUser(user *User) error
  709. updateUser(user *User) error
  710. deleteUser(user User, softDelete bool) error
  711. updateUserPassword(username, password string) error // used internally when converting passwords from other hash
  712. getUsers(limit int, offset int, order, role string) ([]User, error)
  713. dumpUsers() ([]User, error)
  714. getRecentlyUpdatedUsers(after int64) ([]User, error)
  715. getUsersForQuotaCheck(toFetch map[string]bool) ([]User, error)
  716. updateLastLogin(username string) error
  717. updateAdminLastLogin(username string) error
  718. setUpdatedAt(username string)
  719. getFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error)
  720. getFolderByName(name string) (vfs.BaseVirtualFolder, error)
  721. addFolder(folder *vfs.BaseVirtualFolder) error
  722. updateFolder(folder *vfs.BaseVirtualFolder) error
  723. deleteFolder(folder vfs.BaseVirtualFolder) error
  724. updateFolderQuota(name string, filesAdd int, sizeAdd int64, reset bool) error
  725. getUsedFolderQuota(name string) (int, int64, error)
  726. dumpFolders() ([]vfs.BaseVirtualFolder, error)
  727. getGroups(limit, offset int, order string, minimal bool) ([]Group, error)
  728. getGroupsWithNames(names []string) ([]Group, error)
  729. getUsersInGroups(names []string) ([]string, error)
  730. groupExists(name string) (Group, error)
  731. addGroup(group *Group) error
  732. updateGroup(group *Group) error
  733. deleteGroup(group Group) error
  734. dumpGroups() ([]Group, error)
  735. adminExists(username string) (Admin, error)
  736. addAdmin(admin *Admin) error
  737. updateAdmin(admin *Admin) error
  738. deleteAdmin(admin Admin) error
  739. getAdmins(limit int, offset int, order string) ([]Admin, error)
  740. dumpAdmins() ([]Admin, error)
  741. validateAdminAndPass(username, password, ip string) (Admin, error)
  742. apiKeyExists(keyID string) (APIKey, error)
  743. addAPIKey(apiKey *APIKey) error
  744. updateAPIKey(apiKey *APIKey) error
  745. deleteAPIKey(apiKey APIKey) error
  746. getAPIKeys(limit int, offset int, order string) ([]APIKey, error)
  747. dumpAPIKeys() ([]APIKey, error)
  748. updateAPIKeyLastUse(keyID string) error
  749. shareExists(shareID, username string) (Share, error)
  750. addShare(share *Share) error
  751. updateShare(share *Share) error
  752. deleteShare(share Share) error
  753. getShares(limit int, offset int, order, username string) ([]Share, error)
  754. dumpShares() ([]Share, error)
  755. updateShareLastUse(shareID string, numTokens int) error
  756. getDefenderHosts(from int64, limit int) ([]DefenderEntry, error)
  757. getDefenderHostByIP(ip string, from int64) (DefenderEntry, error)
  758. isDefenderHostBanned(ip string) (DefenderEntry, error)
  759. updateDefenderBanTime(ip string, minutes int) error
  760. deleteDefenderHost(ip string) error
  761. addDefenderEvent(ip string, score int) error
  762. setDefenderBanTime(ip string, banTime int64) error
  763. cleanupDefender(from int64) error
  764. addActiveTransfer(transfer ActiveTransfer) error
  765. updateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string) error
  766. removeActiveTransfer(transferID int64, connectionID string) error
  767. cleanupActiveTransfers(before time.Time) error
  768. getActiveTransfers(from time.Time) ([]ActiveTransfer, error)
  769. addSharedSession(session Session) error
  770. deleteSharedSession(key string) error
  771. getSharedSession(key string) (Session, error)
  772. cleanupSharedSessions(sessionType SessionType, before int64) error
  773. getEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error)
  774. dumpEventActions() ([]BaseEventAction, error)
  775. eventActionExists(name string) (BaseEventAction, error)
  776. addEventAction(action *BaseEventAction) error
  777. updateEventAction(action *BaseEventAction) error
  778. deleteEventAction(action BaseEventAction) error
  779. getEventRules(limit, offset int, order string) ([]EventRule, error)
  780. dumpEventRules() ([]EventRule, error)
  781. getRecentlyUpdatedRules(after int64) ([]EventRule, error)
  782. eventRuleExists(name string) (EventRule, error)
  783. addEventRule(rule *EventRule) error
  784. updateEventRule(rule *EventRule) error
  785. deleteEventRule(rule EventRule, softDelete bool) error
  786. getTaskByName(name string) (Task, error)
  787. addTask(name string) error
  788. updateTask(name string, version int64) error
  789. updateTaskTimestamp(name string) error
  790. setFirstDownloadTimestamp(username string) error
  791. setFirstUploadTimestamp(username string) error
  792. addNode() error
  793. getNodeByName(name string) (Node, error)
  794. getNodes() ([]Node, error)
  795. updateNodeTimestamp() error
  796. cleanupNodes() error
  797. roleExists(name string) (Role, error)
  798. addRole(role *Role) error
  799. updateRole(role *Role) error
  800. deleteRole(role Role) error
  801. getRoles(limit int, offset int, order string, minimal bool) ([]Role, error)
  802. dumpRoles() ([]Role, error)
  803. ipListEntryExists(ipOrNet string, listType IPListType) (IPListEntry, error)
  804. addIPListEntry(entry *IPListEntry) error
  805. updateIPListEntry(entry *IPListEntry) error
  806. deleteIPListEntry(entry IPListEntry, softDelete bool) error
  807. getIPListEntries(listType IPListType, filter, from, order string, limit int) ([]IPListEntry, error)
  808. getRecentlyUpdatedIPListEntries(after int64) ([]IPListEntry, error)
  809. dumpIPListEntries() ([]IPListEntry, error)
  810. countIPListEntries(listType IPListType) (int64, error)
  811. getListEntriesForIP(ip string, listType IPListType) ([]IPListEntry, error)
  812. getConfigs() (Configs, error)
  813. setConfigs(configs *Configs) error
  814. checkAvailability() error
  815. close() error
  816. reloadConfig() error
  817. initializeDatabase() error
  818. migrateDatabase() error
  819. revertDatabase(targetVersion int) error
  820. resetDatabase() error
  821. }
  822. // SetAllowSelfConnections sets the desired behaviour for self connections
  823. func SetAllowSelfConnections(value int) {
  824. allowSelfConnections = value
  825. }
  826. // SetTempPath sets the path for temporary files
  827. func SetTempPath(fsPath string) {
  828. tempPath = fsPath
  829. }
  830. func checkSharedMode() {
  831. if !util.Contains(sharedProviders, config.Driver) {
  832. config.IsShared = 0
  833. }
  834. }
  835. // Initialize the data provider.
  836. // An error is returned if the configured driver is invalid or if the data provider cannot be initialized
  837. func Initialize(cnf Config, basePath string, checkAdmins bool) error {
  838. config = cnf
  839. checkSharedMode()
  840. config.Actions.ExecuteOn = util.RemoveDuplicates(config.Actions.ExecuteOn, true)
  841. config.Actions.ExecuteFor = util.RemoveDuplicates(config.Actions.ExecuteFor, true)
  842. cnf.BackupsPath = getConfigPath(cnf.BackupsPath, basePath)
  843. if cnf.BackupsPath == "" {
  844. return fmt.Errorf("required directory is invalid, backup path %q", cnf.BackupsPath)
  845. }
  846. absoluteBackupPath, err := util.GetAbsolutePath(cnf.BackupsPath)
  847. if err != nil {
  848. return fmt.Errorf("unable to get absolute backup path: %w", err)
  849. }
  850. config.BackupsPath = absoluteBackupPath
  851. if err := initializeHashingAlgo(&cnf); err != nil {
  852. return err
  853. }
  854. if err := validateHooks(); err != nil {
  855. return err
  856. }
  857. if err := createProvider(basePath); err != nil {
  858. return err
  859. }
  860. if err := checkDatabase(checkAdmins); err != nil {
  861. return err
  862. }
  863. admins, err := provider.getAdmins(1, 0, OrderASC)
  864. if err != nil {
  865. return err
  866. }
  867. isAdminCreated.Store(len(admins) > 0)
  868. if err := config.Node.validate(); err != nil {
  869. return err
  870. }
  871. delayedQuotaUpdater.start()
  872. if currentNode != nil {
  873. config.BackupsPath = filepath.Join(config.BackupsPath, currentNode.Name)
  874. }
  875. providerLog(logger.LevelDebug, "absolute backup path %q", config.BackupsPath)
  876. return startScheduler()
  877. }
  878. func checkDatabase(checkAdmins bool) error {
  879. if config.UpdateMode == 0 {
  880. err := provider.initializeDatabase()
  881. if err != nil && err != ErrNoInitRequired {
  882. logger.WarnToConsole("unable to initialize data provider: %v", err)
  883. providerLog(logger.LevelError, "unable to initialize data provider: %v", err)
  884. return err
  885. }
  886. if err == nil {
  887. logger.DebugToConsole("data provider successfully initialized")
  888. providerLog(logger.LevelInfo, "data provider successfully initialized")
  889. }
  890. err = provider.migrateDatabase()
  891. if err != nil && err != ErrNoInitRequired {
  892. providerLog(logger.LevelError, "database migration error: %v", err)
  893. return err
  894. }
  895. if checkAdmins && config.CreateDefaultAdmin {
  896. err = checkDefaultAdmin()
  897. if err != nil {
  898. providerLog(logger.LevelError, "erro checking the default admin: %v", err)
  899. return err
  900. }
  901. }
  902. } else {
  903. providerLog(logger.LevelInfo, "database initialization/migration skipped, manual mode is configured")
  904. }
  905. return nil
  906. }
  907. func validateHooks() error {
  908. var hooks []string
  909. if config.PreLoginHook != "" && !strings.HasPrefix(config.PreLoginHook, "http") {
  910. hooks = append(hooks, config.PreLoginHook)
  911. }
  912. if config.ExternalAuthHook != "" && !strings.HasPrefix(config.ExternalAuthHook, "http") {
  913. hooks = append(hooks, config.ExternalAuthHook)
  914. }
  915. if config.PostLoginHook != "" && !strings.HasPrefix(config.PostLoginHook, "http") {
  916. hooks = append(hooks, config.PostLoginHook)
  917. }
  918. if config.CheckPasswordHook != "" && !strings.HasPrefix(config.CheckPasswordHook, "http") {
  919. hooks = append(hooks, config.CheckPasswordHook)
  920. }
  921. for _, hook := range hooks {
  922. if !filepath.IsAbs(hook) {
  923. return fmt.Errorf("invalid hook: %q must be an absolute path", hook)
  924. }
  925. _, err := os.Stat(hook)
  926. if err != nil {
  927. providerLog(logger.LevelError, "invalid hook: %v", err)
  928. return err
  929. }
  930. }
  931. return nil
  932. }
  933. // GetBackupsPath returns the normalized backups path
  934. func GetBackupsPath() string {
  935. return config.BackupsPath
  936. }
  937. // GetProviderFromValue returns the FilesystemProvider matching the specified value.
  938. // If no match is found LocalFilesystemProvider is returned.
  939. func GetProviderFromValue(value string) sdk.FilesystemProvider {
  940. val, err := strconv.Atoi(value)
  941. if err != nil {
  942. return sdk.LocalFilesystemProvider
  943. }
  944. result := sdk.FilesystemProvider(val)
  945. if sdk.IsProviderSupported(result) {
  946. return result
  947. }
  948. return sdk.LocalFilesystemProvider
  949. }
  950. func initializeHashingAlgo(cnf *Config) error {
  951. parallelism := cnf.PasswordHashing.Argon2Options.Parallelism
  952. if parallelism == 0 {
  953. parallelism = uint8(runtime.NumCPU())
  954. }
  955. argon2Params = &argon2id.Params{
  956. Memory: cnf.PasswordHashing.Argon2Options.Memory,
  957. Iterations: cnf.PasswordHashing.Argon2Options.Iterations,
  958. Parallelism: parallelism,
  959. SaltLength: 16,
  960. KeyLength: 32,
  961. }
  962. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  963. if config.PasswordHashing.BcryptOptions.Cost > bcrypt.MaxCost {
  964. err := fmt.Errorf("invalid bcrypt cost %v, max allowed %v", config.PasswordHashing.BcryptOptions.Cost, bcrypt.MaxCost)
  965. logger.WarnToConsole("Unable to initialize data provider: %v", err)
  966. providerLog(logger.LevelError, "Unable to initialize data provider: %v", err)
  967. return err
  968. }
  969. }
  970. return nil
  971. }
  972. func validateSQLTablesPrefix() error {
  973. initSQLTables()
  974. if config.SQLTablesPrefix != "" {
  975. for _, char := range config.SQLTablesPrefix {
  976. if !strings.Contains(sqlPrefixValidChars, strings.ToLower(string(char))) {
  977. return errors.New("invalid sql_tables_prefix only chars in range 'a..z', 'A..Z', '0-9' and '_' are allowed")
  978. }
  979. }
  980. sqlTableUsers = config.SQLTablesPrefix + sqlTableUsers
  981. sqlTableFolders = config.SQLTablesPrefix + sqlTableFolders
  982. sqlTableUsersFoldersMapping = config.SQLTablesPrefix + sqlTableUsersFoldersMapping
  983. sqlTableAdmins = config.SQLTablesPrefix + sqlTableAdmins
  984. sqlTableAPIKeys = config.SQLTablesPrefix + sqlTableAPIKeys
  985. sqlTableShares = config.SQLTablesPrefix + sqlTableShares
  986. sqlTableDefenderEvents = config.SQLTablesPrefix + sqlTableDefenderEvents
  987. sqlTableDefenderHosts = config.SQLTablesPrefix + sqlTableDefenderHosts
  988. sqlTableActiveTransfers = config.SQLTablesPrefix + sqlTableActiveTransfers
  989. sqlTableGroups = config.SQLTablesPrefix + sqlTableGroups
  990. sqlTableUsersGroupsMapping = config.SQLTablesPrefix + sqlTableUsersGroupsMapping
  991. sqlTableAdminsGroupsMapping = config.SQLTablesPrefix + sqlTableAdminsGroupsMapping
  992. sqlTableGroupsFoldersMapping = config.SQLTablesPrefix + sqlTableGroupsFoldersMapping
  993. sqlTableSharedSessions = config.SQLTablesPrefix + sqlTableSharedSessions
  994. sqlTableEventsActions = config.SQLTablesPrefix + sqlTableEventsActions
  995. sqlTableEventsRules = config.SQLTablesPrefix + sqlTableEventsRules
  996. sqlTableRulesActionsMapping = config.SQLTablesPrefix + sqlTableRulesActionsMapping
  997. sqlTableTasks = config.SQLTablesPrefix + sqlTableTasks
  998. sqlTableNodes = config.SQLTablesPrefix + sqlTableNodes
  999. sqlTableRoles = config.SQLTablesPrefix + sqlTableRoles
  1000. sqlTableIPLists = config.SQLTablesPrefix + sqlTableIPLists
  1001. sqlTableConfigs = config.SQLTablesPrefix + sqlTableConfigs
  1002. sqlTableSchemaVersion = config.SQLTablesPrefix + sqlTableSchemaVersion
  1003. providerLog(logger.LevelDebug, "sql table for users %q, folders %q users folders mapping %q admins %q "+
  1004. "api keys %q shares %q defender hosts %q defender events %q transfers %q groups %q "+
  1005. "users groups mapping %q admins groups mapping %q groups folders mapping %q shared sessions %q "+
  1006. "schema version %q events actions %q events rules %q rules actions mapping %q tasks %q nodes %q roles %q"+
  1007. "ip lists %q configs %q",
  1008. sqlTableUsers, sqlTableFolders, sqlTableUsersFoldersMapping, sqlTableAdmins, sqlTableAPIKeys,
  1009. sqlTableShares, sqlTableDefenderHosts, sqlTableDefenderEvents, sqlTableActiveTransfers, sqlTableGroups,
  1010. sqlTableUsersGroupsMapping, sqlTableAdminsGroupsMapping, sqlTableGroupsFoldersMapping, sqlTableSharedSessions,
  1011. sqlTableSchemaVersion, sqlTableEventsActions, sqlTableEventsRules, sqlTableRulesActionsMapping,
  1012. sqlTableTasks, sqlTableNodes, sqlTableRoles, sqlTableIPLists, sqlTableConfigs)
  1013. }
  1014. return nil
  1015. }
  1016. func checkDefaultAdmin() error {
  1017. admins, err := provider.getAdmins(1, 0, OrderASC)
  1018. if err != nil {
  1019. return err
  1020. }
  1021. if len(admins) > 0 {
  1022. return nil
  1023. }
  1024. logger.Debug(logSender, "", "no admins found, try to create the default one")
  1025. // we need to create the default admin
  1026. admin := &Admin{}
  1027. if err := admin.setFromEnv(); err != nil {
  1028. return err
  1029. }
  1030. return provider.addAdmin(admin)
  1031. }
  1032. // InitializeDatabase creates the initial database structure
  1033. func InitializeDatabase(cnf Config, basePath string) error {
  1034. config = cnf
  1035. if err := initializeHashingAlgo(&cnf); err != nil {
  1036. return err
  1037. }
  1038. err := createProvider(basePath)
  1039. if err != nil {
  1040. return err
  1041. }
  1042. err = provider.initializeDatabase()
  1043. if err != nil && err != ErrNoInitRequired {
  1044. return err
  1045. }
  1046. return provider.migrateDatabase()
  1047. }
  1048. // RevertDatabase restores schema and/or data to a previous version
  1049. func RevertDatabase(cnf Config, basePath string, targetVersion int) error {
  1050. config = cnf
  1051. err := createProvider(basePath)
  1052. if err != nil {
  1053. return err
  1054. }
  1055. err = provider.initializeDatabase()
  1056. if err != nil && err != ErrNoInitRequired {
  1057. return err
  1058. }
  1059. return provider.revertDatabase(targetVersion)
  1060. }
  1061. // ResetDatabase restores schema and/or data to a previous version
  1062. func ResetDatabase(cnf Config, basePath string) error {
  1063. config = cnf
  1064. if err := createProvider(basePath); err != nil {
  1065. return err
  1066. }
  1067. return provider.resetDatabase()
  1068. }
  1069. // CheckAdminAndPass validates the given admin and password connecting from ip
  1070. func CheckAdminAndPass(username, password, ip string) (Admin, error) {
  1071. username = config.convertName(username)
  1072. return provider.validateAdminAndPass(username, password, ip)
  1073. }
  1074. // CheckCachedUserCredentials checks the credentials for a cached user
  1075. func CheckCachedUserCredentials(user *CachedUser, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (*CachedUser, *User, error) {
  1076. if !user.User.skipExternalAuth() && isExternalAuthConfigured(loginMethod) {
  1077. u, _, err := CheckCompositeCredentials(user.User.Username, password, ip, loginMethod, protocol, tlsCert)
  1078. if err != nil {
  1079. return nil, nil, err
  1080. }
  1081. webDAVUsersCache.swap(&u, password)
  1082. cu, _ := webDAVUsersCache.get(u.Username)
  1083. return cu, &u, nil
  1084. }
  1085. if err := user.User.CheckLoginConditions(); err != nil {
  1086. return user, nil, err
  1087. }
  1088. if loginMethod == LoginMethodPassword && user.User.Filters.IsAnonymous {
  1089. return user, nil, nil
  1090. }
  1091. if loginMethod != LoginMethodPassword {
  1092. _, err := checkUserAndTLSCertificate(&user.User, protocol, tlsCert)
  1093. if err != nil {
  1094. return user, nil, err
  1095. }
  1096. if loginMethod == LoginMethodTLSCertificate {
  1097. if !user.User.IsLoginMethodAllowed(LoginMethodTLSCertificate, protocol) {
  1098. return user, nil, fmt.Errorf("certificate login method is not allowed for user %q", user.User.Username)
  1099. }
  1100. return user, nil, nil
  1101. }
  1102. }
  1103. if password == "" {
  1104. return user, nil, ErrInvalidCredentials
  1105. }
  1106. if user.Password != "" {
  1107. if password == user.Password {
  1108. return user, nil, nil
  1109. }
  1110. } else {
  1111. if ok, _ := isPasswordOK(&user.User, password); ok {
  1112. return user, nil, nil
  1113. }
  1114. }
  1115. return user, nil, ErrInvalidCredentials
  1116. }
  1117. // CheckCompositeCredentials checks multiple credentials.
  1118. // WebDAV users can send both a password and a TLS certificate within the same request
  1119. func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (User, string, error) {
  1120. username = config.convertName(username)
  1121. if loginMethod == LoginMethodPassword {
  1122. user, err := CheckUserAndPass(username, password, ip, protocol)
  1123. return user, loginMethod, err
  1124. }
  1125. user, err := CheckUserBeforeTLSAuth(username, ip, protocol, tlsCert)
  1126. if err != nil {
  1127. return user, loginMethod, err
  1128. }
  1129. if !user.IsTLSVerificationEnabled() {
  1130. // for backward compatibility with 2.0.x we only check the password and change the login method here
  1131. // in future updates we have to return an error
  1132. user, err := CheckUserAndPass(username, password, ip, protocol)
  1133. return user, LoginMethodPassword, err
  1134. }
  1135. user, err = checkUserAndTLSCertificate(&user, protocol, tlsCert)
  1136. if err != nil {
  1137. return user, loginMethod, err
  1138. }
  1139. if loginMethod == LoginMethodTLSCertificate && !user.IsLoginMethodAllowed(LoginMethodTLSCertificate, protocol) {
  1140. return user, loginMethod, fmt.Errorf("certificate login method is not allowed for user %q", user.Username)
  1141. }
  1142. if loginMethod == LoginMethodTLSCertificateAndPwd {
  1143. if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
  1144. user, err = doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
  1145. } else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
  1146. user, err = doExternalAuth(username, password, nil, "", ip, protocol, nil)
  1147. } else if config.PreLoginHook != "" {
  1148. user, err = executePreLoginHook(username, LoginMethodPassword, ip, protocol, nil)
  1149. }
  1150. if err != nil {
  1151. return user, loginMethod, err
  1152. }
  1153. user, err = checkUserAndPass(&user, password, ip, protocol)
  1154. }
  1155. return user, loginMethod, err
  1156. }
  1157. // CheckUserBeforeTLSAuth checks if a user exits before trying mutual TLS
  1158. func CheckUserBeforeTLSAuth(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
  1159. username = config.convertName(username)
  1160. if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
  1161. user, err := doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
  1162. if err != nil {
  1163. return user, err
  1164. }
  1165. err = user.LoadAndApplyGroupSettings()
  1166. return user, err
  1167. }
  1168. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
  1169. user, err := doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
  1170. if err != nil {
  1171. return user, err
  1172. }
  1173. err = user.LoadAndApplyGroupSettings()
  1174. return user, err
  1175. }
  1176. if config.PreLoginHook != "" {
  1177. user, err := executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol, nil)
  1178. if err != nil {
  1179. return user, err
  1180. }
  1181. err = user.LoadAndApplyGroupSettings()
  1182. return user, err
  1183. }
  1184. user, err := UserExists(username, "")
  1185. if err != nil {
  1186. return user, err
  1187. }
  1188. err = user.LoadAndApplyGroupSettings()
  1189. return user, err
  1190. }
  1191. // CheckUserAndTLSCert returns the SFTPGo user with the given username and check if the
  1192. // given TLS certificate allow authentication without password
  1193. func CheckUserAndTLSCert(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
  1194. username = config.convertName(username)
  1195. if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
  1196. user, err := doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
  1197. if err != nil {
  1198. return user, err
  1199. }
  1200. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  1201. }
  1202. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
  1203. user, err := doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
  1204. if err != nil {
  1205. return user, err
  1206. }
  1207. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  1208. }
  1209. if config.PreLoginHook != "" {
  1210. user, err := executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol, nil)
  1211. if err != nil {
  1212. return user, err
  1213. }
  1214. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  1215. }
  1216. return provider.validateUserAndTLSCert(username, protocol, tlsCert)
  1217. }
  1218. // CheckUserAndPass retrieves the SFTPGo user with the given username and password if a match is found or an error
  1219. func CheckUserAndPass(username, password, ip, protocol string) (User, error) {
  1220. username = config.convertName(username)
  1221. if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
  1222. user, err := doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
  1223. if err != nil {
  1224. return user, err
  1225. }
  1226. return checkUserAndPass(&user, password, ip, protocol)
  1227. }
  1228. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
  1229. user, err := doExternalAuth(username, password, nil, "", ip, protocol, nil)
  1230. if err != nil {
  1231. return user, err
  1232. }
  1233. return checkUserAndPass(&user, password, ip, protocol)
  1234. }
  1235. if config.PreLoginHook != "" {
  1236. user, err := executePreLoginHook(username, LoginMethodPassword, ip, protocol, nil)
  1237. if err != nil {
  1238. return user, err
  1239. }
  1240. return checkUserAndPass(&user, password, ip, protocol)
  1241. }
  1242. return provider.validateUserAndPass(username, password, ip, protocol)
  1243. }
  1244. // CheckUserAndPubKey retrieves the SFTP user with the given username and public key if a match is found or an error
  1245. func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string, isSSHCert bool) (User, string, error) {
  1246. username = config.convertName(username)
  1247. if plugin.Handler.HasAuthScope(plugin.AuthScopePublicKey) {
  1248. user, err := doPluginAuth(username, "", pubKey, ip, protocol, nil, plugin.AuthScopePublicKey)
  1249. if err != nil {
  1250. return user, "", err
  1251. }
  1252. return checkUserAndPubKey(&user, pubKey, isSSHCert)
  1253. }
  1254. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&2 != 0) {
  1255. user, err := doExternalAuth(username, "", pubKey, "", ip, protocol, nil)
  1256. if err != nil {
  1257. return user, "", err
  1258. }
  1259. return checkUserAndPubKey(&user, pubKey, isSSHCert)
  1260. }
  1261. if config.PreLoginHook != "" {
  1262. user, err := executePreLoginHook(username, SSHLoginMethodPublicKey, ip, protocol, nil)
  1263. if err != nil {
  1264. return user, "", err
  1265. }
  1266. return checkUserAndPubKey(&user, pubKey, isSSHCert)
  1267. }
  1268. return provider.validateUserAndPubKey(username, pubKey, isSSHCert)
  1269. }
  1270. // CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns
  1271. // the authenticated user or an error
  1272. func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge,
  1273. ip, protocol string, isPartialAuth bool,
  1274. ) (User, error) {
  1275. var user User
  1276. var err error
  1277. username = config.convertName(username)
  1278. if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
  1279. user, err = doPluginAuth(username, "", nil, ip, protocol, nil, plugin.AuthScopeKeyboardInteractive)
  1280. } else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&4 != 0) {
  1281. user, err = doExternalAuth(username, "", nil, "1", ip, protocol, nil)
  1282. } else if config.PreLoginHook != "" {
  1283. user, err = executePreLoginHook(username, SSHLoginMethodKeyboardInteractive, ip, protocol, nil)
  1284. } else {
  1285. user, err = provider.userExists(username, "")
  1286. }
  1287. if err != nil {
  1288. return user, err
  1289. }
  1290. return doKeyboardInteractiveAuth(&user, authHook, client, ip, protocol, isPartialAuth)
  1291. }
  1292. // GetFTPPreAuthUser returns the SFTPGo user with the specified username
  1293. // after receiving the FTP "USER" command.
  1294. // If a pre-login hook is defined it will be executed so the SFTPGo user
  1295. // can be created if it does not exist
  1296. func GetFTPPreAuthUser(username, ip string) (User, error) {
  1297. var user User
  1298. var err error
  1299. if config.PreLoginHook != "" {
  1300. user, err = executePreLoginHook(username, "", ip, protocolFTP, nil)
  1301. } else {
  1302. user, err = UserExists(username, "")
  1303. }
  1304. if err != nil {
  1305. return user, err
  1306. }
  1307. err = user.LoadAndApplyGroupSettings()
  1308. return user, err
  1309. }
  1310. // GetUserAfterIDPAuth returns the SFTPGo user with the specified username
  1311. // after a successful authentication with an external identity provider.
  1312. // If a pre-login hook is defined it will be executed so the SFTPGo user
  1313. // can be created if it does not exist
  1314. func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error) {
  1315. var user User
  1316. var err error
  1317. if config.PreLoginHook != "" {
  1318. user, err = executePreLoginHook(username, LoginMethodIDP, ip, protocol, oidcTokenFields)
  1319. user.Filters.RequirePasswordChange = false
  1320. } else {
  1321. user, err = UserExists(username, "")
  1322. }
  1323. if err != nil {
  1324. return user, err
  1325. }
  1326. err = user.LoadAndApplyGroupSettings()
  1327. return user, err
  1328. }
  1329. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  1330. func GetDefenderHosts(from int64, limit int) ([]DefenderEntry, error) {
  1331. return provider.getDefenderHosts(from, limit)
  1332. }
  1333. // GetDefenderHostByIP returns a defender host by ip, if any
  1334. func GetDefenderHostByIP(ip string, from int64) (DefenderEntry, error) {
  1335. return provider.getDefenderHostByIP(ip, from)
  1336. }
  1337. // IsDefenderHostBanned returns a defender entry and no error if the specified host is banned
  1338. func IsDefenderHostBanned(ip string) (DefenderEntry, error) {
  1339. return provider.isDefenderHostBanned(ip)
  1340. }
  1341. // UpdateDefenderBanTime increments ban time for the specified ip
  1342. func UpdateDefenderBanTime(ip string, minutes int) error {
  1343. return provider.updateDefenderBanTime(ip, minutes)
  1344. }
  1345. // DeleteDefenderHost removes the specified IP from the defender lists
  1346. func DeleteDefenderHost(ip string) error {
  1347. return provider.deleteDefenderHost(ip)
  1348. }
  1349. // AddDefenderEvent adds an event for the given IP with the given score
  1350. // and returns the host with the updated score
  1351. func AddDefenderEvent(ip string, score int, from int64) (DefenderEntry, error) {
  1352. if err := provider.addDefenderEvent(ip, score); err != nil {
  1353. return DefenderEntry{}, err
  1354. }
  1355. return provider.getDefenderHostByIP(ip, from)
  1356. }
  1357. // SetDefenderBanTime sets the ban time for the specified IP
  1358. func SetDefenderBanTime(ip string, banTime int64) error {
  1359. return provider.setDefenderBanTime(ip, banTime)
  1360. }
  1361. // CleanupDefender removes events and hosts older than "from" from the data provider
  1362. func CleanupDefender(from int64) error {
  1363. return provider.cleanupDefender(from)
  1364. }
  1365. // UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share
  1366. func UpdateShareLastUse(share *Share, numTokens int) error {
  1367. return provider.updateShareLastUse(share.ShareID, numTokens)
  1368. }
  1369. // UpdateAPIKeyLastUse updates the LastUseAt field for the given API key
  1370. func UpdateAPIKeyLastUse(apiKey *APIKey) error {
  1371. lastUse := util.GetTimeFromMsecSinceEpoch(apiKey.LastUseAt)
  1372. diff := -time.Until(lastUse)
  1373. if diff < 0 || diff > lastLoginMinDelay {
  1374. return provider.updateAPIKeyLastUse(apiKey.KeyID)
  1375. }
  1376. return nil
  1377. }
  1378. // UpdateLastLogin updates the last login field for the given SFTPGo user
  1379. func UpdateLastLogin(user *User) {
  1380. delay := lastLoginMinDelay
  1381. if user.Filters.ExternalAuthCacheTime > 0 {
  1382. delay = time.Duration(user.Filters.ExternalAuthCacheTime) * time.Second
  1383. }
  1384. if user.LastLogin <= user.UpdatedAt || !isLastActivityRecent(user.LastLogin, delay) {
  1385. err := provider.updateLastLogin(user.Username)
  1386. if err == nil {
  1387. webDAVUsersCache.updateLastLogin(user.Username)
  1388. }
  1389. }
  1390. }
  1391. // UpdateAdminLastLogin updates the last login field for the given SFTPGo admin
  1392. func UpdateAdminLastLogin(admin *Admin) {
  1393. if !isLastActivityRecent(admin.LastLogin, lastLoginMinDelay) {
  1394. provider.updateAdminLastLogin(admin.Username) //nolint:errcheck
  1395. }
  1396. }
  1397. // UpdateUserQuota updates the quota for the given SFTPGo user adding filesAdd and sizeAdd.
  1398. // If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
  1399. func UpdateUserQuota(user *User, filesAdd int, sizeAdd int64, reset bool) error {
  1400. if config.TrackQuota == 0 {
  1401. return util.NewMethodDisabledError(trackQuotaDisabledError)
  1402. } else if config.TrackQuota == 2 && !reset && !user.HasQuotaRestrictions() {
  1403. return nil
  1404. }
  1405. if filesAdd == 0 && sizeAdd == 0 && !reset {
  1406. return nil
  1407. }
  1408. if config.DelayedQuotaUpdate == 0 || reset {
  1409. if reset {
  1410. delayedQuotaUpdater.resetUserQuota(user.Username)
  1411. }
  1412. return provider.updateQuota(user.Username, filesAdd, sizeAdd, reset)
  1413. }
  1414. delayedQuotaUpdater.updateUserQuota(user.Username, filesAdd, sizeAdd)
  1415. return nil
  1416. }
  1417. // UpdateUserFolderQuota updates the quota for the given user and virtual folder.
  1418. func UpdateUserFolderQuota(folder *vfs.VirtualFolder, user *User, filesAdd int, sizeAdd int64, reset bool) {
  1419. if folder.IsIncludedInUserQuota() {
  1420. UpdateUserQuota(user, filesAdd, sizeAdd, reset) //nolint:errcheck
  1421. return
  1422. }
  1423. UpdateVirtualFolderQuota(&folder.BaseVirtualFolder, filesAdd, sizeAdd, reset) //nolint:errcheck
  1424. }
  1425. // UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd.
  1426. // If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
  1427. func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error {
  1428. if config.TrackQuota == 0 {
  1429. return util.NewMethodDisabledError(trackQuotaDisabledError)
  1430. }
  1431. if filesAdd == 0 && sizeAdd == 0 && !reset {
  1432. return nil
  1433. }
  1434. if config.DelayedQuotaUpdate == 0 || reset {
  1435. if reset {
  1436. delayedQuotaUpdater.resetFolderQuota(vfolder.Name)
  1437. }
  1438. return provider.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd, reset)
  1439. }
  1440. delayedQuotaUpdater.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd)
  1441. return nil
  1442. }
  1443. // UpdateUserTransferQuota updates the transfer quota for the given SFTPGo user.
  1444. // If reset is true uploadSize and downloadSize indicates the actual sizes instead of the difference.
  1445. func UpdateUserTransferQuota(user *User, uploadSize, downloadSize int64, reset bool) error {
  1446. if config.TrackQuota == 0 {
  1447. return util.NewMethodDisabledError(trackQuotaDisabledError)
  1448. } else if config.TrackQuota == 2 && !reset && !user.HasTransferQuotaRestrictions() {
  1449. return nil
  1450. }
  1451. if downloadSize == 0 && uploadSize == 0 && !reset {
  1452. return nil
  1453. }
  1454. if config.DelayedQuotaUpdate == 0 || reset {
  1455. if reset {
  1456. delayedQuotaUpdater.resetUserTransferQuota(user.Username)
  1457. }
  1458. return provider.updateTransferQuota(user.Username, uploadSize, downloadSize, reset)
  1459. }
  1460. delayedQuotaUpdater.updateUserTransferQuota(user.Username, uploadSize, downloadSize)
  1461. return nil
  1462. }
  1463. // UpdateUserTransferTimestamps updates the first download/upload fields if unset
  1464. func UpdateUserTransferTimestamps(username string, isUpload bool) error {
  1465. if isUpload {
  1466. err := provider.setFirstUploadTimestamp(username)
  1467. if err != nil {
  1468. providerLog(logger.LevelWarn, "unable to set first upload: %v", err)
  1469. }
  1470. return err
  1471. }
  1472. err := provider.setFirstDownloadTimestamp(username)
  1473. if err != nil {
  1474. providerLog(logger.LevelWarn, "unable to set first download: %v", err)
  1475. }
  1476. return err
  1477. }
  1478. // GetUsedQuota returns the used quota for the given SFTPGo user.
  1479. func GetUsedQuota(username string) (int, int64, int64, int64, error) {
  1480. if config.TrackQuota == 0 {
  1481. return 0, 0, 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  1482. }
  1483. files, size, ulTransferSize, dlTransferSize, err := provider.getUsedQuota(username)
  1484. if err != nil {
  1485. return files, size, ulTransferSize, dlTransferSize, err
  1486. }
  1487. delayedFiles, delayedSize := delayedQuotaUpdater.getUserPendingQuota(username)
  1488. delayedUlTransferSize, delayedDLTransferSize := delayedQuotaUpdater.getUserPendingTransferQuota(username)
  1489. return files + delayedFiles, size + delayedSize, ulTransferSize + delayedUlTransferSize,
  1490. dlTransferSize + delayedDLTransferSize, err
  1491. }
  1492. // GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.
  1493. func GetUsedVirtualFolderQuota(name string) (int, int64, error) {
  1494. if config.TrackQuota == 0 {
  1495. return 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  1496. }
  1497. files, size, err := provider.getUsedFolderQuota(name)
  1498. if err != nil {
  1499. return files, size, err
  1500. }
  1501. delayedFiles, delayedSize := delayedQuotaUpdater.getFolderPendingQuota(name)
  1502. return files + delayedFiles, size + delayedSize, err
  1503. }
  1504. // GetConfigs returns the configurations
  1505. func GetConfigs() (Configs, error) {
  1506. return provider.getConfigs()
  1507. }
  1508. // UpdateConfigs updates configurations
  1509. func UpdateConfigs(configs *Configs, executor, ipAddress, role string) error {
  1510. if configs == nil {
  1511. configs = &Configs{}
  1512. } else {
  1513. configs.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  1514. }
  1515. err := provider.setConfigs(configs)
  1516. if err == nil {
  1517. executeAction(operationUpdate, executor, ipAddress, actionObjectConfigs, "configs", role, configs)
  1518. }
  1519. return err
  1520. }
  1521. // AddShare adds a new share
  1522. func AddShare(share *Share, executor, ipAddress, role string) error {
  1523. err := provider.addShare(share)
  1524. if err == nil {
  1525. executeAction(operationAdd, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
  1526. }
  1527. return err
  1528. }
  1529. // UpdateShare updates an existing share
  1530. func UpdateShare(share *Share, executor, ipAddress, role string) error {
  1531. err := provider.updateShare(share)
  1532. if err == nil {
  1533. executeAction(operationUpdate, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
  1534. }
  1535. return err
  1536. }
  1537. // DeleteShare deletes an existing share
  1538. func DeleteShare(shareID string, executor, ipAddress, role string) error {
  1539. share, err := provider.shareExists(shareID, executor)
  1540. if err != nil {
  1541. return err
  1542. }
  1543. err = provider.deleteShare(share)
  1544. if err == nil {
  1545. executeAction(operationDelete, executor, ipAddress, actionObjectShare, shareID, role, &share)
  1546. }
  1547. return err
  1548. }
  1549. // ShareExists returns the share with the given ID if it exists
  1550. func ShareExists(shareID, username string) (Share, error) {
  1551. if shareID == "" {
  1552. return Share{}, util.NewRecordNotFoundError(fmt.Sprintf("Share %q does not exist", shareID))
  1553. }
  1554. return provider.shareExists(shareID, username)
  1555. }
  1556. // AddIPListEntry adds a new IP list entry
  1557. func AddIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
  1558. err := provider.addIPListEntry(entry)
  1559. if err == nil {
  1560. executeAction(operationAdd, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
  1561. for _, l := range inMemoryLists {
  1562. l.addEntry(entry)
  1563. }
  1564. }
  1565. return err
  1566. }
  1567. // UpdateIPListEntry updates an existing IP list entry
  1568. func UpdateIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
  1569. err := provider.updateIPListEntry(entry)
  1570. if err == nil {
  1571. executeAction(operationUpdate, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
  1572. for _, l := range inMemoryLists {
  1573. l.updateEntry(entry)
  1574. }
  1575. }
  1576. return err
  1577. }
  1578. // DeleteIPListEntry deletes an existing IP list entry
  1579. func DeleteIPListEntry(ipOrNet string, listType IPListType, executor, ipAddress, executorRole string) error {
  1580. entry, err := provider.ipListEntryExists(ipOrNet, listType)
  1581. if err != nil {
  1582. return err
  1583. }
  1584. err = provider.deleteIPListEntry(entry, config.IsShared == 1)
  1585. if err == nil {
  1586. executeAction(operationDelete, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, &entry)
  1587. for _, l := range inMemoryLists {
  1588. l.removeEntry(&entry)
  1589. }
  1590. }
  1591. return err
  1592. }
  1593. // IPListEntryExists returns the IP list entry with the given IP/net and type if it exists
  1594. func IPListEntryExists(ipOrNet string, listType IPListType) (IPListEntry, error) {
  1595. return provider.ipListEntryExists(ipOrNet, listType)
  1596. }
  1597. // GetIPListEntries returns the IP list entries applying the specified criteria and search limit
  1598. func GetIPListEntries(listType IPListType, filter, from, order string, limit int) ([]IPListEntry, error) {
  1599. if !util.Contains(supportedIPListType, listType) {
  1600. return nil, util.NewValidationError(fmt.Sprintf("invalid list type %d", listType))
  1601. }
  1602. return provider.getIPListEntries(listType, filter, from, order, limit)
  1603. }
  1604. // AddRole adds a new role
  1605. func AddRole(role *Role, executor, ipAddress, executorRole string) error {
  1606. role.Name = config.convertName(role.Name)
  1607. err := provider.addRole(role)
  1608. if err == nil {
  1609. executeAction(operationAdd, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
  1610. }
  1611. return err
  1612. }
  1613. // UpdateRole updates an existing Role
  1614. func UpdateRole(role *Role, executor, ipAddress, executorRole string) error {
  1615. err := provider.updateRole(role)
  1616. if err == nil {
  1617. executeAction(operationUpdate, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
  1618. }
  1619. return err
  1620. }
  1621. // DeleteRole deletes an existing Role
  1622. func DeleteRole(name string, executor, ipAddress, executorRole string) error {
  1623. name = config.convertName(name)
  1624. role, err := provider.roleExists(name)
  1625. if err != nil {
  1626. return err
  1627. }
  1628. if len(role.Admins) > 0 {
  1629. errorString := fmt.Sprintf("the role %q is referenced, it cannot be removed", role.Name)
  1630. return util.NewValidationError(errorString)
  1631. }
  1632. err = provider.deleteRole(role)
  1633. if err == nil {
  1634. executeAction(operationDelete, executor, ipAddress, actionObjectRole, role.Name, executorRole, &role)
  1635. for _, user := range role.Users {
  1636. provider.setUpdatedAt(user)
  1637. u, err := provider.userExists(user, "")
  1638. if err == nil {
  1639. webDAVUsersCache.swap(&u, "")
  1640. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  1641. }
  1642. }
  1643. }
  1644. return err
  1645. }
  1646. // RoleExists returns the Role with the given name if it exists
  1647. func RoleExists(name string) (Role, error) {
  1648. name = config.convertName(name)
  1649. return provider.roleExists(name)
  1650. }
  1651. // AddGroup adds a new group
  1652. func AddGroup(group *Group, executor, ipAddress, role string) error {
  1653. group.Name = config.convertName(group.Name)
  1654. err := provider.addGroup(group)
  1655. if err == nil {
  1656. executeAction(operationAdd, executor, ipAddress, actionObjectGroup, group.Name, role, group)
  1657. }
  1658. return err
  1659. }
  1660. // UpdateGroup updates an existing Group
  1661. func UpdateGroup(group *Group, users []string, executor, ipAddress, role string) error {
  1662. err := provider.updateGroup(group)
  1663. if err == nil {
  1664. for _, user := range users {
  1665. provider.setUpdatedAt(user)
  1666. u, err := provider.userExists(user, "")
  1667. if err == nil {
  1668. webDAVUsersCache.swap(&u, "")
  1669. } else {
  1670. RemoveCachedWebDAVUser(user)
  1671. }
  1672. }
  1673. executeAction(operationUpdate, executor, ipAddress, actionObjectGroup, group.Name, role, group)
  1674. }
  1675. return err
  1676. }
  1677. // DeleteGroup deletes an existing Group
  1678. func DeleteGroup(name string, executor, ipAddress, role string) error {
  1679. name = config.convertName(name)
  1680. group, err := provider.groupExists(name)
  1681. if err != nil {
  1682. return err
  1683. }
  1684. if len(group.Users) > 0 {
  1685. errorString := fmt.Sprintf("the group %q is referenced, it cannot be removed", group.Name)
  1686. return util.NewValidationError(errorString)
  1687. }
  1688. err = provider.deleteGroup(group)
  1689. if err == nil {
  1690. for _, user := range group.Users {
  1691. provider.setUpdatedAt(user)
  1692. u, err := provider.userExists(user, "")
  1693. if err == nil {
  1694. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  1695. }
  1696. RemoveCachedWebDAVUser(user)
  1697. }
  1698. executeAction(operationDelete, executor, ipAddress, actionObjectGroup, group.Name, role, &group)
  1699. }
  1700. return err
  1701. }
  1702. // GroupExists returns the Group with the given name if it exists
  1703. func GroupExists(name string) (Group, error) {
  1704. name = config.convertName(name)
  1705. return provider.groupExists(name)
  1706. }
  1707. // AddAPIKey adds a new API key
  1708. func AddAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
  1709. err := provider.addAPIKey(apiKey)
  1710. if err == nil {
  1711. executeAction(operationAdd, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
  1712. }
  1713. return err
  1714. }
  1715. // UpdateAPIKey updates an existing API key
  1716. func UpdateAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
  1717. err := provider.updateAPIKey(apiKey)
  1718. if err == nil {
  1719. executeAction(operationUpdate, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
  1720. }
  1721. return err
  1722. }
  1723. // DeleteAPIKey deletes an existing API key
  1724. func DeleteAPIKey(keyID string, executor, ipAddress, role string) error {
  1725. apiKey, err := provider.apiKeyExists(keyID)
  1726. if err != nil {
  1727. return err
  1728. }
  1729. err = provider.deleteAPIKey(apiKey)
  1730. if err == nil {
  1731. executeAction(operationDelete, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, &apiKey)
  1732. cachedAPIKeys.Remove(keyID)
  1733. }
  1734. return err
  1735. }
  1736. // APIKeyExists returns the API key with the given ID if it exists
  1737. func APIKeyExists(keyID string) (APIKey, error) {
  1738. if keyID == "" {
  1739. return APIKey{}, util.NewRecordNotFoundError(fmt.Sprintf("API key %q does not exist", keyID))
  1740. }
  1741. return provider.apiKeyExists(keyID)
  1742. }
  1743. // GetEventActions returns an array of event actions respecting limit and offset
  1744. func GetEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error) {
  1745. return provider.getEventActions(limit, offset, order, minimal)
  1746. }
  1747. // EventActionExists returns the event action with the given name if it exists
  1748. func EventActionExists(name string) (BaseEventAction, error) {
  1749. name = config.convertName(name)
  1750. return provider.eventActionExists(name)
  1751. }
  1752. // AddEventAction adds a new event action
  1753. func AddEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
  1754. action.Name = config.convertName(action.Name)
  1755. err := provider.addEventAction(action)
  1756. if err == nil {
  1757. executeAction(operationAdd, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
  1758. }
  1759. return err
  1760. }
  1761. // UpdateEventAction updates an existing event action
  1762. func UpdateEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
  1763. err := provider.updateEventAction(action)
  1764. if err == nil {
  1765. if fnReloadRules != nil {
  1766. fnReloadRules()
  1767. }
  1768. executeAction(operationUpdate, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
  1769. }
  1770. return err
  1771. }
  1772. // DeleteEventAction deletes an existing event action
  1773. func DeleteEventAction(name string, executor, ipAddress, role string) error {
  1774. name = config.convertName(name)
  1775. action, err := provider.eventActionExists(name)
  1776. if err != nil {
  1777. return err
  1778. }
  1779. if len(action.Rules) > 0 {
  1780. errorString := fmt.Sprintf("the event action %#q is referenced, it cannot be removed", action.Name)
  1781. return util.NewValidationError(errorString)
  1782. }
  1783. err = provider.deleteEventAction(action)
  1784. if err == nil {
  1785. executeAction(operationDelete, executor, ipAddress, actionObjectEventAction, action.Name, role, &action)
  1786. }
  1787. return err
  1788. }
  1789. // GetEventRules returns an array of event rules respecting limit and offset
  1790. func GetEventRules(limit, offset int, order string) ([]EventRule, error) {
  1791. return provider.getEventRules(limit, offset, order)
  1792. }
  1793. // GetRecentlyUpdatedRules returns the event rules updated after the specified time
  1794. func GetRecentlyUpdatedRules(after int64) ([]EventRule, error) {
  1795. return provider.getRecentlyUpdatedRules(after)
  1796. }
  1797. // EventRuleExists returns the event rule with the given name if it exists
  1798. func EventRuleExists(name string) (EventRule, error) {
  1799. name = config.convertName(name)
  1800. return provider.eventRuleExists(name)
  1801. }
  1802. // AddEventRule adds a new event rule
  1803. func AddEventRule(rule *EventRule, executor, ipAddress, role string) error {
  1804. rule.Name = config.convertName(rule.Name)
  1805. err := provider.addEventRule(rule)
  1806. if err == nil {
  1807. if fnReloadRules != nil {
  1808. fnReloadRules()
  1809. }
  1810. executeAction(operationAdd, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
  1811. }
  1812. return err
  1813. }
  1814. // UpdateEventRule updates an existing event rule
  1815. func UpdateEventRule(rule *EventRule, executor, ipAddress, role string) error {
  1816. err := provider.updateEventRule(rule)
  1817. if err == nil {
  1818. if fnReloadRules != nil {
  1819. fnReloadRules()
  1820. }
  1821. executeAction(operationUpdate, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
  1822. }
  1823. return err
  1824. }
  1825. // DeleteEventRule deletes an existing event rule
  1826. func DeleteEventRule(name string, executor, ipAddress, role string) error {
  1827. name = config.convertName(name)
  1828. rule, err := provider.eventRuleExists(name)
  1829. if err != nil {
  1830. return err
  1831. }
  1832. err = provider.deleteEventRule(rule, config.IsShared == 1)
  1833. if err == nil {
  1834. if fnRemoveRule != nil {
  1835. fnRemoveRule(rule.Name)
  1836. }
  1837. executeAction(operationDelete, executor, ipAddress, actionObjectEventRule, rule.Name, role, &rule)
  1838. }
  1839. return err
  1840. }
  1841. // RemoveEventRule delets an existing event rule without marking it as deleted
  1842. func RemoveEventRule(rule EventRule) error {
  1843. return provider.deleteEventRule(rule, false)
  1844. }
  1845. // GetTaskByName returns the task with the specified name
  1846. func GetTaskByName(name string) (Task, error) {
  1847. return provider.getTaskByName(name)
  1848. }
  1849. // AddTask add a task with the specified name
  1850. func AddTask(name string) error {
  1851. return provider.addTask(name)
  1852. }
  1853. // UpdateTask updates the task with the specified name and version
  1854. func UpdateTask(name string, version int64) error {
  1855. return provider.updateTask(name, version)
  1856. }
  1857. // UpdateTaskTimestamp updates the timestamp for the task with the specified name
  1858. func UpdateTaskTimestamp(name string) error {
  1859. return provider.updateTaskTimestamp(name)
  1860. }
  1861. // GetNodes returns the other cluster nodes
  1862. func GetNodes() ([]Node, error) {
  1863. if currentNode == nil {
  1864. return nil, nil
  1865. }
  1866. nodes, err := provider.getNodes()
  1867. if err != nil {
  1868. providerLog(logger.LevelError, "unable to get other cluster nodes %v", err)
  1869. }
  1870. return nodes, err
  1871. }
  1872. // GetNodeByName returns a node, different from the current one, by name
  1873. func GetNodeByName(name string) (Node, error) {
  1874. if currentNode == nil {
  1875. return Node{}, util.NewRecordNotFoundError(errNoClusterNodes.Error())
  1876. }
  1877. if name == currentNode.Name {
  1878. return Node{}, util.NewValidationError(fmt.Sprintf("%s is the current node, it must refer to other nodes", name))
  1879. }
  1880. return provider.getNodeByName(name)
  1881. }
  1882. // HasAdmin returns true if the first admin has been created
  1883. // and so SFTPGo is ready to be used
  1884. func HasAdmin() bool {
  1885. return isAdminCreated.Load()
  1886. }
  1887. // AddAdmin adds a new SFTPGo admin
  1888. func AddAdmin(admin *Admin, executor, ipAddress, role string) error {
  1889. admin.Filters.RecoveryCodes = nil
  1890. admin.Filters.TOTPConfig = AdminTOTPConfig{
  1891. Enabled: false,
  1892. }
  1893. admin.Username = config.convertName(admin.Username)
  1894. err := provider.addAdmin(admin)
  1895. if err == nil {
  1896. isAdminCreated.Store(true)
  1897. executeAction(operationAdd, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
  1898. }
  1899. return err
  1900. }
  1901. // UpdateAdmin updates an existing SFTPGo admin
  1902. func UpdateAdmin(admin *Admin, executor, ipAddress, role string) error {
  1903. err := provider.updateAdmin(admin)
  1904. if err == nil {
  1905. executeAction(operationUpdate, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
  1906. }
  1907. return err
  1908. }
  1909. // DeleteAdmin deletes an existing SFTPGo admin
  1910. func DeleteAdmin(username, executor, ipAddress, role string) error {
  1911. username = config.convertName(username)
  1912. admin, err := provider.adminExists(username)
  1913. if err != nil {
  1914. return err
  1915. }
  1916. err = provider.deleteAdmin(admin)
  1917. if err == nil {
  1918. executeAction(operationDelete, executor, ipAddress, actionObjectAdmin, admin.Username, role, &admin)
  1919. cachedAdminPasswords.Remove(username)
  1920. }
  1921. return err
  1922. }
  1923. // AdminExists returns the admin with the given username if it exists
  1924. func AdminExists(username string) (Admin, error) {
  1925. username = config.convertName(username)
  1926. return provider.adminExists(username)
  1927. }
  1928. // UserExists checks if the given SFTPGo username exists, returns an error if no match is found
  1929. func UserExists(username, role string) (User, error) {
  1930. username = config.convertName(username)
  1931. return provider.userExists(username, role)
  1932. }
  1933. // GetUserWithGroupSettings tries to return the user with the specified username
  1934. // loading also the group settings
  1935. func GetUserWithGroupSettings(username, role string) (User, error) {
  1936. username = config.convertName(username)
  1937. user, err := provider.userExists(username, role)
  1938. if err != nil {
  1939. return user, err
  1940. }
  1941. err = user.LoadAndApplyGroupSettings()
  1942. return user, err
  1943. }
  1944. // GetUserVariants tries to return the user with the specified username with and without
  1945. // group settings applied
  1946. func GetUserVariants(username, role string) (User, User, error) {
  1947. username = config.convertName(username)
  1948. user, err := provider.userExists(username, role)
  1949. if err != nil {
  1950. return user, User{}, err
  1951. }
  1952. userWithGroupSettings := user.getACopy()
  1953. err = userWithGroupSettings.LoadAndApplyGroupSettings()
  1954. return user, userWithGroupSettings, err
  1955. }
  1956. // AddUser adds a new SFTPGo user.
  1957. func AddUser(user *User, executor, ipAddress, role string) error {
  1958. user.Username = config.convertName(user.Username)
  1959. err := provider.addUser(user)
  1960. if err == nil {
  1961. executeAction(operationAdd, executor, ipAddress, actionObjectUser, user.Username, role, user)
  1962. }
  1963. return err
  1964. }
  1965. // UpdateUserPassword updates the user password
  1966. func UpdateUserPassword(username, plainPwd, executor, ipAddress, role string) error {
  1967. user, err := provider.userExists(username, role)
  1968. if err != nil {
  1969. return err
  1970. }
  1971. userCopy := user.getACopy()
  1972. if err := userCopy.LoadAndApplyGroupSettings(); err != nil {
  1973. return err
  1974. }
  1975. userCopy.Password = plainPwd
  1976. if err := createUserPasswordHash(&userCopy); err != nil {
  1977. return err
  1978. }
  1979. user.LastPasswordChange = userCopy.LastPasswordChange
  1980. user.Password = userCopy.Password
  1981. user.Filters.RequirePasswordChange = false
  1982. // the last password change is set when validating the user
  1983. if err := provider.updateUser(&user); err != nil {
  1984. return err
  1985. }
  1986. webDAVUsersCache.swap(&user, plainPwd)
  1987. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, username, role, &user)
  1988. return nil
  1989. }
  1990. // UpdateUser updates an existing SFTPGo user.
  1991. func UpdateUser(user *User, executor, ipAddress, role string) error {
  1992. if user.groupSettingsApplied {
  1993. return errors.New("cannot save a user with group settings applied")
  1994. }
  1995. err := provider.updateUser(user)
  1996. if err == nil {
  1997. webDAVUsersCache.swap(user, "")
  1998. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, user.Username, role, user)
  1999. }
  2000. return err
  2001. }
  2002. // DeleteUser deletes an existing SFTPGo user.
  2003. func DeleteUser(username, executor, ipAddress, role string) error {
  2004. username = config.convertName(username)
  2005. user, err := provider.userExists(username, role)
  2006. if err != nil {
  2007. return err
  2008. }
  2009. err = provider.deleteUser(user, config.IsShared == 1)
  2010. if err == nil {
  2011. RemoveCachedWebDAVUser(user.Username)
  2012. delayedQuotaUpdater.resetUserQuota(user.Username)
  2013. cachedUserPasswords.Remove(username)
  2014. executeAction(operationDelete, executor, ipAddress, actionObjectUser, user.Username, role, &user)
  2015. }
  2016. return err
  2017. }
  2018. // AddActiveTransfer stores the specified transfer
  2019. func AddActiveTransfer(transfer ActiveTransfer) {
  2020. if err := provider.addActiveTransfer(transfer); err != nil {
  2021. providerLog(logger.LevelError, "unable to add transfer id %v, connection id %v: %v",
  2022. transfer.ID, transfer.ConnID, err)
  2023. }
  2024. }
  2025. // UpdateActiveTransferSizes updates the current upload and download sizes for the specified transfer
  2026. func UpdateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string) {
  2027. if err := provider.updateActiveTransferSizes(ulSize, dlSize, transferID, connectionID); err != nil {
  2028. providerLog(logger.LevelError, "unable to update sizes for transfer id %v, connection id %v: %v",
  2029. transferID, connectionID, err)
  2030. }
  2031. }
  2032. // RemoveActiveTransfer removes the specified transfer
  2033. func RemoveActiveTransfer(transferID int64, connectionID string) {
  2034. if err := provider.removeActiveTransfer(transferID, connectionID); err != nil {
  2035. providerLog(logger.LevelError, "unable to delete transfer id %v, connection id %v: %v",
  2036. transferID, connectionID, err)
  2037. }
  2038. }
  2039. // CleanupActiveTransfers removes the transfer before the specified time
  2040. func CleanupActiveTransfers(before time.Time) error {
  2041. err := provider.cleanupActiveTransfers(before)
  2042. if err == nil {
  2043. providerLog(logger.LevelDebug, "deleted active transfers updated before: %v", before)
  2044. } else {
  2045. providerLog(logger.LevelError, "error deleting active transfers updated before %v: %v", before, err)
  2046. }
  2047. return err
  2048. }
  2049. // GetActiveTransfers retrieves the active transfers with an update time after the specified value
  2050. func GetActiveTransfers(from time.Time) ([]ActiveTransfer, error) {
  2051. return provider.getActiveTransfers(from)
  2052. }
  2053. // AddSharedSession stores a new session within the data provider
  2054. func AddSharedSession(session Session) error {
  2055. err := provider.addSharedSession(session)
  2056. if err != nil {
  2057. providerLog(logger.LevelError, "unable to add shared session, key %q, type: %v, err: %v",
  2058. session.Key, session.Type, err)
  2059. }
  2060. return err
  2061. }
  2062. // DeleteSharedSession deletes the session with the specified key
  2063. func DeleteSharedSession(key string) error {
  2064. err := provider.deleteSharedSession(key)
  2065. if err != nil {
  2066. providerLog(logger.LevelError, "unable to add shared session, key %q, err: %v", key, err)
  2067. }
  2068. return err
  2069. }
  2070. // GetSharedSession retrieves the session with the specified key
  2071. func GetSharedSession(key string) (Session, error) {
  2072. return provider.getSharedSession(key)
  2073. }
  2074. // CleanupSharedSessions removes the shared session with the specified type and
  2075. // before the specified time
  2076. func CleanupSharedSessions(sessionType SessionType, before time.Time) error {
  2077. err := provider.cleanupSharedSessions(sessionType, util.GetTimeAsMsSinceEpoch(before))
  2078. if err == nil {
  2079. providerLog(logger.LevelDebug, "deleted shared sessions before: %v, type: %v", before, sessionType)
  2080. } else {
  2081. providerLog(logger.LevelError, "error deleting shared session before %v, type %v: %v", before, sessionType, err)
  2082. }
  2083. return err
  2084. }
  2085. // ReloadConfig reloads provider configuration.
  2086. // Currently only implemented for memory provider, allows to reload the users
  2087. // from the configured file, if defined
  2088. func ReloadConfig() error {
  2089. return provider.reloadConfig()
  2090. }
  2091. // GetShares returns an array of shares respecting limit and offset
  2092. func GetShares(limit, offset int, order, username string) ([]Share, error) {
  2093. return provider.getShares(limit, offset, order, username)
  2094. }
  2095. // GetAPIKeys returns an array of API keys respecting limit and offset
  2096. func GetAPIKeys(limit, offset int, order string) ([]APIKey, error) {
  2097. return provider.getAPIKeys(limit, offset, order)
  2098. }
  2099. // GetAdmins returns an array of admins respecting limit and offset
  2100. func GetAdmins(limit, offset int, order string) ([]Admin, error) {
  2101. return provider.getAdmins(limit, offset, order)
  2102. }
  2103. // GetRoles returns an array of roles respecting limit and offset
  2104. func GetRoles(limit, offset int, order string, minimal bool) ([]Role, error) {
  2105. return provider.getRoles(limit, offset, order, minimal)
  2106. }
  2107. // GetGroups returns an array of groups respecting limit and offset
  2108. func GetGroups(limit, offset int, order string, minimal bool) ([]Group, error) {
  2109. return provider.getGroups(limit, offset, order, minimal)
  2110. }
  2111. // GetUsers returns an array of users respecting limit and offset
  2112. func GetUsers(limit, offset int, order, role string) ([]User, error) {
  2113. return provider.getUsers(limit, offset, order, role)
  2114. }
  2115. // GetUsersForQuotaCheck returns the users with the fields required for a quota check
  2116. func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error) {
  2117. return provider.getUsersForQuotaCheck(toFetch)
  2118. }
  2119. // AddFolder adds a new virtual folder.
  2120. func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress, role string) error {
  2121. folder.Name = config.convertName(folder.Name)
  2122. err := provider.addFolder(folder)
  2123. if err == nil {
  2124. executeAction(operationAdd, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
  2125. }
  2126. return err
  2127. }
  2128. // UpdateFolder updates the specified virtual folder
  2129. func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress, role string) error {
  2130. err := provider.updateFolder(folder)
  2131. if err == nil {
  2132. executeAction(operationUpdate, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
  2133. usersInGroups, errGrp := provider.getUsersInGroups(groups)
  2134. if errGrp == nil {
  2135. users = append(users, usersInGroups...)
  2136. users = util.RemoveDuplicates(users, false)
  2137. } else {
  2138. providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", groups, errGrp)
  2139. }
  2140. for _, user := range users {
  2141. provider.setUpdatedAt(user)
  2142. u, err := provider.userExists(user, "")
  2143. if err == nil {
  2144. webDAVUsersCache.swap(&u, "")
  2145. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  2146. } else {
  2147. RemoveCachedWebDAVUser(user)
  2148. }
  2149. }
  2150. }
  2151. return err
  2152. }
  2153. // DeleteFolder deletes an existing folder.
  2154. func DeleteFolder(folderName, executor, ipAddress, role string) error {
  2155. folderName = config.convertName(folderName)
  2156. folder, err := provider.getFolderByName(folderName)
  2157. if err != nil {
  2158. return err
  2159. }
  2160. err = provider.deleteFolder(folder)
  2161. if err == nil {
  2162. executeAction(operationDelete, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: folder})
  2163. users := folder.Users
  2164. usersInGroups, errGrp := provider.getUsersInGroups(folder.Groups)
  2165. if errGrp == nil {
  2166. users = append(users, usersInGroups...)
  2167. users = util.RemoveDuplicates(users, false)
  2168. } else {
  2169. providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", folder.Groups, errGrp)
  2170. }
  2171. for _, user := range users {
  2172. provider.setUpdatedAt(user)
  2173. u, err := provider.userExists(user, "")
  2174. if err == nil {
  2175. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  2176. }
  2177. RemoveCachedWebDAVUser(user)
  2178. }
  2179. delayedQuotaUpdater.resetFolderQuota(folderName)
  2180. }
  2181. return err
  2182. }
  2183. // GetFolderByName returns the folder with the specified name if any
  2184. func GetFolderByName(name string) (vfs.BaseVirtualFolder, error) {
  2185. name = config.convertName(name)
  2186. return provider.getFolderByName(name)
  2187. }
  2188. // GetFolders returns an array of folders respecting limit and offset
  2189. func GetFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error) {
  2190. return provider.getFolders(limit, offset, order, minimal)
  2191. }
  2192. func dumpUsers(data *BackupData, scopes []string) error {
  2193. if len(scopes) == 0 || util.Contains(scopes, DumpScopeUsers) {
  2194. users, err := provider.dumpUsers()
  2195. if err != nil {
  2196. return err
  2197. }
  2198. data.Users = users
  2199. }
  2200. return nil
  2201. }
  2202. func dumpFolders(data *BackupData, scopes []string) error {
  2203. if len(scopes) == 0 || util.Contains(scopes, DumpScopeFolders) {
  2204. folders, err := provider.dumpFolders()
  2205. if err != nil {
  2206. return err
  2207. }
  2208. data.Folders = folders
  2209. }
  2210. return nil
  2211. }
  2212. func dumpGroups(data *BackupData, scopes []string) error {
  2213. if len(scopes) == 0 || util.Contains(scopes, DumpScopeGroups) {
  2214. groups, err := provider.dumpGroups()
  2215. if err != nil {
  2216. return err
  2217. }
  2218. data.Groups = groups
  2219. }
  2220. return nil
  2221. }
  2222. func dumpAdmins(data *BackupData, scopes []string) error {
  2223. if len(scopes) == 0 || util.Contains(scopes, DumpScopeAdmins) {
  2224. admins, err := provider.dumpAdmins()
  2225. if err != nil {
  2226. return err
  2227. }
  2228. data.Admins = admins
  2229. }
  2230. return nil
  2231. }
  2232. func dumpAPIKeys(data *BackupData, scopes []string) error {
  2233. if len(scopes) == 0 || util.Contains(scopes, DumpScopeAPIKeys) {
  2234. apiKeys, err := provider.dumpAPIKeys()
  2235. if err != nil {
  2236. return err
  2237. }
  2238. data.APIKeys = apiKeys
  2239. }
  2240. return nil
  2241. }
  2242. func dumpShares(data *BackupData, scopes []string) error {
  2243. if len(scopes) == 0 || util.Contains(scopes, DumpScopeShares) {
  2244. shares, err := provider.dumpShares()
  2245. if err != nil {
  2246. return err
  2247. }
  2248. data.Shares = shares
  2249. }
  2250. return nil
  2251. }
  2252. func dumpActions(data *BackupData, scopes []string) error {
  2253. if len(scopes) == 0 || util.Contains(scopes, DumpScopeActions) {
  2254. actions, err := provider.dumpEventActions()
  2255. if err != nil {
  2256. return err
  2257. }
  2258. data.EventActions = actions
  2259. }
  2260. return nil
  2261. }
  2262. func dumpRules(data *BackupData, scopes []string) error {
  2263. if len(scopes) == 0 || util.Contains(scopes, DumpScopeRules) {
  2264. rules, err := provider.dumpEventRules()
  2265. if err != nil {
  2266. return err
  2267. }
  2268. data.EventRules = rules
  2269. }
  2270. return nil
  2271. }
  2272. func dumpRoles(data *BackupData, scopes []string) error {
  2273. if len(scopes) == 0 || util.Contains(scopes, DumpScopeRoles) {
  2274. roles, err := provider.dumpRoles()
  2275. if err != nil {
  2276. return err
  2277. }
  2278. data.Roles = roles
  2279. }
  2280. return nil
  2281. }
  2282. func dumpIPLists(data *BackupData, scopes []string) error {
  2283. if len(scopes) == 0 || util.Contains(scopes, DumpScopeIPLists) {
  2284. ipLists, err := provider.dumpIPListEntries()
  2285. if err != nil {
  2286. return err
  2287. }
  2288. data.IPLists = ipLists
  2289. }
  2290. return nil
  2291. }
  2292. func dumpConfigs(data *BackupData, scopes []string) error {
  2293. if len(scopes) == 0 || util.Contains(scopes, DumpScopeConfigs) {
  2294. configs, err := provider.getConfigs()
  2295. if err != nil {
  2296. return err
  2297. }
  2298. data.Configs = &configs
  2299. }
  2300. return nil
  2301. }
  2302. // DumpData returns a dump containing the requested scopes.
  2303. // Empty scopes means all
  2304. func DumpData(scopes []string) (BackupData, error) {
  2305. data := BackupData{
  2306. Version: DumpVersion,
  2307. }
  2308. if err := dumpGroups(&data, scopes); err != nil {
  2309. return data, err
  2310. }
  2311. if err := dumpUsers(&data, scopes); err != nil {
  2312. return data, err
  2313. }
  2314. if err := dumpFolders(&data, scopes); err != nil {
  2315. return data, err
  2316. }
  2317. if err := dumpAdmins(&data, scopes); err != nil {
  2318. return data, err
  2319. }
  2320. if err := dumpAPIKeys(&data, scopes); err != nil {
  2321. return data, err
  2322. }
  2323. if err := dumpShares(&data, scopes); err != nil {
  2324. return data, err
  2325. }
  2326. if err := dumpActions(&data, scopes); err != nil {
  2327. return data, err
  2328. }
  2329. if err := dumpRules(&data, scopes); err != nil {
  2330. return data, err
  2331. }
  2332. if err := dumpRoles(&data, scopes); err != nil {
  2333. return data, err
  2334. }
  2335. if err := dumpIPLists(&data, scopes); err != nil {
  2336. return data, err
  2337. }
  2338. if err := dumpConfigs(&data, scopes); err != nil {
  2339. return data, err
  2340. }
  2341. return data, nil
  2342. }
  2343. // ParseDumpData tries to parse data as BackupData
  2344. func ParseDumpData(data []byte) (BackupData, error) {
  2345. var dump BackupData
  2346. err := json.Unmarshal(data, &dump)
  2347. return dump, err
  2348. }
  2349. // GetProviderConfig returns the current provider configuration
  2350. func GetProviderConfig() Config {
  2351. return config
  2352. }
  2353. // GetProviderStatus returns an error if the provider is not available
  2354. func GetProviderStatus() ProviderStatus {
  2355. err := provider.checkAvailability()
  2356. status := ProviderStatus{
  2357. Driver: config.Driver,
  2358. }
  2359. if err == nil {
  2360. status.IsActive = true
  2361. } else {
  2362. status.IsActive = false
  2363. status.Error = err.Error()
  2364. }
  2365. return status
  2366. }
  2367. // Close releases all provider resources.
  2368. // This method is used in test cases.
  2369. // Closing an uninitialized provider is not supported
  2370. func Close() error {
  2371. stopScheduler()
  2372. return provider.close()
  2373. }
  2374. func createProvider(basePath string) error {
  2375. sqlPlaceholders = getSQLPlaceholders()
  2376. if err := validateSQLTablesPrefix(); err != nil {
  2377. return err
  2378. }
  2379. logSender = fmt.Sprintf("dataprovider_%v", config.Driver)
  2380. switch config.Driver {
  2381. case SQLiteDataProviderName:
  2382. return initializeSQLiteProvider(basePath)
  2383. case PGSQLDataProviderName, CockroachDataProviderName:
  2384. return initializePGSQLProvider()
  2385. case MySQLDataProviderName:
  2386. return initializeMySQLProvider()
  2387. case BoltDataProviderName:
  2388. return initializeBoltProvider(basePath)
  2389. case MemoryDataProviderName:
  2390. if err := initializeMemoryProvider(basePath); err != nil {
  2391. msg := fmt.Sprintf("provider initialized but data loading failed: %v", err)
  2392. logger.Warn(logSender, "", msg)
  2393. logger.WarnToConsole(msg)
  2394. }
  2395. return nil
  2396. default:
  2397. return fmt.Errorf("unsupported data provider: %v", config.Driver)
  2398. }
  2399. }
  2400. func copyBaseUserFilters(in sdk.BaseUserFilters) sdk.BaseUserFilters {
  2401. filters := sdk.BaseUserFilters{}
  2402. filters.MaxUploadFileSize = in.MaxUploadFileSize
  2403. filters.TLSUsername = in.TLSUsername
  2404. filters.UserType = in.UserType
  2405. filters.AllowedIP = make([]string, len(in.AllowedIP))
  2406. copy(filters.AllowedIP, in.AllowedIP)
  2407. filters.DeniedIP = make([]string, len(in.DeniedIP))
  2408. copy(filters.DeniedIP, in.DeniedIP)
  2409. filters.DeniedLoginMethods = make([]string, len(in.DeniedLoginMethods))
  2410. copy(filters.DeniedLoginMethods, in.DeniedLoginMethods)
  2411. filters.FilePatterns = make([]sdk.PatternsFilter, len(in.FilePatterns))
  2412. copy(filters.FilePatterns, in.FilePatterns)
  2413. filters.DeniedProtocols = make([]string, len(in.DeniedProtocols))
  2414. copy(filters.DeniedProtocols, in.DeniedProtocols)
  2415. filters.TwoFactorAuthProtocols = make([]string, len(in.TwoFactorAuthProtocols))
  2416. copy(filters.TwoFactorAuthProtocols, in.TwoFactorAuthProtocols)
  2417. filters.Hooks.ExternalAuthDisabled = in.Hooks.ExternalAuthDisabled
  2418. filters.Hooks.PreLoginDisabled = in.Hooks.PreLoginDisabled
  2419. filters.Hooks.CheckPasswordDisabled = in.Hooks.CheckPasswordDisabled
  2420. filters.DisableFsChecks = in.DisableFsChecks
  2421. filters.StartDirectory = in.StartDirectory
  2422. filters.FTPSecurity = in.FTPSecurity
  2423. filters.IsAnonymous = in.IsAnonymous
  2424. filters.AllowAPIKeyAuth = in.AllowAPIKeyAuth
  2425. filters.ExternalAuthCacheTime = in.ExternalAuthCacheTime
  2426. filters.DefaultSharesExpiration = in.DefaultSharesExpiration
  2427. filters.MaxSharesExpiration = in.MaxSharesExpiration
  2428. filters.PasswordExpiration = in.PasswordExpiration
  2429. filters.PasswordStrength = in.PasswordStrength
  2430. filters.WebClient = make([]string, len(in.WebClient))
  2431. copy(filters.WebClient, in.WebClient)
  2432. filters.TLSCerts = make([]string, len(in.TLSCerts))
  2433. copy(filters.TLSCerts, in.TLSCerts)
  2434. filters.BandwidthLimits = make([]sdk.BandwidthLimit, 0, len(in.BandwidthLimits))
  2435. for _, limit := range in.BandwidthLimits {
  2436. bwLimit := sdk.BandwidthLimit{
  2437. UploadBandwidth: limit.UploadBandwidth,
  2438. DownloadBandwidth: limit.DownloadBandwidth,
  2439. Sources: make([]string, 0, len(limit.Sources)),
  2440. }
  2441. bwLimit.Sources = make([]string, len(limit.Sources))
  2442. copy(bwLimit.Sources, limit.Sources)
  2443. filters.BandwidthLimits = append(filters.BandwidthLimits, bwLimit)
  2444. }
  2445. filters.AccessTime = make([]sdk.TimePeriod, 0, len(in.AccessTime))
  2446. for _, period := range in.AccessTime {
  2447. filters.AccessTime = append(filters.AccessTime, sdk.TimePeriod{
  2448. DayOfWeek: period.DayOfWeek,
  2449. From: period.From,
  2450. To: period.To,
  2451. })
  2452. }
  2453. return filters
  2454. }
  2455. func buildUserHomeDir(user *User) {
  2456. if user.HomeDir == "" {
  2457. if config.UsersBaseDir != "" {
  2458. user.HomeDir = filepath.Join(config.UsersBaseDir, user.Username)
  2459. return
  2460. }
  2461. switch user.FsConfig.Provider {
  2462. case sdk.SFTPFilesystemProvider, sdk.S3FilesystemProvider, sdk.AzureBlobFilesystemProvider, sdk.GCSFilesystemProvider, sdk.HTTPFilesystemProvider:
  2463. if tempPath != "" {
  2464. user.HomeDir = filepath.Join(tempPath, user.Username)
  2465. } else {
  2466. user.HomeDir = filepath.Join(os.TempDir(), user.Username)
  2467. }
  2468. }
  2469. } else {
  2470. user.HomeDir = filepath.Clean(user.HomeDir)
  2471. }
  2472. }
  2473. func validateFolderQuotaLimits(folder vfs.VirtualFolder) error {
  2474. if folder.QuotaSize < -1 {
  2475. return util.NewI18nError(
  2476. util.NewValidationError(fmt.Sprintf("invalid quota_size: %v folder path %q", folder.QuotaSize, folder.MappedPath)),
  2477. util.I18nErrorFolderQuotaSizeInvalid,
  2478. )
  2479. }
  2480. if folder.QuotaFiles < -1 {
  2481. return util.NewI18nError(
  2482. util.NewValidationError(fmt.Sprintf("invalid quota_file: %v folder path %q", folder.QuotaFiles, folder.MappedPath)),
  2483. util.I18nErrorFolderQuotaFileInvalid,
  2484. )
  2485. }
  2486. if (folder.QuotaSize == -1 && folder.QuotaFiles != -1) || (folder.QuotaFiles == -1 && folder.QuotaSize != -1) {
  2487. return util.NewI18nError(
  2488. util.NewValidationError(fmt.Sprintf("virtual folder quota_size and quota_files must be both -1 or >= 0, quota_size: %v quota_files: %v",
  2489. folder.QuotaFiles, folder.QuotaSize)),
  2490. util.I18nErrorFolderQuotaInvalid,
  2491. )
  2492. }
  2493. return nil
  2494. }
  2495. func validateUserGroups(user *User) error {
  2496. if len(user.Groups) == 0 {
  2497. return nil
  2498. }
  2499. hasPrimary := false
  2500. groupNames := make(map[string]bool)
  2501. for _, g := range user.Groups {
  2502. if g.Type < sdk.GroupTypePrimary && g.Type > sdk.GroupTypeMembership {
  2503. return util.NewValidationError(fmt.Sprintf("invalid group type: %v", g.Type))
  2504. }
  2505. if g.Type == sdk.GroupTypePrimary {
  2506. if hasPrimary {
  2507. return util.NewI18nError(
  2508. util.NewValidationError("only one primary group is allowed"),
  2509. util.I18nErrorPrimaryGroup,
  2510. )
  2511. }
  2512. hasPrimary = true
  2513. }
  2514. if groupNames[g.Name] {
  2515. return util.NewI18nError(
  2516. util.NewValidationError(fmt.Sprintf("the group %q is duplicated", g.Name)),
  2517. util.I18nErrorDuplicateGroup,
  2518. )
  2519. }
  2520. groupNames[g.Name] = true
  2521. }
  2522. return nil
  2523. }
  2524. func validateAssociatedVirtualFolders(vfolders []vfs.VirtualFolder) ([]vfs.VirtualFolder, error) {
  2525. if len(vfolders) == 0 {
  2526. return []vfs.VirtualFolder{}, nil
  2527. }
  2528. var virtualFolders []vfs.VirtualFolder
  2529. folderNames := make(map[string]bool)
  2530. for _, v := range vfolders {
  2531. if v.VirtualPath == "" {
  2532. return nil, util.NewI18nError(
  2533. util.NewValidationError("mount/virtual path is mandatory"),
  2534. util.I18nErrorFolderMountPathRequired,
  2535. )
  2536. }
  2537. cleanedVPath := util.CleanPath(v.VirtualPath)
  2538. if err := validateFolderQuotaLimits(v); err != nil {
  2539. return nil, err
  2540. }
  2541. if v.Name == "" {
  2542. return nil, util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorFolderNameRequired)
  2543. }
  2544. if folderNames[v.Name] {
  2545. return nil, util.NewI18nError(
  2546. util.NewValidationError(fmt.Sprintf("the folder %q is duplicated", v.Name)),
  2547. util.I18nErrorDuplicatedFolders,
  2548. )
  2549. }
  2550. for _, vFolder := range virtualFolders {
  2551. if util.IsDirOverlapped(vFolder.VirtualPath, cleanedVPath, false, "/") {
  2552. return nil, util.NewI18nError(
  2553. util.NewValidationError(fmt.Sprintf("invalid virtual folder %q, it overlaps with virtual folder %q",
  2554. v.VirtualPath, vFolder.VirtualPath)),
  2555. util.I18nErrorOverlappedFolders,
  2556. )
  2557. }
  2558. }
  2559. virtualFolders = append(virtualFolders, vfs.VirtualFolder{
  2560. BaseVirtualFolder: vfs.BaseVirtualFolder{
  2561. Name: v.Name,
  2562. },
  2563. VirtualPath: cleanedVPath,
  2564. QuotaSize: v.QuotaSize,
  2565. QuotaFiles: v.QuotaFiles,
  2566. })
  2567. folderNames[v.Name] = true
  2568. }
  2569. return virtualFolders, nil
  2570. }
  2571. func validateUserTOTPConfig(c *UserTOTPConfig, username string) error {
  2572. if !c.Enabled {
  2573. c.ConfigName = ""
  2574. c.Secret = kms.NewEmptySecret()
  2575. c.Protocols = nil
  2576. return nil
  2577. }
  2578. if c.ConfigName == "" {
  2579. return util.NewValidationError("totp: config name is mandatory")
  2580. }
  2581. if !util.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
  2582. return util.NewValidationError(fmt.Sprintf("totp: config name %q not found", c.ConfigName))
  2583. }
  2584. if c.Secret.IsEmpty() {
  2585. return util.NewValidationError("totp: secret is mandatory")
  2586. }
  2587. if c.Secret.IsPlain() {
  2588. c.Secret.SetAdditionalData(username)
  2589. if err := c.Secret.Encrypt(); err != nil {
  2590. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  2591. }
  2592. }
  2593. if len(c.Protocols) == 0 {
  2594. return util.NewValidationError("totp: specify at least one protocol")
  2595. }
  2596. for _, protocol := range c.Protocols {
  2597. if !util.Contains(MFAProtocols, protocol) {
  2598. return util.NewValidationError(fmt.Sprintf("totp: invalid protocol %q", protocol))
  2599. }
  2600. }
  2601. return nil
  2602. }
  2603. func validateUserRecoveryCodes(user *User) error {
  2604. for i := 0; i < len(user.Filters.RecoveryCodes); i++ {
  2605. code := &user.Filters.RecoveryCodes[i]
  2606. if code.Secret.IsEmpty() {
  2607. return util.NewValidationError("mfa: recovery code cannot be empty")
  2608. }
  2609. if code.Secret.IsPlain() {
  2610. code.Secret.SetAdditionalData(user.Username)
  2611. if err := code.Secret.Encrypt(); err != nil {
  2612. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  2613. }
  2614. }
  2615. }
  2616. return nil
  2617. }
  2618. func validateUserPermissions(permsToCheck map[string][]string) (map[string][]string, error) {
  2619. permissions := make(map[string][]string)
  2620. for dir, perms := range permsToCheck {
  2621. if len(perms) == 0 && dir == "/" {
  2622. return permissions, util.NewValidationError(fmt.Sprintf("no permissions granted for the directory: %q", dir))
  2623. }
  2624. if len(perms) > len(ValidPerms) {
  2625. return permissions, util.NewValidationError("invalid permissions")
  2626. }
  2627. for _, p := range perms {
  2628. if !util.Contains(ValidPerms, p) {
  2629. return permissions, util.NewValidationError(fmt.Sprintf("invalid permission: %q", p))
  2630. }
  2631. }
  2632. cleanedDir := filepath.ToSlash(path.Clean(dir))
  2633. if cleanedDir != "/" {
  2634. cleanedDir = strings.TrimSuffix(cleanedDir, "/")
  2635. }
  2636. if !path.IsAbs(cleanedDir) {
  2637. return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for non absolute path: %q", dir))
  2638. }
  2639. if dir != cleanedDir && cleanedDir == "/" {
  2640. return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for invalid subdirectory: %q is an alias for \"/\"", dir))
  2641. }
  2642. if util.Contains(perms, PermAny) {
  2643. permissions[cleanedDir] = []string{PermAny}
  2644. } else {
  2645. permissions[cleanedDir] = util.RemoveDuplicates(perms, false)
  2646. }
  2647. }
  2648. return permissions, nil
  2649. }
  2650. func validatePermissions(user *User) error {
  2651. if len(user.Permissions) == 0 {
  2652. return util.NewI18nError(util.NewValidationError("please grant some permissions to this user"), util.I18nErrorNoPermission)
  2653. }
  2654. if _, ok := user.Permissions["/"]; !ok {
  2655. return util.NewI18nError(util.NewValidationError("permissions for the root dir \"/\" must be set"), util.I18nErrorNoRootPermission)
  2656. }
  2657. permissions, err := validateUserPermissions(user.Permissions)
  2658. if err != nil {
  2659. return util.NewI18nError(err, util.I18nErrorGenericPermission)
  2660. }
  2661. user.Permissions = permissions
  2662. return nil
  2663. }
  2664. func validatePublicKeys(user *User) error {
  2665. if len(user.PublicKeys) == 0 {
  2666. user.PublicKeys = []string{}
  2667. }
  2668. var validatedKeys []string
  2669. for idx, key := range user.PublicKeys {
  2670. if key == "" {
  2671. continue
  2672. }
  2673. out, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
  2674. if err != nil {
  2675. return util.NewI18nError(
  2676. util.NewValidationError(fmt.Sprintf("error parsing public key at position %d: %v", idx, err)),
  2677. util.I18nErrorPubKeyInvalid,
  2678. )
  2679. }
  2680. if k, ok := out.(ssh.CryptoPublicKey); ok {
  2681. cryptoKey := k.CryptoPublicKey()
  2682. if rsaKey, ok := cryptoKey.(*rsa.PublicKey); ok {
  2683. if size := rsaKey.N.BitLen(); size < 2048 {
  2684. providerLog(logger.LevelError, "rsa key with size %d not accepted, minimum 2048", size)
  2685. return util.NewI18nError(
  2686. util.NewValidationError(fmt.Sprintf("invalid size %d for rsa key at position %d, minimum 2048",
  2687. size, idx)),
  2688. util.I18nErrorKeySizeInvalid,
  2689. )
  2690. }
  2691. }
  2692. }
  2693. validatedKeys = append(validatedKeys, key)
  2694. }
  2695. user.PublicKeys = util.RemoveDuplicates(validatedKeys, false)
  2696. return nil
  2697. }
  2698. func validateFiltersPatternExtensions(baseFilters *sdk.BaseUserFilters) error {
  2699. if len(baseFilters.FilePatterns) == 0 {
  2700. baseFilters.FilePatterns = []sdk.PatternsFilter{}
  2701. return nil
  2702. }
  2703. filteredPaths := []string{}
  2704. var filters []sdk.PatternsFilter
  2705. for _, f := range baseFilters.FilePatterns {
  2706. cleanedPath := filepath.ToSlash(path.Clean(f.Path))
  2707. if !path.IsAbs(cleanedPath) {
  2708. return util.NewI18nError(
  2709. util.NewValidationError(fmt.Sprintf("invalid path %q for file patterns filter", f.Path)),
  2710. util.I18nErrorFilePatternPathInvalid,
  2711. )
  2712. }
  2713. if util.Contains(filteredPaths, cleanedPath) {
  2714. return util.NewI18nError(
  2715. util.NewValidationError(fmt.Sprintf("duplicate file patterns filter for path %q", f.Path)),
  2716. util.I18nErrorFilePatternDuplicated,
  2717. )
  2718. }
  2719. if len(f.AllowedPatterns) == 0 && len(f.DeniedPatterns) == 0 {
  2720. return util.NewValidationError(fmt.Sprintf("empty file patterns filter for path %q", f.Path))
  2721. }
  2722. if f.DenyPolicy < sdk.DenyPolicyDefault || f.DenyPolicy > sdk.DenyPolicyHide {
  2723. return util.NewValidationError(fmt.Sprintf("invalid deny policy %v for path %q", f.DenyPolicy, f.Path))
  2724. }
  2725. f.Path = cleanedPath
  2726. allowed := make([]string, 0, len(f.AllowedPatterns))
  2727. denied := make([]string, 0, len(f.DeniedPatterns))
  2728. for _, pattern := range f.AllowedPatterns {
  2729. _, err := path.Match(pattern, "abc")
  2730. if err != nil {
  2731. return util.NewI18nError(
  2732. util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
  2733. util.I18nErrorFilePatternInvalid,
  2734. )
  2735. }
  2736. allowed = append(allowed, strings.ToLower(pattern))
  2737. }
  2738. for _, pattern := range f.DeniedPatterns {
  2739. _, err := path.Match(pattern, "abc")
  2740. if err != nil {
  2741. return util.NewI18nError(
  2742. util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
  2743. util.I18nErrorFilePatternInvalid,
  2744. )
  2745. }
  2746. denied = append(denied, strings.ToLower(pattern))
  2747. }
  2748. f.AllowedPatterns = util.RemoveDuplicates(allowed, false)
  2749. f.DeniedPatterns = util.RemoveDuplicates(denied, false)
  2750. filters = append(filters, f)
  2751. filteredPaths = append(filteredPaths, cleanedPath)
  2752. }
  2753. baseFilters.FilePatterns = filters
  2754. return nil
  2755. }
  2756. func checkEmptyFiltersStruct(filters *sdk.BaseUserFilters) {
  2757. if len(filters.AllowedIP) == 0 {
  2758. filters.AllowedIP = []string{}
  2759. }
  2760. if len(filters.DeniedIP) == 0 {
  2761. filters.DeniedIP = []string{}
  2762. }
  2763. if len(filters.DeniedLoginMethods) == 0 {
  2764. filters.DeniedLoginMethods = []string{}
  2765. }
  2766. if len(filters.DeniedProtocols) == 0 {
  2767. filters.DeniedProtocols = []string{}
  2768. }
  2769. }
  2770. func validateIPFilters(filters *sdk.BaseUserFilters) error {
  2771. filters.DeniedIP = util.RemoveDuplicates(filters.DeniedIP, false)
  2772. for _, IPMask := range filters.DeniedIP {
  2773. _, _, err := net.ParseCIDR(IPMask)
  2774. if err != nil {
  2775. return util.NewValidationError(fmt.Sprintf("could not parse denied IP/Mask %q: %v", IPMask, err))
  2776. }
  2777. }
  2778. filters.AllowedIP = util.RemoveDuplicates(filters.AllowedIP, false)
  2779. for _, IPMask := range filters.AllowedIP {
  2780. _, _, err := net.ParseCIDR(IPMask)
  2781. if err != nil {
  2782. return util.NewValidationError(fmt.Sprintf("could not parse allowed IP/Mask %q: %v", IPMask, err))
  2783. }
  2784. }
  2785. return nil
  2786. }
  2787. func validateBandwidthLimit(bl sdk.BandwidthLimit) error {
  2788. if len(bl.Sources) == 0 {
  2789. return util.NewValidationError("no bandwidth limit source specified")
  2790. }
  2791. for _, source := range bl.Sources {
  2792. _, _, err := net.ParseCIDR(source)
  2793. if err != nil {
  2794. return util.NewValidationError(fmt.Sprintf("could not parse bandwidth limit source %q: %v", source, err))
  2795. }
  2796. }
  2797. return nil
  2798. }
  2799. func validateBandwidthLimitsFilter(filters *sdk.BaseUserFilters) error {
  2800. for idx, bandwidthLimit := range filters.BandwidthLimits {
  2801. if err := validateBandwidthLimit(bandwidthLimit); err != nil {
  2802. return err
  2803. }
  2804. if bandwidthLimit.DownloadBandwidth < 0 {
  2805. filters.BandwidthLimits[idx].DownloadBandwidth = 0
  2806. }
  2807. if bandwidthLimit.UploadBandwidth < 0 {
  2808. filters.BandwidthLimits[idx].UploadBandwidth = 0
  2809. }
  2810. }
  2811. return nil
  2812. }
  2813. func updateFiltersValues(filters *sdk.BaseUserFilters) {
  2814. if filters.StartDirectory != "" {
  2815. filters.StartDirectory = util.CleanPath(filters.StartDirectory)
  2816. if filters.StartDirectory == "/" {
  2817. filters.StartDirectory = ""
  2818. }
  2819. }
  2820. }
  2821. func validateFilterProtocols(filters *sdk.BaseUserFilters) error {
  2822. if len(filters.DeniedProtocols) >= len(ValidProtocols) {
  2823. return util.NewValidationError("invalid denied_protocols")
  2824. }
  2825. for _, p := range filters.DeniedProtocols {
  2826. if !util.Contains(ValidProtocols, p) {
  2827. return util.NewValidationError(fmt.Sprintf("invalid denied protocol %q", p))
  2828. }
  2829. }
  2830. for _, p := range filters.TwoFactorAuthProtocols {
  2831. if !util.Contains(MFAProtocols, p) {
  2832. return util.NewValidationError(fmt.Sprintf("invalid two factor protocol %q", p))
  2833. }
  2834. }
  2835. return nil
  2836. }
  2837. func validateTLSCerts(certs []string) ([]string, error) {
  2838. var validateCerts []string
  2839. for idx, cert := range certs {
  2840. if cert == "" {
  2841. continue
  2842. }
  2843. derBlock, _ := pem.Decode([]byte(cert))
  2844. if derBlock == nil {
  2845. return nil, util.NewI18nError(
  2846. util.NewValidationError(fmt.Sprintf("invalid TLS certificate %d", idx)),
  2847. util.I18nErrorInvalidTLSCert,
  2848. )
  2849. }
  2850. crt, err := x509.ParseCertificate(derBlock.Bytes)
  2851. if err != nil {
  2852. return nil, util.NewI18nError(
  2853. util.NewValidationError(fmt.Sprintf("error parsing TLS certificate %d", idx)),
  2854. util.I18nErrorInvalidTLSCert,
  2855. )
  2856. }
  2857. if crt.PublicKeyAlgorithm == x509.RSA {
  2858. if rsaCert, ok := crt.PublicKey.(*rsa.PublicKey); ok {
  2859. if size := rsaCert.N.BitLen(); size < 2048 {
  2860. providerLog(logger.LevelError, "rsa cert with size %d not accepted, minimum 2048", size)
  2861. return nil, util.NewI18nError(
  2862. util.NewValidationError(fmt.Sprintf("invalid size %d for rsa cert at position %d, minimum 2048",
  2863. size, idx)),
  2864. util.I18nErrorKeySizeInvalid,
  2865. )
  2866. }
  2867. }
  2868. }
  2869. validateCerts = append(validateCerts, cert)
  2870. }
  2871. return validateCerts, nil
  2872. }
  2873. func validateBaseFilters(filters *sdk.BaseUserFilters) error {
  2874. checkEmptyFiltersStruct(filters)
  2875. if err := validateIPFilters(filters); err != nil {
  2876. return util.NewI18nError(err, util.I18nErrorIPFiltersInvalid)
  2877. }
  2878. if err := validateBandwidthLimitsFilter(filters); err != nil {
  2879. return util.NewI18nError(err, util.I18nErrorSourceBWLimitInvalid)
  2880. }
  2881. if len(filters.DeniedLoginMethods) >= len(ValidLoginMethods) {
  2882. return util.NewValidationError("invalid denied_login_methods")
  2883. }
  2884. for _, loginMethod := range filters.DeniedLoginMethods {
  2885. if !util.Contains(ValidLoginMethods, loginMethod) {
  2886. return util.NewValidationError(fmt.Sprintf("invalid login method: %q", loginMethod))
  2887. }
  2888. }
  2889. if err := validateFilterProtocols(filters); err != nil {
  2890. return err
  2891. }
  2892. if filters.TLSUsername != "" {
  2893. if !util.Contains(validTLSUsernames, string(filters.TLSUsername)) {
  2894. return util.NewValidationError(fmt.Sprintf("invalid TLS username: %q", filters.TLSUsername))
  2895. }
  2896. }
  2897. certs, err := validateTLSCerts(filters.TLSCerts)
  2898. if err != nil {
  2899. return err
  2900. }
  2901. filters.TLSCerts = certs
  2902. for _, opts := range filters.WebClient {
  2903. if !util.Contains(sdk.WebClientOptions, opts) {
  2904. return util.NewValidationError(fmt.Sprintf("invalid web client options %q", opts))
  2905. }
  2906. }
  2907. if filters.MaxSharesExpiration > 0 && filters.MaxSharesExpiration < filters.DefaultSharesExpiration {
  2908. return util.NewI18nError(
  2909. util.NewValidationError(fmt.Sprintf("default shares expiration: %d must be less than or equal to max shares expiration: %d",
  2910. filters.DefaultSharesExpiration, filters.MaxSharesExpiration)),
  2911. util.I18nErrorShareExpirationInvalid,
  2912. )
  2913. }
  2914. updateFiltersValues(filters)
  2915. if err := validateAccessTimeFilters(filters); err != nil {
  2916. return err
  2917. }
  2918. return validateFiltersPatternExtensions(filters)
  2919. }
  2920. func isTimeOfDayValid(value string) bool {
  2921. if len(value) != 5 {
  2922. return false
  2923. }
  2924. parts := strings.Split(value, ":")
  2925. if len(parts) != 2 {
  2926. return false
  2927. }
  2928. hour, err := strconv.Atoi(parts[0])
  2929. if err != nil {
  2930. return false
  2931. }
  2932. if hour < 0 || hour > 23 {
  2933. return false
  2934. }
  2935. minute, err := strconv.Atoi(parts[1])
  2936. if err != nil {
  2937. return false
  2938. }
  2939. if minute < 0 || minute > 59 {
  2940. return false
  2941. }
  2942. return true
  2943. }
  2944. func validateAccessTimeFilters(filters *sdk.BaseUserFilters) error {
  2945. for _, period := range filters.AccessTime {
  2946. if period.DayOfWeek < int(time.Sunday) || period.DayOfWeek > int(time.Saturday) {
  2947. return util.NewValidationError(fmt.Sprintf("invalid day of week: %d", period.DayOfWeek))
  2948. }
  2949. if !isTimeOfDayValid(period.From) || !isTimeOfDayValid(period.To) {
  2950. return util.NewI18nError(
  2951. util.NewValidationError("invalid time of day. Supported format: HH:MM"),
  2952. util.I18nErrorTimeOfDayInvalid,
  2953. )
  2954. }
  2955. if period.To <= period.From {
  2956. return util.NewI18nError(
  2957. util.NewValidationError("invalid time of day. The end time cannot be earlier than the start time"),
  2958. util.I18nErrorTimeOfDayConflict,
  2959. )
  2960. }
  2961. }
  2962. return nil
  2963. }
  2964. func validateCombinedUserFilters(user *User) error {
  2965. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
  2966. return util.NewI18nError(
  2967. util.NewValidationError("two-factor authentication cannot be disabled for a user with an active configuration"),
  2968. util.I18nErrorDisableActive2FA,
  2969. )
  2970. }
  2971. if user.Filters.RequirePasswordChange && util.Contains(user.Filters.WebClient, sdk.WebClientPasswordChangeDisabled) {
  2972. return util.NewI18nError(
  2973. util.NewValidationError("you cannot require password change and at the same time disallow it"),
  2974. util.I18nErrorPwdChangeConflict,
  2975. )
  2976. }
  2977. if len(user.Filters.TwoFactorAuthProtocols) > 0 && util.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
  2978. return util.NewI18nError(
  2979. util.NewValidationError("you cannot require two-factor authentication and at the same time disallow it"),
  2980. util.I18nError2FAConflict,
  2981. )
  2982. }
  2983. return nil
  2984. }
  2985. func validateBaseParams(user *User) error {
  2986. if user.Username == "" {
  2987. return util.NewI18nError(util.NewValidationError("username is mandatory"), util.I18nErrorUsernameRequired)
  2988. }
  2989. if err := checkReservedUsernames(user.Username); err != nil {
  2990. return util.NewI18nError(err, util.I18nErrorReservedUsername)
  2991. }
  2992. if user.Email != "" && !util.IsEmailValid(user.Email) {
  2993. return util.NewI18nError(
  2994. util.NewValidationError(fmt.Sprintf("email %q is not valid", user.Email)),
  2995. util.I18nErrorInvalidEmail,
  2996. )
  2997. }
  2998. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(user.Username) {
  2999. return util.NewI18nError(
  3000. util.NewValidationError(fmt.Sprintf("username %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", user.Username)),
  3001. util.I18nErrorInvalidUser,
  3002. )
  3003. }
  3004. if user.hasRedactedSecret() {
  3005. return util.NewValidationError("cannot save a user with a redacted secret")
  3006. }
  3007. if user.HomeDir == "" {
  3008. return util.NewI18nError(util.NewValidationError("home_dir is mandatory"), util.I18nErrorHomeRequired)
  3009. }
  3010. // we can have users with no passwords and public keys, they can authenticate via SSH user certs or OIDC
  3011. /*if user.Password == "" && len(user.PublicKeys) == 0 {
  3012. return util.NewValidationError("please set a password or at least a public_key")
  3013. }*/
  3014. if !filepath.IsAbs(user.HomeDir) {
  3015. return util.NewI18nError(
  3016. util.NewValidationError(fmt.Sprintf("home_dir must be an absolute path, actual value: %v", user.HomeDir)),
  3017. util.I18nErrorHomeInvalid,
  3018. )
  3019. }
  3020. if user.DownloadBandwidth < 0 {
  3021. user.DownloadBandwidth = 0
  3022. }
  3023. if user.UploadBandwidth < 0 {
  3024. user.UploadBandwidth = 0
  3025. }
  3026. if user.TotalDataTransfer > 0 {
  3027. // if a total data transfer is defined we reset the separate upload and download limits
  3028. user.UploadDataTransfer = 0
  3029. user.DownloadDataTransfer = 0
  3030. }
  3031. if user.Filters.IsAnonymous {
  3032. user.setAnonymousSettings()
  3033. }
  3034. err := user.FsConfig.Validate(user.GetEncryptionAdditionalData())
  3035. if err != nil {
  3036. return err
  3037. }
  3038. return nil
  3039. }
  3040. func hashPlainPassword(plainPwd string) (string, error) {
  3041. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  3042. pwd, err := bcrypt.GenerateFromPassword([]byte(plainPwd), config.PasswordHashing.BcryptOptions.Cost)
  3043. if err != nil {
  3044. return "", fmt.Errorf("bcrypt hashing error: %w", err)
  3045. }
  3046. return util.BytesToString(pwd), nil
  3047. }
  3048. pwd, err := argon2id.CreateHash(plainPwd, argon2Params)
  3049. if err != nil {
  3050. return "", fmt.Errorf("argon2ID hashing error: %w", err)
  3051. }
  3052. return pwd, nil
  3053. }
  3054. func createUserPasswordHash(user *User) error {
  3055. if user.Password != "" && !user.IsPasswordHashed() {
  3056. if minEntropy := user.getMinPasswordEntropy(); minEntropy > 0 {
  3057. if err := passwordvalidator.Validate(user.Password, minEntropy); err != nil {
  3058. return util.NewI18nError(util.NewValidationError(err.Error()), util.I18nErrorPasswordComplexity)
  3059. }
  3060. }
  3061. hashedPwd, err := hashPlainPassword(user.Password)
  3062. if err != nil {
  3063. return err
  3064. }
  3065. user.Password = hashedPwd
  3066. user.LastPasswordChange = util.GetTimeAsMsSinceEpoch(time.Now())
  3067. }
  3068. return nil
  3069. }
  3070. // ValidateFolder returns an error if the folder is not valid
  3071. // FIXME: this should be defined as Folder struct method
  3072. func ValidateFolder(folder *vfs.BaseVirtualFolder) error {
  3073. folder.FsConfig.SetEmptySecretsIfNil()
  3074. if folder.Name == "" {
  3075. return util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorNameRequired)
  3076. }
  3077. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(folder.Name) {
  3078. return util.NewI18nError(
  3079. util.NewValidationError(fmt.Sprintf("folder name %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", folder.Name)),
  3080. util.I18nErrorInvalidName,
  3081. )
  3082. }
  3083. if folder.FsConfig.Provider == sdk.LocalFilesystemProvider || folder.FsConfig.Provider == sdk.CryptedFilesystemProvider ||
  3084. folder.MappedPath != "" {
  3085. cleanedMPath := filepath.Clean(folder.MappedPath)
  3086. if !filepath.IsAbs(cleanedMPath) {
  3087. return util.NewI18nError(
  3088. util.NewValidationError(fmt.Sprintf("invalid folder mapped path %q", folder.MappedPath)),
  3089. util.I18nErrorInvalidHomeDir,
  3090. )
  3091. }
  3092. folder.MappedPath = cleanedMPath
  3093. }
  3094. if folder.HasRedactedSecret() {
  3095. return errors.New("cannot save a folder with a redacted secret")
  3096. }
  3097. return folder.FsConfig.Validate(folder.GetEncryptionAdditionalData())
  3098. }
  3099. // ValidateUser returns an error if the user is not valid
  3100. // FIXME: this should be defined as User struct method
  3101. func ValidateUser(user *User) error {
  3102. user.OIDCCustomFields = nil
  3103. user.HasPassword = false
  3104. user.SetEmptySecretsIfNil()
  3105. buildUserHomeDir(user)
  3106. if err := validateBaseParams(user); err != nil {
  3107. return err
  3108. }
  3109. if err := validateUserGroups(user); err != nil {
  3110. return err
  3111. }
  3112. if err := validatePermissions(user); err != nil {
  3113. return err
  3114. }
  3115. if err := validateUserTOTPConfig(&user.Filters.TOTPConfig, user.Username); err != nil {
  3116. return util.NewI18nError(err, util.I18nError2FAInvalid)
  3117. }
  3118. if err := validateUserRecoveryCodes(user); err != nil {
  3119. return util.NewI18nError(err, util.I18nErrorRecoveryCodesInvalid)
  3120. }
  3121. vfolders, err := validateAssociatedVirtualFolders(user.VirtualFolders)
  3122. if err != nil {
  3123. return err
  3124. }
  3125. user.VirtualFolders = vfolders
  3126. if user.Status < 0 || user.Status > 1 {
  3127. return util.NewValidationError(fmt.Sprintf("invalid user status: %v", user.Status))
  3128. }
  3129. if err := createUserPasswordHash(user); err != nil {
  3130. return err
  3131. }
  3132. if err := validatePublicKeys(user); err != nil {
  3133. return err
  3134. }
  3135. if err := validateBaseFilters(&user.Filters.BaseUserFilters); err != nil {
  3136. return err
  3137. }
  3138. if !user.HasExternalAuth() {
  3139. user.Filters.ExternalAuthCacheTime = 0
  3140. }
  3141. return validateCombinedUserFilters(user)
  3142. }
  3143. func isPasswordOK(user *User, password string) (bool, error) {
  3144. if config.PasswordCaching {
  3145. found, match := cachedUserPasswords.Check(user.Username, password, user.Password)
  3146. if found {
  3147. return match, nil
  3148. }
  3149. }
  3150. match := false
  3151. updatePwd := true
  3152. var err error
  3153. switch {
  3154. case strings.HasPrefix(user.Password, bcryptPwdPrefix):
  3155. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
  3156. return match, ErrInvalidCredentials
  3157. }
  3158. match = true
  3159. updatePwd = config.PasswordHashing.Algo != HashingAlgoBcrypt
  3160. case strings.HasPrefix(user.Password, argonPwdPrefix):
  3161. match, err = argon2id.ComparePasswordAndHash(password, user.Password)
  3162. if err != nil {
  3163. providerLog(logger.LevelError, "error comparing password with argon hash: %v", err)
  3164. return match, err
  3165. }
  3166. updatePwd = config.PasswordHashing.Algo != HashingAlgoArgon2ID
  3167. case util.IsStringPrefixInSlice(user.Password, unixPwdPrefixes):
  3168. match, err = compareUnixPasswordAndHash(user, password)
  3169. if err != nil {
  3170. return match, err
  3171. }
  3172. case util.IsStringPrefixInSlice(user.Password, pbkdfPwdPrefixes):
  3173. match, err = comparePbkdf2PasswordAndHash(password, user.Password)
  3174. if err != nil {
  3175. return match, err
  3176. }
  3177. case util.IsStringPrefixInSlice(user.Password, digestPwdPrefixes):
  3178. match = compareDigestPasswordAndHash(user, password)
  3179. }
  3180. if err == nil && match {
  3181. cachedUserPasswords.Add(user.Username, password, user.Password)
  3182. if updatePwd {
  3183. convertUserPassword(user.Username, password)
  3184. }
  3185. }
  3186. return match, err
  3187. }
  3188. func convertUserPassword(username, plainPwd string) {
  3189. hashedPwd, err := hashPlainPassword(plainPwd)
  3190. if err == nil {
  3191. err = provider.updateUserPassword(username, hashedPwd)
  3192. }
  3193. if err != nil {
  3194. providerLog(logger.LevelWarn, "unable to convert password for user %s: %v", username, err)
  3195. } else {
  3196. providerLog(logger.LevelDebug, "password converted for user %s", username)
  3197. }
  3198. }
  3199. func checkUserAndTLSCertificate(user *User, protocol string, tlsCert *x509.Certificate) (User, error) {
  3200. err := user.LoadAndApplyGroupSettings()
  3201. if err != nil {
  3202. return *user, err
  3203. }
  3204. err = user.CheckLoginConditions()
  3205. if err != nil {
  3206. return *user, err
  3207. }
  3208. switch protocol {
  3209. case protocolFTP, protocolWebDAV:
  3210. for _, cert := range user.Filters.TLSCerts {
  3211. derBlock, _ := pem.Decode(util.StringToBytes(cert))
  3212. if derBlock != nil && bytes.Equal(derBlock.Bytes, tlsCert.Raw) {
  3213. return *user, nil
  3214. }
  3215. }
  3216. if user.Filters.TLSUsername == sdk.TLSUsernameCN {
  3217. if user.Username == tlsCert.Subject.CommonName {
  3218. return *user, nil
  3219. }
  3220. return *user, fmt.Errorf("CN %q does not match username %q", tlsCert.Subject.CommonName, user.Username)
  3221. }
  3222. return *user, errors.New("TLS certificate is not valid")
  3223. default:
  3224. return *user, fmt.Errorf("certificate authentication is not supported for protocol %v", protocol)
  3225. }
  3226. }
  3227. func checkUserAndPass(user *User, password, ip, protocol string) (User, error) {
  3228. err := user.LoadAndApplyGroupSettings()
  3229. if err != nil {
  3230. return *user, err
  3231. }
  3232. err = user.CheckLoginConditions()
  3233. if err != nil {
  3234. return *user, err
  3235. }
  3236. if protocol != protocolHTTP && user.MustChangePassword() {
  3237. return *user, errors.New("login not allowed, password change required")
  3238. }
  3239. if user.Filters.IsAnonymous {
  3240. user.setAnonymousSettings()
  3241. return *user, nil
  3242. }
  3243. password, err = checkUserPasscode(user, password, protocol)
  3244. if err != nil {
  3245. return *user, ErrInvalidCredentials
  3246. }
  3247. if user.Password == "" || password == "" {
  3248. return *user, errors.New("credentials cannot be null or empty")
  3249. }
  3250. if !user.Filters.Hooks.CheckPasswordDisabled {
  3251. hookResponse, err := executeCheckPasswordHook(user.Username, password, ip, protocol)
  3252. if err != nil {
  3253. providerLog(logger.LevelDebug, "error executing check password hook for user %q, ip %v, protocol %v: %v",
  3254. user.Username, ip, protocol, err)
  3255. return *user, errors.New("unable to check credentials")
  3256. }
  3257. switch hookResponse.Status {
  3258. case -1:
  3259. // no hook configured
  3260. case 1:
  3261. providerLog(logger.LevelDebug, "password accepted by check password hook for user %q, ip %v, protocol %v",
  3262. user.Username, ip, protocol)
  3263. return *user, nil
  3264. case 2:
  3265. providerLog(logger.LevelDebug, "partial success from check password hook for user %q, ip %v, protocol %v",
  3266. user.Username, ip, protocol)
  3267. password = hookResponse.ToVerify
  3268. default:
  3269. providerLog(logger.LevelDebug, "password rejected by check password hook for user %q, ip %v, protocol %v, status: %v",
  3270. user.Username, ip, protocol, hookResponse.Status)
  3271. return *user, ErrInvalidCredentials
  3272. }
  3273. }
  3274. match, err := isPasswordOK(user, password)
  3275. if !match {
  3276. err = ErrInvalidCredentials
  3277. }
  3278. return *user, err
  3279. }
  3280. func checkUserPasscode(user *User, password, protocol string) (string, error) {
  3281. if user.Filters.TOTPConfig.Enabled {
  3282. switch protocol {
  3283. case protocolFTP:
  3284. if util.Contains(user.Filters.TOTPConfig.Protocols, protocol) {
  3285. // the TOTP passcode has six digits
  3286. pwdLen := len(password)
  3287. if pwdLen < 7 {
  3288. providerLog(logger.LevelDebug, "password len %v is too short to contain a passcode, user %q, protocol %v",
  3289. pwdLen, user.Username, protocol)
  3290. return "", util.NewValidationError("password too short, cannot contain the passcode")
  3291. }
  3292. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3293. if err != nil {
  3294. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3295. user.Username, protocol, err)
  3296. return "", err
  3297. }
  3298. pwd := password[0:(pwdLen - 6)]
  3299. passcode := password[(pwdLen - 6):]
  3300. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  3301. user.Filters.TOTPConfig.Secret.GetPayload())
  3302. if !match || err != nil {
  3303. providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
  3304. user.Username, protocol, err)
  3305. return "", util.NewValidationError("invalid passcode")
  3306. }
  3307. return pwd, nil
  3308. }
  3309. }
  3310. }
  3311. return password, nil
  3312. }
  3313. func checkUserAndPubKey(user *User, pubKey []byte, isSSHCert bool) (User, string, error) {
  3314. err := user.LoadAndApplyGroupSettings()
  3315. if err != nil {
  3316. return *user, "", err
  3317. }
  3318. err = user.CheckLoginConditions()
  3319. if err != nil {
  3320. return *user, "", err
  3321. }
  3322. if isSSHCert {
  3323. return *user, "", nil
  3324. }
  3325. if len(user.PublicKeys) == 0 {
  3326. return *user, "", ErrInvalidCredentials
  3327. }
  3328. for idx, key := range user.PublicKeys {
  3329. storedKey, comment, _, _, err := ssh.ParseAuthorizedKey(util.StringToBytes(key))
  3330. if err != nil {
  3331. providerLog(logger.LevelError, "error parsing stored public key %d for user %s: %v", idx, user.Username, err)
  3332. return *user, "", err
  3333. }
  3334. if bytes.Equal(storedKey.Marshal(), pubKey) {
  3335. return *user, fmt.Sprintf("%s:%s", ssh.FingerprintSHA256(storedKey), comment), nil
  3336. }
  3337. }
  3338. return *user, "", ErrInvalidCredentials
  3339. }
  3340. func compareDigestPasswordAndHash(user *User, password string) bool {
  3341. if strings.HasPrefix(user.Password, md5DigestPwdPrefix) {
  3342. h := md5.New()
  3343. h.Write([]byte(password))
  3344. return fmt.Sprintf("%s%x", md5DigestPwdPrefix, h.Sum(nil)) == user.Password
  3345. }
  3346. if strings.HasPrefix(user.Password, sha256DigestPwdPrefix) {
  3347. h := sha256.New()
  3348. h.Write([]byte(password))
  3349. return fmt.Sprintf("%s%x", sha256DigestPwdPrefix, h.Sum(nil)) == user.Password
  3350. }
  3351. if strings.HasPrefix(user.Password, sha512DigestPwdPrefix) {
  3352. h := sha512.New()
  3353. h.Write([]byte(password))
  3354. return fmt.Sprintf("%s%x", sha512DigestPwdPrefix, h.Sum(nil)) == user.Password
  3355. }
  3356. return false
  3357. }
  3358. func compareUnixPasswordAndHash(user *User, password string) (bool, error) {
  3359. if strings.HasPrefix(user.Password, yescryptPwdPrefix) {
  3360. return compareYescryptPassword(user.Password, password)
  3361. }
  3362. var crypter crypt.Crypter
  3363. if strings.HasPrefix(user.Password, sha512cryptPwdPrefix) {
  3364. crypter = sha512_crypt.New()
  3365. } else if strings.HasPrefix(user.Password, sha256cryptPwdPrefix) {
  3366. crypter = sha256_crypt.New()
  3367. } else if strings.HasPrefix(user.Password, md5cryptPwdPrefix) {
  3368. crypter = md5_crypt.New()
  3369. } else if strings.HasPrefix(user.Password, md5cryptApr1PwdPrefix) {
  3370. crypter = apr1_crypt.New()
  3371. } else {
  3372. return false, errors.New("unix crypt: invalid or unsupported hash format")
  3373. }
  3374. if err := crypter.Verify(user.Password, []byte(password)); err != nil {
  3375. return false, err
  3376. }
  3377. return true, nil
  3378. }
  3379. func comparePbkdf2PasswordAndHash(password, hashedPassword string) (bool, error) {
  3380. vals := strings.Split(hashedPassword, "$")
  3381. if len(vals) != 5 {
  3382. return false, fmt.Errorf("pbkdf2: hash is not in the correct format")
  3383. }
  3384. iterations, err := strconv.Atoi(vals[2])
  3385. if err != nil {
  3386. return false, err
  3387. }
  3388. expected, err := base64.StdEncoding.DecodeString(vals[4])
  3389. if err != nil {
  3390. return false, err
  3391. }
  3392. var salt []byte
  3393. if util.IsStringPrefixInSlice(hashedPassword, pbkdfPwdB64SaltPrefixes) {
  3394. salt, err = base64.StdEncoding.DecodeString(vals[3])
  3395. if err != nil {
  3396. return false, err
  3397. }
  3398. } else {
  3399. salt = []byte(vals[3])
  3400. }
  3401. var hashFunc func() hash.Hash
  3402. if strings.HasPrefix(hashedPassword, pbkdf2SHA256Prefix) || strings.HasPrefix(hashedPassword, pbkdf2SHA256B64SaltPrefix) {
  3403. hashFunc = sha256.New
  3404. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA512Prefix) {
  3405. hashFunc = sha512.New
  3406. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA1Prefix) {
  3407. hashFunc = sha1.New
  3408. } else {
  3409. return false, fmt.Errorf("pbkdf2: invalid or unsupported hash format %v", vals[1])
  3410. }
  3411. df := pbkdf2.Key([]byte(password), salt, iterations, len(expected), hashFunc)
  3412. return subtle.ConstantTimeCompare(df, expected) == 1, nil
  3413. }
  3414. func getSSLMode() string {
  3415. if config.Driver == PGSQLDataProviderName || config.Driver == CockroachDataProviderName {
  3416. switch config.SSLMode {
  3417. case 0:
  3418. return "disable"
  3419. case 1:
  3420. return "require"
  3421. case 2:
  3422. return "verify-ca"
  3423. case 3:
  3424. return "verify-full"
  3425. case 4:
  3426. return "prefer"
  3427. case 5:
  3428. return "allow"
  3429. }
  3430. } else if config.Driver == MySQLDataProviderName {
  3431. if config.requireCustomTLSForMySQL() {
  3432. return "custom"
  3433. }
  3434. switch config.SSLMode {
  3435. case 0:
  3436. return "false"
  3437. case 1:
  3438. return "true"
  3439. case 2:
  3440. return "skip-verify"
  3441. case 3:
  3442. return "preferred"
  3443. }
  3444. }
  3445. return ""
  3446. }
  3447. func terminateInteractiveAuthProgram(cmd *exec.Cmd, isFinished bool) {
  3448. if isFinished {
  3449. return
  3450. }
  3451. providerLog(logger.LevelInfo, "kill interactive auth program after an unexpected error")
  3452. err := cmd.Process.Kill()
  3453. if err != nil {
  3454. providerLog(logger.LevelDebug, "error killing interactive auth program: %v", err)
  3455. }
  3456. }
  3457. func sendKeyboardAuthHTTPReq(url string, request *plugin.KeyboardAuthRequest) (*plugin.KeyboardAuthResponse, error) {
  3458. reqAsJSON, err := json.Marshal(request)
  3459. if err != nil {
  3460. providerLog(logger.LevelError, "error serializing keyboard interactive auth request: %v", err)
  3461. return nil, err
  3462. }
  3463. resp, err := httpclient.Post(url, "application/json", bytes.NewBuffer(reqAsJSON))
  3464. if err != nil {
  3465. providerLog(logger.LevelError, "error getting keyboard interactive auth hook HTTP response: %v", err)
  3466. return nil, err
  3467. }
  3468. defer resp.Body.Close()
  3469. if resp.StatusCode != http.StatusOK {
  3470. return nil, fmt.Errorf("wrong keyboard interactive auth http status code: %v, expected 200", resp.StatusCode)
  3471. }
  3472. var response plugin.KeyboardAuthResponse
  3473. err = render.DecodeJSON(resp.Body, &response)
  3474. return &response, err
  3475. }
  3476. func doBuiltinKeyboardInteractiveAuth(user *User, client ssh.KeyboardInteractiveChallenge,
  3477. ip, protocol string, isPartialAuth bool,
  3478. ) (int, error) {
  3479. if err := user.LoadAndApplyGroupSettings(); err != nil {
  3480. return 0, err
  3481. }
  3482. hasSecondFactor := user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH)
  3483. if !isPartialAuth || !hasSecondFactor {
  3484. answers, err := client("", "", []string{"Password: "}, []bool{false})
  3485. if err != nil {
  3486. return 0, err
  3487. }
  3488. if len(answers) != 1 {
  3489. return 0, fmt.Errorf("unexpected number of answers: %d", len(answers))
  3490. }
  3491. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  3492. if err != nil {
  3493. return 0, err
  3494. }
  3495. }
  3496. return checkKeyboardInteractiveSecondFactor(user, client, protocol)
  3497. }
  3498. func checkKeyboardInteractiveSecondFactor(user *User, client ssh.KeyboardInteractiveChallenge, protocol string) (int, error) {
  3499. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
  3500. return 1, nil
  3501. }
  3502. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3503. if err != nil {
  3504. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3505. user.Username, protocol, err)
  3506. return 0, err
  3507. }
  3508. answers, err := client("", "", []string{"Authentication code: "}, []bool{false})
  3509. if err != nil {
  3510. return 0, err
  3511. }
  3512. if len(answers) != 1 {
  3513. return 0, fmt.Errorf("unexpected number of answers: %v", len(answers))
  3514. }
  3515. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  3516. user.Filters.TOTPConfig.Secret.GetPayload())
  3517. if !match || err != nil {
  3518. providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
  3519. user.Username, protocol, err)
  3520. return 0, util.NewValidationError("invalid passcode")
  3521. }
  3522. return 1, nil
  3523. }
  3524. func executeKeyboardInteractivePlugin(user *User, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3525. authResult := 0
  3526. requestID := xid.New().String()
  3527. authStep := 1
  3528. req := &plugin.KeyboardAuthRequest{
  3529. Username: user.Username,
  3530. IP: ip,
  3531. Password: user.Password,
  3532. RequestID: requestID,
  3533. Step: authStep,
  3534. }
  3535. var response *plugin.KeyboardAuthResponse
  3536. var err error
  3537. for {
  3538. response, err = plugin.Handler.ExecuteKeyboardInteractiveStep(req)
  3539. if err != nil {
  3540. return authResult, err
  3541. }
  3542. if response.AuthResult != 0 {
  3543. return response.AuthResult, err
  3544. }
  3545. if err = response.Validate(); err != nil {
  3546. providerLog(logger.LevelInfo, "invalid response from keyboard interactive plugin: %v", err)
  3547. return authResult, err
  3548. }
  3549. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3550. if err != nil {
  3551. return authResult, err
  3552. }
  3553. authStep++
  3554. req = &plugin.KeyboardAuthRequest{
  3555. RequestID: requestID,
  3556. Step: authStep,
  3557. Username: user.Username,
  3558. Password: user.Password,
  3559. Answers: answers,
  3560. Questions: response.Questions,
  3561. }
  3562. }
  3563. }
  3564. func executeKeyboardInteractiveHTTPHook(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3565. authResult := 0
  3566. requestID := xid.New().String()
  3567. authStep := 1
  3568. req := &plugin.KeyboardAuthRequest{
  3569. Username: user.Username,
  3570. IP: ip,
  3571. Password: user.Password,
  3572. RequestID: requestID,
  3573. Step: authStep,
  3574. }
  3575. var response *plugin.KeyboardAuthResponse
  3576. var err error
  3577. for {
  3578. response, err = sendKeyboardAuthHTTPReq(authHook, req)
  3579. if err != nil {
  3580. return authResult, err
  3581. }
  3582. if response.AuthResult != 0 {
  3583. return response.AuthResult, err
  3584. }
  3585. if err = response.Validate(); err != nil {
  3586. providerLog(logger.LevelInfo, "invalid response from keyboard interactive http hook: %v", err)
  3587. return authResult, err
  3588. }
  3589. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3590. if err != nil {
  3591. return authResult, err
  3592. }
  3593. authStep++
  3594. req = &plugin.KeyboardAuthRequest{
  3595. RequestID: requestID,
  3596. Step: authStep,
  3597. Username: user.Username,
  3598. Password: user.Password,
  3599. Answers: answers,
  3600. Questions: response.Questions,
  3601. }
  3602. }
  3603. }
  3604. func getKeyboardInteractiveAnswers(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  3605. user *User, ip, protocol string,
  3606. ) ([]string, error) {
  3607. questions := response.Questions
  3608. answers, err := client("", response.Instruction, questions, response.Echos)
  3609. if err != nil {
  3610. providerLog(logger.LevelInfo, "error getting interactive auth client response: %v", err)
  3611. return answers, err
  3612. }
  3613. if len(answers) != len(questions) {
  3614. err = fmt.Errorf("client answers does not match questions, expected: %v actual: %v", questions, answers)
  3615. providerLog(logger.LevelInfo, "keyboard interactive auth error: %v", err)
  3616. return answers, err
  3617. }
  3618. if len(answers) == 1 && response.CheckPwd > 0 {
  3619. if response.CheckPwd == 2 {
  3620. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
  3621. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to check TOTP passcode, TOTP is not enabled for user %q",
  3622. user.Username)
  3623. return answers, errors.New("TOTP not enabled for SSH protocol")
  3624. }
  3625. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3626. if err != nil {
  3627. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3628. user.Username, protocol, err)
  3629. return answers, fmt.Errorf("unable to decrypt TOTP secret: %w", err)
  3630. }
  3631. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  3632. user.Filters.TOTPConfig.Secret.GetPayload())
  3633. if !match || err != nil {
  3634. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to validate passcode for user %q, match? %v, err: %v",
  3635. user.Username, match, err)
  3636. return answers, errors.New("unable to validate TOTP passcode")
  3637. }
  3638. } else {
  3639. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  3640. providerLog(logger.LevelInfo, "interactive auth hook requested password validation for user %q, validation error: %v",
  3641. user.Username, err)
  3642. if err != nil {
  3643. return answers, err
  3644. }
  3645. }
  3646. answers[0] = "OK"
  3647. }
  3648. return answers, err
  3649. }
  3650. func handleProgramInteractiveQuestions(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  3651. user *User, stdin io.WriteCloser, ip, protocol string,
  3652. ) error {
  3653. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3654. if err != nil {
  3655. return err
  3656. }
  3657. for _, answer := range answers {
  3658. if runtime.GOOS == "windows" {
  3659. answer += "\r"
  3660. }
  3661. answer += "\n"
  3662. _, err = stdin.Write([]byte(answer))
  3663. if err != nil {
  3664. providerLog(logger.LevelError, "unable to write client answer to keyboard interactive program: %v", err)
  3665. return err
  3666. }
  3667. }
  3668. return nil
  3669. }
  3670. func executeKeyboardInteractiveProgram(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3671. authResult := 0
  3672. timeout, env, args := command.GetConfig(authHook, command.HookKeyboardInteractive)
  3673. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3674. defer cancel()
  3675. cmd := exec.CommandContext(ctx, authHook, args...)
  3676. cmd.Env = append(env,
  3677. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", user.Username),
  3678. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  3679. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", user.Password))
  3680. stdout, err := cmd.StdoutPipe()
  3681. if err != nil {
  3682. return authResult, err
  3683. }
  3684. stdin, err := cmd.StdinPipe()
  3685. if err != nil {
  3686. return authResult, err
  3687. }
  3688. err = cmd.Start()
  3689. if err != nil {
  3690. return authResult, err
  3691. }
  3692. var once sync.Once
  3693. scanner := bufio.NewScanner(stdout)
  3694. for scanner.Scan() {
  3695. var response plugin.KeyboardAuthResponse
  3696. err = json.Unmarshal(scanner.Bytes(), &response)
  3697. if err != nil {
  3698. providerLog(logger.LevelInfo, "interactive auth error parsing response: %v", err)
  3699. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3700. break
  3701. }
  3702. if response.AuthResult != 0 {
  3703. authResult = response.AuthResult
  3704. break
  3705. }
  3706. if err = response.Validate(); err != nil {
  3707. providerLog(logger.LevelInfo, "invalid response from keyboard interactive program: %v", err)
  3708. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3709. break
  3710. }
  3711. go func() {
  3712. err := handleProgramInteractiveQuestions(client, &response, user, stdin, ip, protocol)
  3713. if err != nil {
  3714. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3715. }
  3716. }()
  3717. }
  3718. stdin.Close()
  3719. once.Do(func() { terminateInteractiveAuthProgram(cmd, true) })
  3720. go func() {
  3721. _, err := cmd.Process.Wait()
  3722. if err != nil {
  3723. providerLog(logger.LevelWarn, "error waiting for %q process to exit: %v", authHook, err)
  3724. }
  3725. }()
  3726. return authResult, err
  3727. }
  3728. func doKeyboardInteractiveAuth(user *User, authHook string, client ssh.KeyboardInteractiveChallenge,
  3729. ip, protocol string, isPartialAuth bool,
  3730. ) (User, error) {
  3731. if err := user.LoadAndApplyGroupSettings(); err != nil {
  3732. return *user, err
  3733. }
  3734. var authResult int
  3735. var err error
  3736. if !user.Filters.Hooks.ExternalAuthDisabled {
  3737. if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
  3738. authResult, err = executeKeyboardInteractivePlugin(user, client, ip, protocol)
  3739. if authResult == 1 && err == nil {
  3740. authResult, err = checkKeyboardInteractiveSecondFactor(user, client, protocol)
  3741. }
  3742. } else if authHook != "" {
  3743. if strings.HasPrefix(authHook, "http") {
  3744. authResult, err = executeKeyboardInteractiveHTTPHook(user, authHook, client, ip, protocol)
  3745. } else {
  3746. authResult, err = executeKeyboardInteractiveProgram(user, authHook, client, ip, protocol)
  3747. }
  3748. } else {
  3749. authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
  3750. }
  3751. } else {
  3752. authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
  3753. }
  3754. if err != nil {
  3755. return *user, err
  3756. }
  3757. if authResult != 1 {
  3758. return *user, fmt.Errorf("keyboard interactive auth failed, result: %v", authResult)
  3759. }
  3760. err = user.CheckLoginConditions()
  3761. if err != nil {
  3762. return *user, err
  3763. }
  3764. return *user, nil
  3765. }
  3766. func isCheckPasswordHookDefined(protocol string) bool {
  3767. if config.CheckPasswordHook == "" {
  3768. return false
  3769. }
  3770. if config.CheckPasswordScope == 0 {
  3771. return true
  3772. }
  3773. switch protocol {
  3774. case protocolSSH:
  3775. return config.CheckPasswordScope&1 != 0
  3776. case protocolFTP:
  3777. return config.CheckPasswordScope&2 != 0
  3778. case protocolWebDAV:
  3779. return config.CheckPasswordScope&4 != 0
  3780. default:
  3781. return false
  3782. }
  3783. }
  3784. func getPasswordHookResponse(username, password, ip, protocol string) ([]byte, error) {
  3785. if strings.HasPrefix(config.CheckPasswordHook, "http") {
  3786. var result []byte
  3787. req := checkPasswordRequest{
  3788. Username: username,
  3789. Password: password,
  3790. IP: ip,
  3791. Protocol: protocol,
  3792. }
  3793. reqAsJSON, err := json.Marshal(req)
  3794. if err != nil {
  3795. return result, err
  3796. }
  3797. resp, err := httpclient.Post(config.CheckPasswordHook, "application/json", bytes.NewBuffer(reqAsJSON))
  3798. if err != nil {
  3799. providerLog(logger.LevelError, "error getting check password hook response: %v", err)
  3800. return result, err
  3801. }
  3802. defer resp.Body.Close()
  3803. if resp.StatusCode != http.StatusOK {
  3804. return result, fmt.Errorf("wrong http status code from chek password hook: %v, expected 200", resp.StatusCode)
  3805. }
  3806. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  3807. }
  3808. timeout, env, args := command.GetConfig(config.CheckPasswordHook, command.HookCheckPassword)
  3809. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3810. defer cancel()
  3811. cmd := exec.CommandContext(ctx, config.CheckPasswordHook, args...)
  3812. cmd.Env = append(env,
  3813. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
  3814. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
  3815. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  3816. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
  3817. )
  3818. return cmd.Output()
  3819. }
  3820. func executeCheckPasswordHook(username, password, ip, protocol string) (checkPasswordResponse, error) {
  3821. var response checkPasswordResponse
  3822. if !isCheckPasswordHookDefined(protocol) {
  3823. response.Status = -1
  3824. return response, nil
  3825. }
  3826. startTime := time.Now()
  3827. out, err := getPasswordHookResponse(username, password, ip, protocol)
  3828. providerLog(logger.LevelDebug, "check password hook executed, error: %v, elapsed: %v", err, time.Since(startTime))
  3829. if err != nil {
  3830. return response, err
  3831. }
  3832. err = json.Unmarshal(out, &response)
  3833. return response, err
  3834. }
  3835. func getPreLoginHookResponse(loginMethod, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  3836. if strings.HasPrefix(config.PreLoginHook, "http") {
  3837. var url *url.URL
  3838. var result []byte
  3839. url, err := url.Parse(config.PreLoginHook)
  3840. if err != nil {
  3841. providerLog(logger.LevelError, "invalid url for pre-login hook %q, error: %v", config.PreLoginHook, err)
  3842. return result, err
  3843. }
  3844. q := url.Query()
  3845. q.Add("login_method", loginMethod)
  3846. q.Add("ip", ip)
  3847. q.Add("protocol", protocol)
  3848. url.RawQuery = q.Encode()
  3849. resp, err := httpclient.Post(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  3850. if err != nil {
  3851. providerLog(logger.LevelWarn, "error getting pre-login hook response: %v", err)
  3852. return result, err
  3853. }
  3854. defer resp.Body.Close()
  3855. if resp.StatusCode == http.StatusNoContent {
  3856. return result, nil
  3857. }
  3858. if resp.StatusCode != http.StatusOK {
  3859. return result, fmt.Errorf("wrong pre-login hook http status code: %v, expected 200", resp.StatusCode)
  3860. }
  3861. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  3862. }
  3863. timeout, env, args := command.GetConfig(config.PreLoginHook, command.HookPreLogin)
  3864. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3865. defer cancel()
  3866. cmd := exec.CommandContext(ctx, config.PreLoginHook, args...)
  3867. cmd.Env = append(env,
  3868. fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
  3869. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
  3870. fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
  3871. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol),
  3872. )
  3873. return cmd.Output()
  3874. }
  3875. func executePreLoginHook(username, loginMethod, ip, protocol string, oidcTokenFields *map[string]any) (User, error) {
  3876. u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, oidcTokenFields)
  3877. if err != nil {
  3878. return u, err
  3879. }
  3880. if mergedUser.Filters.Hooks.PreLoginDisabled {
  3881. return u, nil
  3882. }
  3883. startTime := time.Now()
  3884. out, err := getPreLoginHookResponse(loginMethod, ip, protocol, userAsJSON)
  3885. if err != nil {
  3886. return u, fmt.Errorf("pre-login hook error: %v, username %q, ip %v, protocol %v elapsed %v",
  3887. err, username, ip, protocol, time.Since(startTime))
  3888. }
  3889. providerLog(logger.LevelDebug, "pre-login hook completed, elapsed: %s", time.Since(startTime))
  3890. if util.IsByteArrayEmpty(out) {
  3891. providerLog(logger.LevelDebug, "empty response from pre-login hook, no modification requested for user %q id: %d",
  3892. username, u.ID)
  3893. if u.ID == 0 {
  3894. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  3895. }
  3896. return u, nil
  3897. }
  3898. userID := u.ID
  3899. userUsedQuotaSize := u.UsedQuotaSize
  3900. userUsedQuotaFiles := u.UsedQuotaFiles
  3901. userUsedDownloadTransfer := u.UsedDownloadDataTransfer
  3902. userUsedUploadTransfer := u.UsedUploadDataTransfer
  3903. userLastQuotaUpdate := u.LastQuotaUpdate
  3904. userLastLogin := u.LastLogin
  3905. userFirstDownload := u.FirstDownload
  3906. userFirstUpload := u.FirstUpload
  3907. userLastPwdChange := u.LastPasswordChange
  3908. userCreatedAt := u.CreatedAt
  3909. totpConfig := u.Filters.TOTPConfig
  3910. recoveryCodes := u.Filters.RecoveryCodes
  3911. err = json.Unmarshal(out, &u)
  3912. if err != nil {
  3913. return u, fmt.Errorf("invalid pre-login hook response %q, error: %v", util.BytesToString(out), err)
  3914. }
  3915. u.ID = userID
  3916. u.UsedQuotaSize = userUsedQuotaSize
  3917. u.UsedQuotaFiles = userUsedQuotaFiles
  3918. u.UsedUploadDataTransfer = userUsedUploadTransfer
  3919. u.UsedDownloadDataTransfer = userUsedDownloadTransfer
  3920. u.LastQuotaUpdate = userLastQuotaUpdate
  3921. u.LastLogin = userLastLogin
  3922. u.LastPasswordChange = userLastPwdChange
  3923. u.FirstDownload = userFirstDownload
  3924. u.FirstUpload = userFirstUpload
  3925. u.CreatedAt = userCreatedAt
  3926. if userID == 0 {
  3927. err = provider.addUser(&u)
  3928. } else {
  3929. u.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  3930. // preserve TOTP config and recovery codes
  3931. u.Filters.TOTPConfig = totpConfig
  3932. u.Filters.RecoveryCodes = recoveryCodes
  3933. err = provider.updateUser(&u)
  3934. if err == nil {
  3935. webDAVUsersCache.swap(&u, "")
  3936. }
  3937. }
  3938. if err != nil {
  3939. return u, err
  3940. }
  3941. providerLog(logger.LevelDebug, "user %q added/updated from pre-login hook response, id: %d", username, userID)
  3942. if userID == 0 {
  3943. return provider.userExists(username, "")
  3944. }
  3945. return u, nil
  3946. }
  3947. // ExecutePostLoginHook executes the post login hook if defined
  3948. func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error) {
  3949. if config.PostLoginHook == "" {
  3950. return
  3951. }
  3952. if config.PostLoginScope == 1 && err == nil {
  3953. return
  3954. }
  3955. if config.PostLoginScope == 2 && err != nil {
  3956. return
  3957. }
  3958. go func() {
  3959. actionsConcurrencyGuard <- struct{}{}
  3960. defer func() {
  3961. <-actionsConcurrencyGuard
  3962. }()
  3963. status := "0"
  3964. if err == nil {
  3965. status = "1"
  3966. }
  3967. user.PrepareForRendering()
  3968. userAsJSON, err := json.Marshal(user)
  3969. if err != nil {
  3970. providerLog(logger.LevelError, "error serializing user in post login hook: %v", err)
  3971. return
  3972. }
  3973. if strings.HasPrefix(config.PostLoginHook, "http") {
  3974. var url *url.URL
  3975. url, err := url.Parse(config.PostLoginHook)
  3976. if err != nil {
  3977. providerLog(logger.LevelDebug, "Invalid post-login hook %q", config.PostLoginHook)
  3978. return
  3979. }
  3980. q := url.Query()
  3981. q.Add("login_method", loginMethod)
  3982. q.Add("ip", ip)
  3983. q.Add("protocol", protocol)
  3984. q.Add("status", status)
  3985. url.RawQuery = q.Encode()
  3986. startTime := time.Now()
  3987. respCode := 0
  3988. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  3989. if err == nil {
  3990. respCode = resp.StatusCode
  3991. resp.Body.Close()
  3992. }
  3993. providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, response code: %v, elapsed: %v err: %v",
  3994. user.Username, ip, protocol, respCode, time.Since(startTime), err)
  3995. return
  3996. }
  3997. timeout, env, args := command.GetConfig(config.PostLoginHook, command.HookPostLogin)
  3998. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3999. defer cancel()
  4000. cmd := exec.CommandContext(ctx, config.PostLoginHook, args...)
  4001. cmd.Env = append(env,
  4002. fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
  4003. fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
  4004. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
  4005. fmt.Sprintf("SFTPGO_LOGIND_STATUS=%s", status),
  4006. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol))
  4007. startTime := time.Now()
  4008. err = cmd.Run()
  4009. providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, elapsed %v err: %v",
  4010. user.Username, ip, protocol, time.Since(startTime), err)
  4011. }()
  4012. }
  4013. func getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol string, cert *x509.Certificate,
  4014. user User,
  4015. ) ([]byte, error) {
  4016. var tlsCert string
  4017. if cert != nil {
  4018. var err error
  4019. tlsCert, err = util.EncodeTLSCertToPem(cert)
  4020. if err != nil {
  4021. return nil, err
  4022. }
  4023. }
  4024. if strings.HasPrefix(config.ExternalAuthHook, "http") {
  4025. var result []byte
  4026. authRequest := make(map[string]any)
  4027. authRequest["username"] = username
  4028. authRequest["ip"] = ip
  4029. authRequest["password"] = password
  4030. authRequest["public_key"] = pkey
  4031. authRequest["protocol"] = protocol
  4032. authRequest["keyboard_interactive"] = keyboardInteractive
  4033. authRequest["tls_cert"] = tlsCert
  4034. if user.ID > 0 {
  4035. authRequest["user"] = user
  4036. }
  4037. authRequestAsJSON, err := json.Marshal(authRequest)
  4038. if err != nil {
  4039. providerLog(logger.LevelError, "error serializing external auth request: %v", err)
  4040. return result, err
  4041. }
  4042. resp, err := httpclient.Post(config.ExternalAuthHook, "application/json", bytes.NewBuffer(authRequestAsJSON))
  4043. if err != nil {
  4044. providerLog(logger.LevelWarn, "error getting external auth hook HTTP response: %v", err)
  4045. return result, err
  4046. }
  4047. defer resp.Body.Close()
  4048. providerLog(logger.LevelDebug, "external auth hook executed, response code: %v", resp.StatusCode)
  4049. if resp.StatusCode != http.StatusOK {
  4050. return result, fmt.Errorf("wrong external auth http status code: %v, expected 200", resp.StatusCode)
  4051. }
  4052. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  4053. }
  4054. var userAsJSON []byte
  4055. var err error
  4056. if user.ID > 0 {
  4057. userAsJSON, err = json.Marshal(user)
  4058. if err != nil {
  4059. return nil, fmt.Errorf("unable to serialize user as JSON: %w", err)
  4060. }
  4061. }
  4062. timeout, env, args := command.GetConfig(config.ExternalAuthHook, command.HookExternalAuth)
  4063. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  4064. defer cancel()
  4065. cmd := exec.CommandContext(ctx, config.ExternalAuthHook, args...)
  4066. cmd.Env = append(env,
  4067. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
  4068. fmt.Sprintf("SFTPGO_AUTHD_USER=%s", util.BytesToString(userAsJSON)),
  4069. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  4070. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
  4071. fmt.Sprintf("SFTPGO_AUTHD_PUBLIC_KEY=%s", pkey),
  4072. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
  4073. fmt.Sprintf("SFTPGO_AUTHD_TLS_CERT=%s", strings.ReplaceAll(tlsCert, "\n", "\\n")),
  4074. fmt.Sprintf("SFTPGO_AUTHD_KEYBOARD_INTERACTIVE=%v", keyboardInteractive))
  4075. return cmd.Output()
  4076. }
  4077. func updateUserFromExtAuthResponse(user *User, password, pkey string) {
  4078. if password != "" {
  4079. user.Password = password
  4080. }
  4081. if pkey != "" && !util.IsStringPrefixInSlice(pkey, user.PublicKeys) {
  4082. user.PublicKeys = append(user.PublicKeys, pkey)
  4083. }
  4084. user.LastPasswordChange = 0
  4085. }
  4086. func checkPasswordAfterEmptyExtAuthResponse(user *User, plainPwd, protocol string) error {
  4087. if plainPwd == "" {
  4088. return nil
  4089. }
  4090. match, err := isPasswordOK(user, plainPwd)
  4091. if match && err == nil {
  4092. return nil
  4093. }
  4094. hashedPwd, err := hashPlainPassword(plainPwd)
  4095. if err != nil {
  4096. providerLog(logger.LevelError, "unable to hash password for user %q after empty external response: %v",
  4097. user.Username, err)
  4098. return err
  4099. }
  4100. err = provider.updateUserPassword(user.Username, hashedPwd)
  4101. if err != nil {
  4102. providerLog(logger.LevelError, "unable to update password for user %q after empty external response: %v",
  4103. user.Username, err)
  4104. }
  4105. user.Password = hashedPwd
  4106. cachedUserPasswords.Add(user.Username, plainPwd, user.Password)
  4107. if protocol != protocolWebDAV {
  4108. webDAVUsersCache.swap(user, plainPwd)
  4109. }
  4110. providerLog(logger.LevelDebug, "updated password for user %q after empty external auth response", user.Username)
  4111. return nil
  4112. }
  4113. func doExternalAuth(username, password string, pubKey []byte, keyboardInteractive, ip, protocol string,
  4114. tlsCert *x509.Certificate,
  4115. ) (User, error) {
  4116. var user User
  4117. u, mergedUser, err := getUserForHook(username, nil)
  4118. if err != nil {
  4119. return user, err
  4120. }
  4121. if mergedUser.skipExternalAuth() {
  4122. return u, nil
  4123. }
  4124. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  4125. if err != nil {
  4126. return user, err
  4127. }
  4128. startTime := time.Now()
  4129. out, err := getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol, tlsCert, u)
  4130. if err != nil {
  4131. return user, fmt.Errorf("external auth error for user %q, elapsed: %s: %w", username, time.Since(startTime), err)
  4132. }
  4133. providerLog(logger.LevelDebug, "external auth completed for user %q, elapsed: %s", username, time.Since(startTime))
  4134. if util.IsByteArrayEmpty(out) {
  4135. providerLog(logger.LevelDebug, "empty response from external hook, no modification requested for user %q, id: %d",
  4136. username, u.ID)
  4137. if u.ID == 0 {
  4138. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  4139. }
  4140. err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
  4141. return u, err
  4142. }
  4143. err = json.Unmarshal(out, &user)
  4144. if err != nil {
  4145. return user, fmt.Errorf("invalid external auth response: %v", err)
  4146. }
  4147. // an empty username means authentication failure
  4148. if user.Username == "" {
  4149. return user, ErrInvalidCredentials
  4150. }
  4151. updateUserFromExtAuthResponse(&user, password, pkey)
  4152. // some users want to map multiple login usernames with a single SFTPGo account
  4153. // for example an SFTP user logins using "user1" or "user2" and the external auth
  4154. // returns "user" in both cases, so we use the username returned from
  4155. // external auth and not the one used to login
  4156. if user.Username != username {
  4157. u, err = provider.userExists(user.Username, "")
  4158. }
  4159. if u.ID > 0 && err == nil {
  4160. user.ID = u.ID
  4161. user.UsedQuotaSize = u.UsedQuotaSize
  4162. user.UsedQuotaFiles = u.UsedQuotaFiles
  4163. user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
  4164. user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
  4165. user.LastQuotaUpdate = u.LastQuotaUpdate
  4166. user.LastLogin = u.LastLogin
  4167. user.LastPasswordChange = u.LastPasswordChange
  4168. user.FirstDownload = u.FirstDownload
  4169. user.FirstUpload = u.FirstUpload
  4170. user.CreatedAt = u.CreatedAt
  4171. user.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  4172. // preserve TOTP config and recovery codes
  4173. user.Filters.TOTPConfig = u.Filters.TOTPConfig
  4174. user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
  4175. user, err = updateUserAfterExternalAuth(&user)
  4176. if err == nil {
  4177. if protocol != protocolWebDAV {
  4178. webDAVUsersCache.swap(&user, password)
  4179. }
  4180. cachedUserPasswords.Add(user.Username, password, user.Password)
  4181. }
  4182. return user, err
  4183. }
  4184. err = provider.addUser(&user)
  4185. if err != nil {
  4186. return user, err
  4187. }
  4188. return provider.userExists(user.Username, "")
  4189. }
  4190. func doPluginAuth(username, password string, pubKey []byte, ip, protocol string,
  4191. tlsCert *x509.Certificate, authScope int,
  4192. ) (User, error) {
  4193. var user User
  4194. u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, nil)
  4195. if err != nil {
  4196. return user, err
  4197. }
  4198. if mergedUser.skipExternalAuth() {
  4199. return u, nil
  4200. }
  4201. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  4202. if err != nil {
  4203. return user, err
  4204. }
  4205. startTime := time.Now()
  4206. out, err := plugin.Handler.Authenticate(username, password, ip, protocol, pkey, tlsCert, authScope, userAsJSON)
  4207. if err != nil {
  4208. return user, fmt.Errorf("plugin auth error for user %q: %v, elapsed: %v, auth scope: %d",
  4209. username, err, time.Since(startTime), authScope)
  4210. }
  4211. providerLog(logger.LevelDebug, "plugin auth completed for user %q, elapsed: %v, auth scope: %d",
  4212. username, time.Since(startTime), authScope)
  4213. if util.IsByteArrayEmpty(out) {
  4214. providerLog(logger.LevelDebug, "empty response from plugin auth, no modification requested for user %q id: %d, auth scope: %d",
  4215. username, u.ID, authScope)
  4216. if u.ID == 0 {
  4217. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  4218. }
  4219. err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
  4220. return u, err
  4221. }
  4222. err = json.Unmarshal(out, &user)
  4223. if err != nil {
  4224. return user, fmt.Errorf("invalid plugin auth response: %v", err)
  4225. }
  4226. updateUserFromExtAuthResponse(&user, password, pkey)
  4227. if u.ID > 0 {
  4228. user.ID = u.ID
  4229. user.UsedQuotaSize = u.UsedQuotaSize
  4230. user.UsedQuotaFiles = u.UsedQuotaFiles
  4231. user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
  4232. user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
  4233. user.LastQuotaUpdate = u.LastQuotaUpdate
  4234. user.LastLogin = u.LastLogin
  4235. user.LastPasswordChange = u.LastPasswordChange
  4236. user.FirstDownload = u.FirstDownload
  4237. user.FirstUpload = u.FirstUpload
  4238. // preserve TOTP config and recovery codes
  4239. user.Filters.TOTPConfig = u.Filters.TOTPConfig
  4240. user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
  4241. user, err = updateUserAfterExternalAuth(&user)
  4242. if err == nil {
  4243. if protocol != protocolWebDAV {
  4244. webDAVUsersCache.swap(&user, password)
  4245. }
  4246. cachedUserPasswords.Add(user.Username, password, user.Password)
  4247. }
  4248. return user, err
  4249. }
  4250. err = provider.addUser(&user)
  4251. if err != nil {
  4252. return user, err
  4253. }
  4254. return provider.userExists(user.Username, "")
  4255. }
  4256. func updateUserAfterExternalAuth(user *User) (User, error) {
  4257. if err := provider.updateUser(user); err != nil {
  4258. return *user, err
  4259. }
  4260. return provider.userExists(user.Username, "")
  4261. }
  4262. func getUserForHook(username string, oidcTokenFields *map[string]any) (User, User, error) {
  4263. u, err := provider.userExists(username, "")
  4264. if err != nil {
  4265. if !errors.Is(err, util.ErrNotFound) {
  4266. return u, u, err
  4267. }
  4268. u = User{
  4269. BaseUser: sdk.BaseUser{
  4270. ID: 0,
  4271. Username: username,
  4272. },
  4273. }
  4274. }
  4275. mergedUser := u.getACopy()
  4276. err = mergedUser.LoadAndApplyGroupSettings()
  4277. if err != nil {
  4278. return u, mergedUser, err
  4279. }
  4280. u.OIDCCustomFields = oidcTokenFields
  4281. return u, mergedUser, err
  4282. }
  4283. func getUserAndJSONForHook(username string, oidcTokenFields *map[string]any) (User, User, []byte, error) {
  4284. u, mergedUser, err := getUserForHook(username, oidcTokenFields)
  4285. if err != nil {
  4286. return u, mergedUser, nil, err
  4287. }
  4288. userAsJSON, err := json.Marshal(u)
  4289. if err != nil {
  4290. return u, mergedUser, userAsJSON, err
  4291. }
  4292. return u, mergedUser, userAsJSON, err
  4293. }
  4294. func isLastActivityRecent(lastActivity int64, minDelay time.Duration) bool {
  4295. lastActivityTime := util.GetTimeFromMsecSinceEpoch(lastActivity)
  4296. diff := -time.Until(lastActivityTime)
  4297. if diff < -10*time.Second {
  4298. return false
  4299. }
  4300. return diff < minDelay
  4301. }
  4302. func isExternalAuthConfigured(loginMethod string) bool {
  4303. if config.ExternalAuthHook != "" {
  4304. if config.ExternalAuthScope == 0 {
  4305. return true
  4306. }
  4307. switch loginMethod {
  4308. case LoginMethodPassword:
  4309. return config.ExternalAuthScope&1 != 0
  4310. case LoginMethodTLSCertificate:
  4311. return config.ExternalAuthScope&8 != 0
  4312. case LoginMethodTLSCertificateAndPwd:
  4313. return config.ExternalAuthScope&1 != 0 || config.ExternalAuthScope&8 != 0
  4314. }
  4315. }
  4316. switch loginMethod {
  4317. case LoginMethodPassword:
  4318. return plugin.Handler.HasAuthScope(plugin.AuthScopePassword)
  4319. case LoginMethodTLSCertificate:
  4320. return plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
  4321. case LoginMethodTLSCertificateAndPwd:
  4322. return plugin.Handler.HasAuthScope(plugin.AuthScopePassword) ||
  4323. plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
  4324. default:
  4325. return false
  4326. }
  4327. }
  4328. func getConfigPath(name, configDir string) string {
  4329. if !util.IsFileInputValid(name) {
  4330. return ""
  4331. }
  4332. if name != "" && !filepath.IsAbs(name) {
  4333. return filepath.Join(configDir, name)
  4334. }
  4335. return name
  4336. }
  4337. func checkReservedUsernames(username string) error {
  4338. if util.Contains(reservedUsers, username) {
  4339. return util.NewValidationError("this username is reserved")
  4340. }
  4341. return nil
  4342. }
  4343. func providerLog(level logger.LogLevel, format string, v ...any) {
  4344. logger.Log(level, logSender, "", format, v...)
  4345. }