dataprovider.go 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650
  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. UpdateVirtualFolderQuota(&folder.BaseVirtualFolder, filesAdd, sizeAdd, reset) //nolint:errcheck
  1420. if folder.IsIncludedInUserQuota() {
  1421. UpdateUserQuota(user, filesAdd, sizeAdd, reset) //nolint:errcheck
  1422. }
  1423. }
  1424. // UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd.
  1425. // If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
  1426. func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error {
  1427. if config.TrackQuota == 0 {
  1428. return util.NewMethodDisabledError(trackQuotaDisabledError)
  1429. }
  1430. if filesAdd == 0 && sizeAdd == 0 && !reset {
  1431. return nil
  1432. }
  1433. if config.DelayedQuotaUpdate == 0 || reset {
  1434. if reset {
  1435. delayedQuotaUpdater.resetFolderQuota(vfolder.Name)
  1436. }
  1437. return provider.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd, reset)
  1438. }
  1439. delayedQuotaUpdater.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd)
  1440. return nil
  1441. }
  1442. // UpdateUserTransferQuota updates the transfer quota for the given SFTPGo user.
  1443. // If reset is true uploadSize and downloadSize indicates the actual sizes instead of the difference.
  1444. func UpdateUserTransferQuota(user *User, uploadSize, downloadSize int64, reset bool) error {
  1445. if config.TrackQuota == 0 {
  1446. return util.NewMethodDisabledError(trackQuotaDisabledError)
  1447. } else if config.TrackQuota == 2 && !reset && !user.HasTransferQuotaRestrictions() {
  1448. return nil
  1449. }
  1450. if downloadSize == 0 && uploadSize == 0 && !reset {
  1451. return nil
  1452. }
  1453. if config.DelayedQuotaUpdate == 0 || reset {
  1454. if reset {
  1455. delayedQuotaUpdater.resetUserTransferQuota(user.Username)
  1456. }
  1457. return provider.updateTransferQuota(user.Username, uploadSize, downloadSize, reset)
  1458. }
  1459. delayedQuotaUpdater.updateUserTransferQuota(user.Username, uploadSize, downloadSize)
  1460. return nil
  1461. }
  1462. // UpdateUserTransferTimestamps updates the first download/upload fields if unset
  1463. func UpdateUserTransferTimestamps(username string, isUpload bool) error {
  1464. if isUpload {
  1465. err := provider.setFirstUploadTimestamp(username)
  1466. if err != nil {
  1467. providerLog(logger.LevelWarn, "unable to set first upload: %v", err)
  1468. }
  1469. return err
  1470. }
  1471. err := provider.setFirstDownloadTimestamp(username)
  1472. if err != nil {
  1473. providerLog(logger.LevelWarn, "unable to set first download: %v", err)
  1474. }
  1475. return err
  1476. }
  1477. // GetUsedQuota returns the used quota for the given SFTPGo user.
  1478. func GetUsedQuota(username string) (int, int64, int64, int64, error) {
  1479. if config.TrackQuota == 0 {
  1480. return 0, 0, 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  1481. }
  1482. files, size, ulTransferSize, dlTransferSize, err := provider.getUsedQuota(username)
  1483. if err != nil {
  1484. return files, size, ulTransferSize, dlTransferSize, err
  1485. }
  1486. delayedFiles, delayedSize := delayedQuotaUpdater.getUserPendingQuota(username)
  1487. delayedUlTransferSize, delayedDLTransferSize := delayedQuotaUpdater.getUserPendingTransferQuota(username)
  1488. return files + delayedFiles, size + delayedSize, ulTransferSize + delayedUlTransferSize,
  1489. dlTransferSize + delayedDLTransferSize, err
  1490. }
  1491. // GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.
  1492. func GetUsedVirtualFolderQuota(name string) (int, int64, error) {
  1493. if config.TrackQuota == 0 {
  1494. return 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  1495. }
  1496. files, size, err := provider.getUsedFolderQuota(name)
  1497. if err != nil {
  1498. return files, size, err
  1499. }
  1500. delayedFiles, delayedSize := delayedQuotaUpdater.getFolderPendingQuota(name)
  1501. return files + delayedFiles, size + delayedSize, err
  1502. }
  1503. // GetConfigs returns the configurations
  1504. func GetConfigs() (Configs, error) {
  1505. return provider.getConfigs()
  1506. }
  1507. // UpdateConfigs updates configurations
  1508. func UpdateConfigs(configs *Configs, executor, ipAddress, role string) error {
  1509. if configs == nil {
  1510. configs = &Configs{}
  1511. } else {
  1512. configs.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  1513. }
  1514. err := provider.setConfigs(configs)
  1515. if err == nil {
  1516. executeAction(operationUpdate, executor, ipAddress, actionObjectConfigs, "configs", role, configs)
  1517. }
  1518. return err
  1519. }
  1520. // AddShare adds a new share
  1521. func AddShare(share *Share, executor, ipAddress, role string) error {
  1522. err := provider.addShare(share)
  1523. if err == nil {
  1524. executeAction(operationAdd, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
  1525. }
  1526. return err
  1527. }
  1528. // UpdateShare updates an existing share
  1529. func UpdateShare(share *Share, executor, ipAddress, role string) error {
  1530. err := provider.updateShare(share)
  1531. if err == nil {
  1532. executeAction(operationUpdate, executor, ipAddress, actionObjectShare, share.ShareID, role, share)
  1533. }
  1534. return err
  1535. }
  1536. // DeleteShare deletes an existing share
  1537. func DeleteShare(shareID string, executor, ipAddress, role string) error {
  1538. share, err := provider.shareExists(shareID, executor)
  1539. if err != nil {
  1540. return err
  1541. }
  1542. err = provider.deleteShare(share)
  1543. if err == nil {
  1544. executeAction(operationDelete, executor, ipAddress, actionObjectShare, shareID, role, &share)
  1545. }
  1546. return err
  1547. }
  1548. // ShareExists returns the share with the given ID if it exists
  1549. func ShareExists(shareID, username string) (Share, error) {
  1550. if shareID == "" {
  1551. return Share{}, util.NewRecordNotFoundError(fmt.Sprintf("Share %q does not exist", shareID))
  1552. }
  1553. return provider.shareExists(shareID, username)
  1554. }
  1555. // AddIPListEntry adds a new IP list entry
  1556. func AddIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
  1557. err := provider.addIPListEntry(entry)
  1558. if err == nil {
  1559. executeAction(operationAdd, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
  1560. for _, l := range inMemoryLists {
  1561. l.addEntry(entry)
  1562. }
  1563. }
  1564. return err
  1565. }
  1566. // UpdateIPListEntry updates an existing IP list entry
  1567. func UpdateIPListEntry(entry *IPListEntry, executor, ipAddress, executorRole string) error {
  1568. err := provider.updateIPListEntry(entry)
  1569. if err == nil {
  1570. executeAction(operationUpdate, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, entry)
  1571. for _, l := range inMemoryLists {
  1572. l.updateEntry(entry)
  1573. }
  1574. }
  1575. return err
  1576. }
  1577. // DeleteIPListEntry deletes an existing IP list entry
  1578. func DeleteIPListEntry(ipOrNet string, listType IPListType, executor, ipAddress, executorRole string) error {
  1579. entry, err := provider.ipListEntryExists(ipOrNet, listType)
  1580. if err != nil {
  1581. return err
  1582. }
  1583. err = provider.deleteIPListEntry(entry, config.IsShared == 1)
  1584. if err == nil {
  1585. executeAction(operationDelete, executor, ipAddress, actionObjectIPListEntry, entry.getName(), executorRole, &entry)
  1586. for _, l := range inMemoryLists {
  1587. l.removeEntry(&entry)
  1588. }
  1589. }
  1590. return err
  1591. }
  1592. // IPListEntryExists returns the IP list entry with the given IP/net and type if it exists
  1593. func IPListEntryExists(ipOrNet string, listType IPListType) (IPListEntry, error) {
  1594. return provider.ipListEntryExists(ipOrNet, listType)
  1595. }
  1596. // GetIPListEntries returns the IP list entries applying the specified criteria and search limit
  1597. func GetIPListEntries(listType IPListType, filter, from, order string, limit int) ([]IPListEntry, error) {
  1598. if !util.Contains(supportedIPListType, listType) {
  1599. return nil, util.NewValidationError(fmt.Sprintf("invalid list type %d", listType))
  1600. }
  1601. return provider.getIPListEntries(listType, filter, from, order, limit)
  1602. }
  1603. // AddRole adds a new role
  1604. func AddRole(role *Role, executor, ipAddress, executorRole string) error {
  1605. role.Name = config.convertName(role.Name)
  1606. err := provider.addRole(role)
  1607. if err == nil {
  1608. executeAction(operationAdd, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
  1609. }
  1610. return err
  1611. }
  1612. // UpdateRole updates an existing Role
  1613. func UpdateRole(role *Role, executor, ipAddress, executorRole string) error {
  1614. err := provider.updateRole(role)
  1615. if err == nil {
  1616. executeAction(operationUpdate, executor, ipAddress, actionObjectRole, role.Name, executorRole, role)
  1617. }
  1618. return err
  1619. }
  1620. // DeleteRole deletes an existing Role
  1621. func DeleteRole(name string, executor, ipAddress, executorRole string) error {
  1622. name = config.convertName(name)
  1623. role, err := provider.roleExists(name)
  1624. if err != nil {
  1625. return err
  1626. }
  1627. if len(role.Admins) > 0 {
  1628. errorString := fmt.Sprintf("the role %q is referenced, it cannot be removed", role.Name)
  1629. return util.NewValidationError(errorString)
  1630. }
  1631. err = provider.deleteRole(role)
  1632. if err == nil {
  1633. executeAction(operationDelete, executor, ipAddress, actionObjectRole, role.Name, executorRole, &role)
  1634. for _, user := range role.Users {
  1635. provider.setUpdatedAt(user)
  1636. u, err := provider.userExists(user, "")
  1637. if err == nil {
  1638. webDAVUsersCache.swap(&u, "")
  1639. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  1640. }
  1641. }
  1642. }
  1643. return err
  1644. }
  1645. // RoleExists returns the Role with the given name if it exists
  1646. func RoleExists(name string) (Role, error) {
  1647. name = config.convertName(name)
  1648. return provider.roleExists(name)
  1649. }
  1650. // AddGroup adds a new group
  1651. func AddGroup(group *Group, executor, ipAddress, role string) error {
  1652. group.Name = config.convertName(group.Name)
  1653. err := provider.addGroup(group)
  1654. if err == nil {
  1655. executeAction(operationAdd, executor, ipAddress, actionObjectGroup, group.Name, role, group)
  1656. }
  1657. return err
  1658. }
  1659. // UpdateGroup updates an existing Group
  1660. func UpdateGroup(group *Group, users []string, executor, ipAddress, role string) error {
  1661. err := provider.updateGroup(group)
  1662. if err == nil {
  1663. for _, user := range users {
  1664. provider.setUpdatedAt(user)
  1665. u, err := provider.userExists(user, "")
  1666. if err == nil {
  1667. webDAVUsersCache.swap(&u, "")
  1668. } else {
  1669. RemoveCachedWebDAVUser(user)
  1670. }
  1671. }
  1672. executeAction(operationUpdate, executor, ipAddress, actionObjectGroup, group.Name, role, group)
  1673. }
  1674. return err
  1675. }
  1676. // DeleteGroup deletes an existing Group
  1677. func DeleteGroup(name string, executor, ipAddress, role string) error {
  1678. name = config.convertName(name)
  1679. group, err := provider.groupExists(name)
  1680. if err != nil {
  1681. return err
  1682. }
  1683. if len(group.Users) > 0 {
  1684. errorString := fmt.Sprintf("the group %q is referenced, it cannot be removed", group.Name)
  1685. return util.NewValidationError(errorString)
  1686. }
  1687. err = provider.deleteGroup(group)
  1688. if err == nil {
  1689. for _, user := range group.Users {
  1690. provider.setUpdatedAt(user)
  1691. u, err := provider.userExists(user, "")
  1692. if err == nil {
  1693. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  1694. }
  1695. RemoveCachedWebDAVUser(user)
  1696. }
  1697. executeAction(operationDelete, executor, ipAddress, actionObjectGroup, group.Name, role, &group)
  1698. }
  1699. return err
  1700. }
  1701. // GroupExists returns the Group with the given name if it exists
  1702. func GroupExists(name string) (Group, error) {
  1703. name = config.convertName(name)
  1704. return provider.groupExists(name)
  1705. }
  1706. // AddAPIKey adds a new API key
  1707. func AddAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
  1708. err := provider.addAPIKey(apiKey)
  1709. if err == nil {
  1710. executeAction(operationAdd, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
  1711. }
  1712. return err
  1713. }
  1714. // UpdateAPIKey updates an existing API key
  1715. func UpdateAPIKey(apiKey *APIKey, executor, ipAddress, role string) error {
  1716. err := provider.updateAPIKey(apiKey)
  1717. if err == nil {
  1718. executeAction(operationUpdate, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, apiKey)
  1719. }
  1720. return err
  1721. }
  1722. // DeleteAPIKey deletes an existing API key
  1723. func DeleteAPIKey(keyID string, executor, ipAddress, role string) error {
  1724. apiKey, err := provider.apiKeyExists(keyID)
  1725. if err != nil {
  1726. return err
  1727. }
  1728. err = provider.deleteAPIKey(apiKey)
  1729. if err == nil {
  1730. executeAction(operationDelete, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, role, &apiKey)
  1731. cachedAPIKeys.Remove(keyID)
  1732. }
  1733. return err
  1734. }
  1735. // APIKeyExists returns the API key with the given ID if it exists
  1736. func APIKeyExists(keyID string) (APIKey, error) {
  1737. if keyID == "" {
  1738. return APIKey{}, util.NewRecordNotFoundError(fmt.Sprintf("API key %q does not exist", keyID))
  1739. }
  1740. return provider.apiKeyExists(keyID)
  1741. }
  1742. // GetEventActions returns an array of event actions respecting limit and offset
  1743. func GetEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error) {
  1744. return provider.getEventActions(limit, offset, order, minimal)
  1745. }
  1746. // EventActionExists returns the event action with the given name if it exists
  1747. func EventActionExists(name string) (BaseEventAction, error) {
  1748. name = config.convertName(name)
  1749. return provider.eventActionExists(name)
  1750. }
  1751. // AddEventAction adds a new event action
  1752. func AddEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
  1753. action.Name = config.convertName(action.Name)
  1754. err := provider.addEventAction(action)
  1755. if err == nil {
  1756. executeAction(operationAdd, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
  1757. }
  1758. return err
  1759. }
  1760. // UpdateEventAction updates an existing event action
  1761. func UpdateEventAction(action *BaseEventAction, executor, ipAddress, role string) error {
  1762. err := provider.updateEventAction(action)
  1763. if err == nil {
  1764. if fnReloadRules != nil {
  1765. fnReloadRules()
  1766. }
  1767. executeAction(operationUpdate, executor, ipAddress, actionObjectEventAction, action.Name, role, action)
  1768. }
  1769. return err
  1770. }
  1771. // DeleteEventAction deletes an existing event action
  1772. func DeleteEventAction(name string, executor, ipAddress, role string) error {
  1773. name = config.convertName(name)
  1774. action, err := provider.eventActionExists(name)
  1775. if err != nil {
  1776. return err
  1777. }
  1778. if len(action.Rules) > 0 {
  1779. errorString := fmt.Sprintf("the event action %#q is referenced, it cannot be removed", action.Name)
  1780. return util.NewValidationError(errorString)
  1781. }
  1782. err = provider.deleteEventAction(action)
  1783. if err == nil {
  1784. executeAction(operationDelete, executor, ipAddress, actionObjectEventAction, action.Name, role, &action)
  1785. }
  1786. return err
  1787. }
  1788. // GetEventRules returns an array of event rules respecting limit and offset
  1789. func GetEventRules(limit, offset int, order string) ([]EventRule, error) {
  1790. return provider.getEventRules(limit, offset, order)
  1791. }
  1792. // GetRecentlyUpdatedRules returns the event rules updated after the specified time
  1793. func GetRecentlyUpdatedRules(after int64) ([]EventRule, error) {
  1794. return provider.getRecentlyUpdatedRules(after)
  1795. }
  1796. // EventRuleExists returns the event rule with the given name if it exists
  1797. func EventRuleExists(name string) (EventRule, error) {
  1798. name = config.convertName(name)
  1799. return provider.eventRuleExists(name)
  1800. }
  1801. // AddEventRule adds a new event rule
  1802. func AddEventRule(rule *EventRule, executor, ipAddress, role string) error {
  1803. rule.Name = config.convertName(rule.Name)
  1804. err := provider.addEventRule(rule)
  1805. if err == nil {
  1806. if fnReloadRules != nil {
  1807. fnReloadRules()
  1808. }
  1809. executeAction(operationAdd, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
  1810. }
  1811. return err
  1812. }
  1813. // UpdateEventRule updates an existing event rule
  1814. func UpdateEventRule(rule *EventRule, executor, ipAddress, role string) error {
  1815. err := provider.updateEventRule(rule)
  1816. if err == nil {
  1817. if fnReloadRules != nil {
  1818. fnReloadRules()
  1819. }
  1820. executeAction(operationUpdate, executor, ipAddress, actionObjectEventRule, rule.Name, role, rule)
  1821. }
  1822. return err
  1823. }
  1824. // DeleteEventRule deletes an existing event rule
  1825. func DeleteEventRule(name string, executor, ipAddress, role string) error {
  1826. name = config.convertName(name)
  1827. rule, err := provider.eventRuleExists(name)
  1828. if err != nil {
  1829. return err
  1830. }
  1831. err = provider.deleteEventRule(rule, config.IsShared == 1)
  1832. if err == nil {
  1833. if fnRemoveRule != nil {
  1834. fnRemoveRule(rule.Name)
  1835. }
  1836. executeAction(operationDelete, executor, ipAddress, actionObjectEventRule, rule.Name, role, &rule)
  1837. }
  1838. return err
  1839. }
  1840. // RemoveEventRule delets an existing event rule without marking it as deleted
  1841. func RemoveEventRule(rule EventRule) error {
  1842. return provider.deleteEventRule(rule, false)
  1843. }
  1844. // GetTaskByName returns the task with the specified name
  1845. func GetTaskByName(name string) (Task, error) {
  1846. return provider.getTaskByName(name)
  1847. }
  1848. // AddTask add a task with the specified name
  1849. func AddTask(name string) error {
  1850. return provider.addTask(name)
  1851. }
  1852. // UpdateTask updates the task with the specified name and version
  1853. func UpdateTask(name string, version int64) error {
  1854. return provider.updateTask(name, version)
  1855. }
  1856. // UpdateTaskTimestamp updates the timestamp for the task with the specified name
  1857. func UpdateTaskTimestamp(name string) error {
  1858. return provider.updateTaskTimestamp(name)
  1859. }
  1860. // GetNodes returns the other cluster nodes
  1861. func GetNodes() ([]Node, error) {
  1862. if currentNode == nil {
  1863. return nil, nil
  1864. }
  1865. nodes, err := provider.getNodes()
  1866. if err != nil {
  1867. providerLog(logger.LevelError, "unable to get other cluster nodes %v", err)
  1868. }
  1869. return nodes, err
  1870. }
  1871. // GetNodeByName returns a node, different from the current one, by name
  1872. func GetNodeByName(name string) (Node, error) {
  1873. if currentNode == nil {
  1874. return Node{}, util.NewRecordNotFoundError(errNoClusterNodes.Error())
  1875. }
  1876. if name == currentNode.Name {
  1877. return Node{}, util.NewValidationError(fmt.Sprintf("%s is the current node, it must refer to other nodes", name))
  1878. }
  1879. return provider.getNodeByName(name)
  1880. }
  1881. // HasAdmin returns true if the first admin has been created
  1882. // and so SFTPGo is ready to be used
  1883. func HasAdmin() bool {
  1884. return isAdminCreated.Load()
  1885. }
  1886. // AddAdmin adds a new SFTPGo admin
  1887. func AddAdmin(admin *Admin, executor, ipAddress, role string) error {
  1888. admin.Filters.RecoveryCodes = nil
  1889. admin.Filters.TOTPConfig = AdminTOTPConfig{
  1890. Enabled: false,
  1891. }
  1892. admin.Username = config.convertName(admin.Username)
  1893. err := provider.addAdmin(admin)
  1894. if err == nil {
  1895. isAdminCreated.Store(true)
  1896. executeAction(operationAdd, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
  1897. }
  1898. return err
  1899. }
  1900. // UpdateAdmin updates an existing SFTPGo admin
  1901. func UpdateAdmin(admin *Admin, executor, ipAddress, role string) error {
  1902. err := provider.updateAdmin(admin)
  1903. if err == nil {
  1904. executeAction(operationUpdate, executor, ipAddress, actionObjectAdmin, admin.Username, role, admin)
  1905. }
  1906. return err
  1907. }
  1908. // DeleteAdmin deletes an existing SFTPGo admin
  1909. func DeleteAdmin(username, executor, ipAddress, role string) error {
  1910. username = config.convertName(username)
  1911. admin, err := provider.adminExists(username)
  1912. if err != nil {
  1913. return err
  1914. }
  1915. err = provider.deleteAdmin(admin)
  1916. if err == nil {
  1917. executeAction(operationDelete, executor, ipAddress, actionObjectAdmin, admin.Username, role, &admin)
  1918. cachedAdminPasswords.Remove(username)
  1919. }
  1920. return err
  1921. }
  1922. // AdminExists returns the admin with the given username if it exists
  1923. func AdminExists(username string) (Admin, error) {
  1924. username = config.convertName(username)
  1925. return provider.adminExists(username)
  1926. }
  1927. // UserExists checks if the given SFTPGo username exists, returns an error if no match is found
  1928. func UserExists(username, role string) (User, error) {
  1929. username = config.convertName(username)
  1930. return provider.userExists(username, role)
  1931. }
  1932. // GetUserWithGroupSettings tries to return the user with the specified username
  1933. // loading also the group settings
  1934. func GetUserWithGroupSettings(username, role string) (User, error) {
  1935. username = config.convertName(username)
  1936. user, err := provider.userExists(username, role)
  1937. if err != nil {
  1938. return user, err
  1939. }
  1940. err = user.LoadAndApplyGroupSettings()
  1941. return user, err
  1942. }
  1943. // GetUserVariants tries to return the user with the specified username with and without
  1944. // group settings applied
  1945. func GetUserVariants(username, role string) (User, User, error) {
  1946. username = config.convertName(username)
  1947. user, err := provider.userExists(username, role)
  1948. if err != nil {
  1949. return user, User{}, err
  1950. }
  1951. userWithGroupSettings := user.getACopy()
  1952. err = userWithGroupSettings.LoadAndApplyGroupSettings()
  1953. return user, userWithGroupSettings, err
  1954. }
  1955. // AddUser adds a new SFTPGo user.
  1956. func AddUser(user *User, executor, ipAddress, role string) error {
  1957. user.Username = config.convertName(user.Username)
  1958. err := provider.addUser(user)
  1959. if err == nil {
  1960. executeAction(operationAdd, executor, ipAddress, actionObjectUser, user.Username, role, user)
  1961. }
  1962. return err
  1963. }
  1964. // UpdateUserPassword updates the user password
  1965. func UpdateUserPassword(username, plainPwd, executor, ipAddress, role string) error {
  1966. user, err := provider.userExists(username, role)
  1967. if err != nil {
  1968. return err
  1969. }
  1970. userCopy := user.getACopy()
  1971. if err := userCopy.LoadAndApplyGroupSettings(); err != nil {
  1972. return err
  1973. }
  1974. userCopy.Password = plainPwd
  1975. if err := createUserPasswordHash(&userCopy); err != nil {
  1976. return err
  1977. }
  1978. user.LastPasswordChange = userCopy.LastPasswordChange
  1979. user.Password = userCopy.Password
  1980. user.Filters.RequirePasswordChange = false
  1981. // the last password change is set when validating the user
  1982. if err := provider.updateUser(&user); err != nil {
  1983. return err
  1984. }
  1985. webDAVUsersCache.swap(&user, plainPwd)
  1986. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, username, role, &user)
  1987. return nil
  1988. }
  1989. // UpdateUser updates an existing SFTPGo user.
  1990. func UpdateUser(user *User, executor, ipAddress, role string) error {
  1991. if user.groupSettingsApplied {
  1992. return errors.New("cannot save a user with group settings applied")
  1993. }
  1994. err := provider.updateUser(user)
  1995. if err == nil {
  1996. webDAVUsersCache.swap(user, "")
  1997. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, user.Username, role, user)
  1998. }
  1999. return err
  2000. }
  2001. // DeleteUser deletes an existing SFTPGo user.
  2002. func DeleteUser(username, executor, ipAddress, role string) error {
  2003. username = config.convertName(username)
  2004. user, err := provider.userExists(username, role)
  2005. if err != nil {
  2006. return err
  2007. }
  2008. err = provider.deleteUser(user, config.IsShared == 1)
  2009. if err == nil {
  2010. RemoveCachedWebDAVUser(user.Username)
  2011. delayedQuotaUpdater.resetUserQuota(user.Username)
  2012. cachedUserPasswords.Remove(username)
  2013. executeAction(operationDelete, executor, ipAddress, actionObjectUser, user.Username, role, &user)
  2014. }
  2015. return err
  2016. }
  2017. // AddActiveTransfer stores the specified transfer
  2018. func AddActiveTransfer(transfer ActiveTransfer) {
  2019. if err := provider.addActiveTransfer(transfer); err != nil {
  2020. providerLog(logger.LevelError, "unable to add transfer id %v, connection id %v: %v",
  2021. transfer.ID, transfer.ConnID, err)
  2022. }
  2023. }
  2024. // UpdateActiveTransferSizes updates the current upload and download sizes for the specified transfer
  2025. func UpdateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string) {
  2026. if err := provider.updateActiveTransferSizes(ulSize, dlSize, transferID, connectionID); err != nil {
  2027. providerLog(logger.LevelError, "unable to update sizes for transfer id %v, connection id %v: %v",
  2028. transferID, connectionID, err)
  2029. }
  2030. }
  2031. // RemoveActiveTransfer removes the specified transfer
  2032. func RemoveActiveTransfer(transferID int64, connectionID string) {
  2033. if err := provider.removeActiveTransfer(transferID, connectionID); err != nil {
  2034. providerLog(logger.LevelError, "unable to delete transfer id %v, connection id %v: %v",
  2035. transferID, connectionID, err)
  2036. }
  2037. }
  2038. // CleanupActiveTransfers removes the transfer before the specified time
  2039. func CleanupActiveTransfers(before time.Time) error {
  2040. err := provider.cleanupActiveTransfers(before)
  2041. if err == nil {
  2042. providerLog(logger.LevelDebug, "deleted active transfers updated before: %v", before)
  2043. } else {
  2044. providerLog(logger.LevelError, "error deleting active transfers updated before %v: %v", before, err)
  2045. }
  2046. return err
  2047. }
  2048. // GetActiveTransfers retrieves the active transfers with an update time after the specified value
  2049. func GetActiveTransfers(from time.Time) ([]ActiveTransfer, error) {
  2050. return provider.getActiveTransfers(from)
  2051. }
  2052. // AddSharedSession stores a new session within the data provider
  2053. func AddSharedSession(session Session) error {
  2054. err := provider.addSharedSession(session)
  2055. if err != nil {
  2056. providerLog(logger.LevelError, "unable to add shared session, key %q, type: %v, err: %v",
  2057. session.Key, session.Type, err)
  2058. }
  2059. return err
  2060. }
  2061. // DeleteSharedSession deletes the session with the specified key
  2062. func DeleteSharedSession(key string) error {
  2063. err := provider.deleteSharedSession(key)
  2064. if err != nil {
  2065. providerLog(logger.LevelError, "unable to add shared session, key %q, err: %v", key, err)
  2066. }
  2067. return err
  2068. }
  2069. // GetSharedSession retrieves the session with the specified key
  2070. func GetSharedSession(key string) (Session, error) {
  2071. return provider.getSharedSession(key)
  2072. }
  2073. // CleanupSharedSessions removes the shared session with the specified type and
  2074. // before the specified time
  2075. func CleanupSharedSessions(sessionType SessionType, before time.Time) error {
  2076. err := provider.cleanupSharedSessions(sessionType, util.GetTimeAsMsSinceEpoch(before))
  2077. if err == nil {
  2078. providerLog(logger.LevelDebug, "deleted shared sessions before: %v, type: %v", before, sessionType)
  2079. } else {
  2080. providerLog(logger.LevelError, "error deleting shared session before %v, type %v: %v", before, sessionType, err)
  2081. }
  2082. return err
  2083. }
  2084. // ReloadConfig reloads provider configuration.
  2085. // Currently only implemented for memory provider, allows to reload the users
  2086. // from the configured file, if defined
  2087. func ReloadConfig() error {
  2088. return provider.reloadConfig()
  2089. }
  2090. // GetShares returns an array of shares respecting limit and offset
  2091. func GetShares(limit, offset int, order, username string) ([]Share, error) {
  2092. return provider.getShares(limit, offset, order, username)
  2093. }
  2094. // GetAPIKeys returns an array of API keys respecting limit and offset
  2095. func GetAPIKeys(limit, offset int, order string) ([]APIKey, error) {
  2096. return provider.getAPIKeys(limit, offset, order)
  2097. }
  2098. // GetAdmins returns an array of admins respecting limit and offset
  2099. func GetAdmins(limit, offset int, order string) ([]Admin, error) {
  2100. return provider.getAdmins(limit, offset, order)
  2101. }
  2102. // GetRoles returns an array of roles respecting limit and offset
  2103. func GetRoles(limit, offset int, order string, minimal bool) ([]Role, error) {
  2104. return provider.getRoles(limit, offset, order, minimal)
  2105. }
  2106. // GetGroups returns an array of groups respecting limit and offset
  2107. func GetGroups(limit, offset int, order string, minimal bool) ([]Group, error) {
  2108. return provider.getGroups(limit, offset, order, minimal)
  2109. }
  2110. // GetUsers returns an array of users respecting limit and offset
  2111. func GetUsers(limit, offset int, order, role string) ([]User, error) {
  2112. return provider.getUsers(limit, offset, order, role)
  2113. }
  2114. // GetUsersForQuotaCheck returns the users with the fields required for a quota check
  2115. func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error) {
  2116. return provider.getUsersForQuotaCheck(toFetch)
  2117. }
  2118. // AddFolder adds a new virtual folder.
  2119. func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress, role string) error {
  2120. folder.Name = config.convertName(folder.Name)
  2121. err := provider.addFolder(folder)
  2122. if err == nil {
  2123. executeAction(operationAdd, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
  2124. }
  2125. return err
  2126. }
  2127. // UpdateFolder updates the specified virtual folder
  2128. func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress, role string) error {
  2129. err := provider.updateFolder(folder)
  2130. if err == nil {
  2131. executeAction(operationUpdate, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: *folder})
  2132. usersInGroups, errGrp := provider.getUsersInGroups(groups)
  2133. if errGrp == nil {
  2134. users = append(users, usersInGroups...)
  2135. users = util.RemoveDuplicates(users, false)
  2136. } else {
  2137. providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", groups, errGrp)
  2138. }
  2139. for _, user := range users {
  2140. provider.setUpdatedAt(user)
  2141. u, err := provider.userExists(user, "")
  2142. if err == nil {
  2143. webDAVUsersCache.swap(&u, "")
  2144. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  2145. } else {
  2146. RemoveCachedWebDAVUser(user)
  2147. }
  2148. }
  2149. }
  2150. return err
  2151. }
  2152. // DeleteFolder deletes an existing folder.
  2153. func DeleteFolder(folderName, executor, ipAddress, role string) error {
  2154. folderName = config.convertName(folderName)
  2155. folder, err := provider.getFolderByName(folderName)
  2156. if err != nil {
  2157. return err
  2158. }
  2159. err = provider.deleteFolder(folder)
  2160. if err == nil {
  2161. executeAction(operationDelete, executor, ipAddress, actionObjectFolder, folder.Name, role, &wrappedFolder{Folder: folder})
  2162. users := folder.Users
  2163. usersInGroups, errGrp := provider.getUsersInGroups(folder.Groups)
  2164. if errGrp == nil {
  2165. users = append(users, usersInGroups...)
  2166. users = util.RemoveDuplicates(users, false)
  2167. } else {
  2168. providerLog(logger.LevelWarn, "unable to get users in groups %+v: %v", folder.Groups, errGrp)
  2169. }
  2170. for _, user := range users {
  2171. provider.setUpdatedAt(user)
  2172. u, err := provider.userExists(user, "")
  2173. if err == nil {
  2174. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, u.Role, &u)
  2175. }
  2176. RemoveCachedWebDAVUser(user)
  2177. }
  2178. delayedQuotaUpdater.resetFolderQuota(folderName)
  2179. }
  2180. return err
  2181. }
  2182. // GetFolderByName returns the folder with the specified name if any
  2183. func GetFolderByName(name string) (vfs.BaseVirtualFolder, error) {
  2184. name = config.convertName(name)
  2185. return provider.getFolderByName(name)
  2186. }
  2187. // GetFolders returns an array of folders respecting limit and offset
  2188. func GetFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error) {
  2189. return provider.getFolders(limit, offset, order, minimal)
  2190. }
  2191. func dumpUsers(data *BackupData, scopes []string) error {
  2192. if len(scopes) == 0 || util.Contains(scopes, DumpScopeUsers) {
  2193. users, err := provider.dumpUsers()
  2194. if err != nil {
  2195. return err
  2196. }
  2197. data.Users = users
  2198. }
  2199. return nil
  2200. }
  2201. func dumpFolders(data *BackupData, scopes []string) error {
  2202. if len(scopes) == 0 || util.Contains(scopes, DumpScopeFolders) {
  2203. folders, err := provider.dumpFolders()
  2204. if err != nil {
  2205. return err
  2206. }
  2207. data.Folders = folders
  2208. }
  2209. return nil
  2210. }
  2211. func dumpGroups(data *BackupData, scopes []string) error {
  2212. if len(scopes) == 0 || util.Contains(scopes, DumpScopeGroups) {
  2213. groups, err := provider.dumpGroups()
  2214. if err != nil {
  2215. return err
  2216. }
  2217. data.Groups = groups
  2218. }
  2219. return nil
  2220. }
  2221. func dumpAdmins(data *BackupData, scopes []string) error {
  2222. if len(scopes) == 0 || util.Contains(scopes, DumpScopeAdmins) {
  2223. admins, err := provider.dumpAdmins()
  2224. if err != nil {
  2225. return err
  2226. }
  2227. data.Admins = admins
  2228. }
  2229. return nil
  2230. }
  2231. func dumpAPIKeys(data *BackupData, scopes []string) error {
  2232. if len(scopes) == 0 || util.Contains(scopes, DumpScopeAPIKeys) {
  2233. apiKeys, err := provider.dumpAPIKeys()
  2234. if err != nil {
  2235. return err
  2236. }
  2237. data.APIKeys = apiKeys
  2238. }
  2239. return nil
  2240. }
  2241. func dumpShares(data *BackupData, scopes []string) error {
  2242. if len(scopes) == 0 || util.Contains(scopes, DumpScopeShares) {
  2243. shares, err := provider.dumpShares()
  2244. if err != nil {
  2245. return err
  2246. }
  2247. data.Shares = shares
  2248. }
  2249. return nil
  2250. }
  2251. func dumpActions(data *BackupData, scopes []string) error {
  2252. if len(scopes) == 0 || util.Contains(scopes, DumpScopeActions) {
  2253. actions, err := provider.dumpEventActions()
  2254. if err != nil {
  2255. return err
  2256. }
  2257. data.EventActions = actions
  2258. }
  2259. return nil
  2260. }
  2261. func dumpRules(data *BackupData, scopes []string) error {
  2262. if len(scopes) == 0 || util.Contains(scopes, DumpScopeRules) {
  2263. rules, err := provider.dumpEventRules()
  2264. if err != nil {
  2265. return err
  2266. }
  2267. data.EventRules = rules
  2268. }
  2269. return nil
  2270. }
  2271. func dumpRoles(data *BackupData, scopes []string) error {
  2272. if len(scopes) == 0 || util.Contains(scopes, DumpScopeRoles) {
  2273. roles, err := provider.dumpRoles()
  2274. if err != nil {
  2275. return err
  2276. }
  2277. data.Roles = roles
  2278. }
  2279. return nil
  2280. }
  2281. func dumpIPLists(data *BackupData, scopes []string) error {
  2282. if len(scopes) == 0 || util.Contains(scopes, DumpScopeIPLists) {
  2283. ipLists, err := provider.dumpIPListEntries()
  2284. if err != nil {
  2285. return err
  2286. }
  2287. data.IPLists = ipLists
  2288. }
  2289. return nil
  2290. }
  2291. func dumpConfigs(data *BackupData, scopes []string) error {
  2292. if len(scopes) == 0 || util.Contains(scopes, DumpScopeConfigs) {
  2293. configs, err := provider.getConfigs()
  2294. if err != nil {
  2295. return err
  2296. }
  2297. data.Configs = &configs
  2298. }
  2299. return nil
  2300. }
  2301. // DumpData returns a dump containing the requested scopes.
  2302. // Empty scopes means all
  2303. func DumpData(scopes []string) (BackupData, error) {
  2304. data := BackupData{
  2305. Version: DumpVersion,
  2306. }
  2307. if err := dumpGroups(&data, scopes); err != nil {
  2308. return data, err
  2309. }
  2310. if err := dumpUsers(&data, scopes); err != nil {
  2311. return data, err
  2312. }
  2313. if err := dumpFolders(&data, scopes); err != nil {
  2314. return data, err
  2315. }
  2316. if err := dumpAdmins(&data, scopes); err != nil {
  2317. return data, err
  2318. }
  2319. if err := dumpAPIKeys(&data, scopes); err != nil {
  2320. return data, err
  2321. }
  2322. if err := dumpShares(&data, scopes); err != nil {
  2323. return data, err
  2324. }
  2325. if err := dumpActions(&data, scopes); err != nil {
  2326. return data, err
  2327. }
  2328. if err := dumpRules(&data, scopes); err != nil {
  2329. return data, err
  2330. }
  2331. if err := dumpRoles(&data, scopes); err != nil {
  2332. return data, err
  2333. }
  2334. if err := dumpIPLists(&data, scopes); err != nil {
  2335. return data, err
  2336. }
  2337. if err := dumpConfigs(&data, scopes); err != nil {
  2338. return data, err
  2339. }
  2340. return data, nil
  2341. }
  2342. // ParseDumpData tries to parse data as BackupData
  2343. func ParseDumpData(data []byte) (BackupData, error) {
  2344. var dump BackupData
  2345. err := json.Unmarshal(data, &dump)
  2346. return dump, err
  2347. }
  2348. // GetProviderConfig returns the current provider configuration
  2349. func GetProviderConfig() Config {
  2350. return config
  2351. }
  2352. // GetProviderStatus returns an error if the provider is not available
  2353. func GetProviderStatus() ProviderStatus {
  2354. err := provider.checkAvailability()
  2355. status := ProviderStatus{
  2356. Driver: config.Driver,
  2357. }
  2358. if err == nil {
  2359. status.IsActive = true
  2360. } else {
  2361. status.IsActive = false
  2362. status.Error = err.Error()
  2363. }
  2364. return status
  2365. }
  2366. // Close releases all provider resources.
  2367. // This method is used in test cases.
  2368. // Closing an uninitialized provider is not supported
  2369. func Close() error {
  2370. stopScheduler()
  2371. return provider.close()
  2372. }
  2373. func createProvider(basePath string) error {
  2374. sqlPlaceholders = getSQLPlaceholders()
  2375. if err := validateSQLTablesPrefix(); err != nil {
  2376. return err
  2377. }
  2378. logSender = fmt.Sprintf("dataprovider_%v", config.Driver)
  2379. switch config.Driver {
  2380. case SQLiteDataProviderName:
  2381. return initializeSQLiteProvider(basePath)
  2382. case PGSQLDataProviderName, CockroachDataProviderName:
  2383. return initializePGSQLProvider()
  2384. case MySQLDataProviderName:
  2385. return initializeMySQLProvider()
  2386. case BoltDataProviderName:
  2387. return initializeBoltProvider(basePath)
  2388. case MemoryDataProviderName:
  2389. if err := initializeMemoryProvider(basePath); err != nil {
  2390. msg := fmt.Sprintf("provider initialized but data loading failed: %v", err)
  2391. logger.Warn(logSender, "", msg)
  2392. logger.WarnToConsole(msg)
  2393. }
  2394. return nil
  2395. default:
  2396. return fmt.Errorf("unsupported data provider: %v", config.Driver)
  2397. }
  2398. }
  2399. func copyBaseUserFilters(in sdk.BaseUserFilters) sdk.BaseUserFilters {
  2400. filters := sdk.BaseUserFilters{}
  2401. filters.MaxUploadFileSize = in.MaxUploadFileSize
  2402. filters.TLSUsername = in.TLSUsername
  2403. filters.UserType = in.UserType
  2404. filters.AllowedIP = make([]string, len(in.AllowedIP))
  2405. copy(filters.AllowedIP, in.AllowedIP)
  2406. filters.DeniedIP = make([]string, len(in.DeniedIP))
  2407. copy(filters.DeniedIP, in.DeniedIP)
  2408. filters.DeniedLoginMethods = make([]string, len(in.DeniedLoginMethods))
  2409. copy(filters.DeniedLoginMethods, in.DeniedLoginMethods)
  2410. filters.FilePatterns = make([]sdk.PatternsFilter, len(in.FilePatterns))
  2411. copy(filters.FilePatterns, in.FilePatterns)
  2412. filters.DeniedProtocols = make([]string, len(in.DeniedProtocols))
  2413. copy(filters.DeniedProtocols, in.DeniedProtocols)
  2414. filters.TwoFactorAuthProtocols = make([]string, len(in.TwoFactorAuthProtocols))
  2415. copy(filters.TwoFactorAuthProtocols, in.TwoFactorAuthProtocols)
  2416. filters.Hooks.ExternalAuthDisabled = in.Hooks.ExternalAuthDisabled
  2417. filters.Hooks.PreLoginDisabled = in.Hooks.PreLoginDisabled
  2418. filters.Hooks.CheckPasswordDisabled = in.Hooks.CheckPasswordDisabled
  2419. filters.DisableFsChecks = in.DisableFsChecks
  2420. filters.StartDirectory = in.StartDirectory
  2421. filters.FTPSecurity = in.FTPSecurity
  2422. filters.IsAnonymous = in.IsAnonymous
  2423. filters.AllowAPIKeyAuth = in.AllowAPIKeyAuth
  2424. filters.ExternalAuthCacheTime = in.ExternalAuthCacheTime
  2425. filters.DefaultSharesExpiration = in.DefaultSharesExpiration
  2426. filters.MaxSharesExpiration = in.MaxSharesExpiration
  2427. filters.PasswordExpiration = in.PasswordExpiration
  2428. filters.PasswordStrength = in.PasswordStrength
  2429. filters.WebClient = make([]string, len(in.WebClient))
  2430. copy(filters.WebClient, in.WebClient)
  2431. filters.TLSCerts = make([]string, len(in.TLSCerts))
  2432. copy(filters.TLSCerts, in.TLSCerts)
  2433. filters.BandwidthLimits = make([]sdk.BandwidthLimit, 0, len(in.BandwidthLimits))
  2434. for _, limit := range in.BandwidthLimits {
  2435. bwLimit := sdk.BandwidthLimit{
  2436. UploadBandwidth: limit.UploadBandwidth,
  2437. DownloadBandwidth: limit.DownloadBandwidth,
  2438. Sources: make([]string, 0, len(limit.Sources)),
  2439. }
  2440. bwLimit.Sources = make([]string, len(limit.Sources))
  2441. copy(bwLimit.Sources, limit.Sources)
  2442. filters.BandwidthLimits = append(filters.BandwidthLimits, bwLimit)
  2443. }
  2444. filters.AccessTime = make([]sdk.TimePeriod, 0, len(in.AccessTime))
  2445. for _, period := range in.AccessTime {
  2446. filters.AccessTime = append(filters.AccessTime, sdk.TimePeriod{
  2447. DayOfWeek: period.DayOfWeek,
  2448. From: period.From,
  2449. To: period.To,
  2450. })
  2451. }
  2452. return filters
  2453. }
  2454. func buildUserHomeDir(user *User) {
  2455. if user.HomeDir == "" {
  2456. if config.UsersBaseDir != "" {
  2457. user.HomeDir = filepath.Join(config.UsersBaseDir, user.Username)
  2458. return
  2459. }
  2460. switch user.FsConfig.Provider {
  2461. case sdk.SFTPFilesystemProvider, sdk.S3FilesystemProvider, sdk.AzureBlobFilesystemProvider, sdk.GCSFilesystemProvider, sdk.HTTPFilesystemProvider:
  2462. if tempPath != "" {
  2463. user.HomeDir = filepath.Join(tempPath, user.Username)
  2464. } else {
  2465. user.HomeDir = filepath.Join(os.TempDir(), user.Username)
  2466. }
  2467. }
  2468. } else {
  2469. user.HomeDir = filepath.Clean(user.HomeDir)
  2470. }
  2471. }
  2472. func validateFolderQuotaLimits(folder vfs.VirtualFolder) error {
  2473. if folder.QuotaSize < -1 {
  2474. return util.NewI18nError(
  2475. util.NewValidationError(fmt.Sprintf("invalid quota_size: %v folder path %q", folder.QuotaSize, folder.MappedPath)),
  2476. util.I18nErrorFolderQuotaSizeInvalid,
  2477. )
  2478. }
  2479. if folder.QuotaFiles < -1 {
  2480. return util.NewI18nError(
  2481. util.NewValidationError(fmt.Sprintf("invalid quota_file: %v folder path %q", folder.QuotaFiles, folder.MappedPath)),
  2482. util.I18nErrorFolderQuotaFileInvalid,
  2483. )
  2484. }
  2485. if (folder.QuotaSize == -1 && folder.QuotaFiles != -1) || (folder.QuotaFiles == -1 && folder.QuotaSize != -1) {
  2486. return util.NewI18nError(
  2487. util.NewValidationError(fmt.Sprintf("virtual folder quota_size and quota_files must be both -1 or >= 0, quota_size: %v quota_files: %v",
  2488. folder.QuotaFiles, folder.QuotaSize)),
  2489. util.I18nErrorFolderQuotaInvalid,
  2490. )
  2491. }
  2492. return nil
  2493. }
  2494. func validateUserGroups(user *User) error {
  2495. if len(user.Groups) == 0 {
  2496. return nil
  2497. }
  2498. hasPrimary := false
  2499. groupNames := make(map[string]bool)
  2500. for _, g := range user.Groups {
  2501. if g.Type < sdk.GroupTypePrimary && g.Type > sdk.GroupTypeMembership {
  2502. return util.NewValidationError(fmt.Sprintf("invalid group type: %v", g.Type))
  2503. }
  2504. if g.Type == sdk.GroupTypePrimary {
  2505. if hasPrimary {
  2506. return util.NewI18nError(
  2507. util.NewValidationError("only one primary group is allowed"),
  2508. util.I18nErrorPrimaryGroup,
  2509. )
  2510. }
  2511. hasPrimary = true
  2512. }
  2513. if groupNames[g.Name] {
  2514. return util.NewI18nError(
  2515. util.NewValidationError(fmt.Sprintf("the group %q is duplicated", g.Name)),
  2516. util.I18nErrorDuplicateGroup,
  2517. )
  2518. }
  2519. groupNames[g.Name] = true
  2520. }
  2521. return nil
  2522. }
  2523. func validateAssociatedVirtualFolders(vfolders []vfs.VirtualFolder) ([]vfs.VirtualFolder, error) {
  2524. if len(vfolders) == 0 {
  2525. return []vfs.VirtualFolder{}, nil
  2526. }
  2527. var virtualFolders []vfs.VirtualFolder
  2528. folderNames := make(map[string]bool)
  2529. for _, v := range vfolders {
  2530. if v.VirtualPath == "" {
  2531. return nil, util.NewI18nError(
  2532. util.NewValidationError("mount/virtual path is mandatory"),
  2533. util.I18nErrorFolderMountPathRequired,
  2534. )
  2535. }
  2536. cleanedVPath := util.CleanPath(v.VirtualPath)
  2537. if err := validateFolderQuotaLimits(v); err != nil {
  2538. return nil, err
  2539. }
  2540. if v.Name == "" {
  2541. return nil, util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorFolderNameRequired)
  2542. }
  2543. if folderNames[v.Name] {
  2544. return nil, util.NewI18nError(
  2545. util.NewValidationError(fmt.Sprintf("the folder %q is duplicated", v.Name)),
  2546. util.I18nErrorDuplicatedFolders,
  2547. )
  2548. }
  2549. for _, vFolder := range virtualFolders {
  2550. if util.IsDirOverlapped(vFolder.VirtualPath, cleanedVPath, false, "/") {
  2551. return nil, util.NewI18nError(
  2552. util.NewValidationError(fmt.Sprintf("invalid virtual folder %q, it overlaps with virtual folder %q",
  2553. v.VirtualPath, vFolder.VirtualPath)),
  2554. util.I18nErrorOverlappedFolders,
  2555. )
  2556. }
  2557. }
  2558. virtualFolders = append(virtualFolders, vfs.VirtualFolder{
  2559. BaseVirtualFolder: vfs.BaseVirtualFolder{
  2560. Name: v.Name,
  2561. },
  2562. VirtualPath: cleanedVPath,
  2563. QuotaSize: v.QuotaSize,
  2564. QuotaFiles: v.QuotaFiles,
  2565. })
  2566. folderNames[v.Name] = true
  2567. }
  2568. return virtualFolders, nil
  2569. }
  2570. func validateUserTOTPConfig(c *UserTOTPConfig, username string) error {
  2571. if !c.Enabled {
  2572. c.ConfigName = ""
  2573. c.Secret = kms.NewEmptySecret()
  2574. c.Protocols = nil
  2575. return nil
  2576. }
  2577. if c.ConfigName == "" {
  2578. return util.NewValidationError("totp: config name is mandatory")
  2579. }
  2580. if !util.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
  2581. return util.NewValidationError(fmt.Sprintf("totp: config name %q not found", c.ConfigName))
  2582. }
  2583. if c.Secret.IsEmpty() {
  2584. return util.NewValidationError("totp: secret is mandatory")
  2585. }
  2586. if c.Secret.IsPlain() {
  2587. c.Secret.SetAdditionalData(username)
  2588. if err := c.Secret.Encrypt(); err != nil {
  2589. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  2590. }
  2591. }
  2592. if len(c.Protocols) == 0 {
  2593. return util.NewValidationError("totp: specify at least one protocol")
  2594. }
  2595. for _, protocol := range c.Protocols {
  2596. if !util.Contains(MFAProtocols, protocol) {
  2597. return util.NewValidationError(fmt.Sprintf("totp: invalid protocol %q", protocol))
  2598. }
  2599. }
  2600. return nil
  2601. }
  2602. func validateUserRecoveryCodes(user *User) error {
  2603. for i := 0; i < len(user.Filters.RecoveryCodes); i++ {
  2604. code := &user.Filters.RecoveryCodes[i]
  2605. if code.Secret.IsEmpty() {
  2606. return util.NewValidationError("mfa: recovery code cannot be empty")
  2607. }
  2608. if code.Secret.IsPlain() {
  2609. code.Secret.SetAdditionalData(user.Username)
  2610. if err := code.Secret.Encrypt(); err != nil {
  2611. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  2612. }
  2613. }
  2614. }
  2615. return nil
  2616. }
  2617. func validateUserPermissions(permsToCheck map[string][]string) (map[string][]string, error) {
  2618. permissions := make(map[string][]string)
  2619. for dir, perms := range permsToCheck {
  2620. if len(perms) == 0 && dir == "/" {
  2621. return permissions, util.NewValidationError(fmt.Sprintf("no permissions granted for the directory: %q", dir))
  2622. }
  2623. if len(perms) > len(ValidPerms) {
  2624. return permissions, util.NewValidationError("invalid permissions")
  2625. }
  2626. for _, p := range perms {
  2627. if !util.Contains(ValidPerms, p) {
  2628. return permissions, util.NewValidationError(fmt.Sprintf("invalid permission: %q", p))
  2629. }
  2630. }
  2631. cleanedDir := filepath.ToSlash(path.Clean(dir))
  2632. if cleanedDir != "/" {
  2633. cleanedDir = strings.TrimSuffix(cleanedDir, "/")
  2634. }
  2635. if !path.IsAbs(cleanedDir) {
  2636. return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for non absolute path: %q", dir))
  2637. }
  2638. if dir != cleanedDir && cleanedDir == "/" {
  2639. return permissions, util.NewValidationError(fmt.Sprintf("cannot set permissions for invalid subdirectory: %q is an alias for \"/\"", dir))
  2640. }
  2641. if util.Contains(perms, PermAny) {
  2642. permissions[cleanedDir] = []string{PermAny}
  2643. } else {
  2644. permissions[cleanedDir] = util.RemoveDuplicates(perms, false)
  2645. }
  2646. }
  2647. return permissions, nil
  2648. }
  2649. func validatePermissions(user *User) error {
  2650. if len(user.Permissions) == 0 {
  2651. return util.NewI18nError(util.NewValidationError("please grant some permissions to this user"), util.I18nErrorNoPermission)
  2652. }
  2653. if _, ok := user.Permissions["/"]; !ok {
  2654. return util.NewI18nError(util.NewValidationError("permissions for the root dir \"/\" must be set"), util.I18nErrorNoRootPermission)
  2655. }
  2656. permissions, err := validateUserPermissions(user.Permissions)
  2657. if err != nil {
  2658. return util.NewI18nError(err, util.I18nErrorGenericPermission)
  2659. }
  2660. user.Permissions = permissions
  2661. return nil
  2662. }
  2663. func validatePublicKeys(user *User) error {
  2664. if len(user.PublicKeys) == 0 {
  2665. user.PublicKeys = []string{}
  2666. }
  2667. var validatedKeys []string
  2668. for idx, key := range user.PublicKeys {
  2669. if key == "" {
  2670. continue
  2671. }
  2672. out, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
  2673. if err != nil {
  2674. return util.NewI18nError(
  2675. util.NewValidationError(fmt.Sprintf("error parsing public key at position %d: %v", idx, err)),
  2676. util.I18nErrorPubKeyInvalid,
  2677. )
  2678. }
  2679. if k, ok := out.(ssh.CryptoPublicKey); ok {
  2680. cryptoKey := k.CryptoPublicKey()
  2681. if rsaKey, ok := cryptoKey.(*rsa.PublicKey); ok {
  2682. if size := rsaKey.N.BitLen(); size < 2048 {
  2683. providerLog(logger.LevelError, "rsa key with size %d not accepted, minimum 2048", size)
  2684. return util.NewI18nError(
  2685. util.NewValidationError(fmt.Sprintf("invalid size %d for rsa key at position %d, minimum 2048",
  2686. size, idx)),
  2687. util.I18nErrorKeySizeInvalid,
  2688. )
  2689. }
  2690. }
  2691. }
  2692. validatedKeys = append(validatedKeys, key)
  2693. }
  2694. user.PublicKeys = util.RemoveDuplicates(validatedKeys, false)
  2695. return nil
  2696. }
  2697. func validateFiltersPatternExtensions(baseFilters *sdk.BaseUserFilters) error {
  2698. if len(baseFilters.FilePatterns) == 0 {
  2699. baseFilters.FilePatterns = []sdk.PatternsFilter{}
  2700. return nil
  2701. }
  2702. filteredPaths := []string{}
  2703. var filters []sdk.PatternsFilter
  2704. for _, f := range baseFilters.FilePatterns {
  2705. cleanedPath := filepath.ToSlash(path.Clean(f.Path))
  2706. if !path.IsAbs(cleanedPath) {
  2707. return util.NewI18nError(
  2708. util.NewValidationError(fmt.Sprintf("invalid path %q for file patterns filter", f.Path)),
  2709. util.I18nErrorFilePatternPathInvalid,
  2710. )
  2711. }
  2712. if util.Contains(filteredPaths, cleanedPath) {
  2713. return util.NewI18nError(
  2714. util.NewValidationError(fmt.Sprintf("duplicate file patterns filter for path %q", f.Path)),
  2715. util.I18nErrorFilePatternDuplicated,
  2716. )
  2717. }
  2718. if len(f.AllowedPatterns) == 0 && len(f.DeniedPatterns) == 0 {
  2719. return util.NewValidationError(fmt.Sprintf("empty file patterns filter for path %q", f.Path))
  2720. }
  2721. if f.DenyPolicy < sdk.DenyPolicyDefault || f.DenyPolicy > sdk.DenyPolicyHide {
  2722. return util.NewValidationError(fmt.Sprintf("invalid deny policy %v for path %q", f.DenyPolicy, f.Path))
  2723. }
  2724. f.Path = cleanedPath
  2725. allowed := make([]string, 0, len(f.AllowedPatterns))
  2726. denied := make([]string, 0, len(f.DeniedPatterns))
  2727. for _, pattern := range f.AllowedPatterns {
  2728. _, err := path.Match(pattern, "abc")
  2729. if err != nil {
  2730. return util.NewI18nError(
  2731. util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
  2732. util.I18nErrorFilePatternInvalid,
  2733. )
  2734. }
  2735. allowed = append(allowed, strings.ToLower(pattern))
  2736. }
  2737. for _, pattern := range f.DeniedPatterns {
  2738. _, err := path.Match(pattern, "abc")
  2739. if err != nil {
  2740. return util.NewI18nError(
  2741. util.NewValidationError(fmt.Sprintf("invalid file pattern filter %q", pattern)),
  2742. util.I18nErrorFilePatternInvalid,
  2743. )
  2744. }
  2745. denied = append(denied, strings.ToLower(pattern))
  2746. }
  2747. f.AllowedPatterns = util.RemoveDuplicates(allowed, false)
  2748. f.DeniedPatterns = util.RemoveDuplicates(denied, false)
  2749. filters = append(filters, f)
  2750. filteredPaths = append(filteredPaths, cleanedPath)
  2751. }
  2752. baseFilters.FilePatterns = filters
  2753. return nil
  2754. }
  2755. func checkEmptyFiltersStruct(filters *sdk.BaseUserFilters) {
  2756. if len(filters.AllowedIP) == 0 {
  2757. filters.AllowedIP = []string{}
  2758. }
  2759. if len(filters.DeniedIP) == 0 {
  2760. filters.DeniedIP = []string{}
  2761. }
  2762. if len(filters.DeniedLoginMethods) == 0 {
  2763. filters.DeniedLoginMethods = []string{}
  2764. }
  2765. if len(filters.DeniedProtocols) == 0 {
  2766. filters.DeniedProtocols = []string{}
  2767. }
  2768. }
  2769. func validateIPFilters(filters *sdk.BaseUserFilters) error {
  2770. filters.DeniedIP = util.RemoveDuplicates(filters.DeniedIP, false)
  2771. for _, IPMask := range filters.DeniedIP {
  2772. _, _, err := net.ParseCIDR(IPMask)
  2773. if err != nil {
  2774. return util.NewValidationError(fmt.Sprintf("could not parse denied IP/Mask %q: %v", IPMask, err))
  2775. }
  2776. }
  2777. filters.AllowedIP = util.RemoveDuplicates(filters.AllowedIP, false)
  2778. for _, IPMask := range filters.AllowedIP {
  2779. _, _, err := net.ParseCIDR(IPMask)
  2780. if err != nil {
  2781. return util.NewValidationError(fmt.Sprintf("could not parse allowed IP/Mask %q: %v", IPMask, err))
  2782. }
  2783. }
  2784. return nil
  2785. }
  2786. func validateBandwidthLimit(bl sdk.BandwidthLimit) error {
  2787. if len(bl.Sources) == 0 {
  2788. return util.NewValidationError("no bandwidth limit source specified")
  2789. }
  2790. for _, source := range bl.Sources {
  2791. _, _, err := net.ParseCIDR(source)
  2792. if err != nil {
  2793. return util.NewValidationError(fmt.Sprintf("could not parse bandwidth limit source %q: %v", source, err))
  2794. }
  2795. }
  2796. return nil
  2797. }
  2798. func validateBandwidthLimitsFilter(filters *sdk.BaseUserFilters) error {
  2799. for idx, bandwidthLimit := range filters.BandwidthLimits {
  2800. if err := validateBandwidthLimit(bandwidthLimit); err != nil {
  2801. return err
  2802. }
  2803. if bandwidthLimit.DownloadBandwidth < 0 {
  2804. filters.BandwidthLimits[idx].DownloadBandwidth = 0
  2805. }
  2806. if bandwidthLimit.UploadBandwidth < 0 {
  2807. filters.BandwidthLimits[idx].UploadBandwidth = 0
  2808. }
  2809. }
  2810. return nil
  2811. }
  2812. func updateFiltersValues(filters *sdk.BaseUserFilters) {
  2813. if filters.StartDirectory != "" {
  2814. filters.StartDirectory = util.CleanPath(filters.StartDirectory)
  2815. if filters.StartDirectory == "/" {
  2816. filters.StartDirectory = ""
  2817. }
  2818. }
  2819. }
  2820. func validateFilterProtocols(filters *sdk.BaseUserFilters) error {
  2821. if len(filters.DeniedProtocols) >= len(ValidProtocols) {
  2822. return util.NewValidationError("invalid denied_protocols")
  2823. }
  2824. for _, p := range filters.DeniedProtocols {
  2825. if !util.Contains(ValidProtocols, p) {
  2826. return util.NewValidationError(fmt.Sprintf("invalid denied protocol %q", p))
  2827. }
  2828. }
  2829. for _, p := range filters.TwoFactorAuthProtocols {
  2830. if !util.Contains(MFAProtocols, p) {
  2831. return util.NewValidationError(fmt.Sprintf("invalid two factor protocol %q", p))
  2832. }
  2833. }
  2834. return nil
  2835. }
  2836. func validateTLSCerts(certs []string) ([]string, error) {
  2837. var validateCerts []string
  2838. for idx, cert := range certs {
  2839. if cert == "" {
  2840. continue
  2841. }
  2842. derBlock, _ := pem.Decode([]byte(cert))
  2843. if derBlock == nil {
  2844. return nil, util.NewI18nError(
  2845. util.NewValidationError(fmt.Sprintf("invalid TLS certificate %d", idx)),
  2846. util.I18nErrorInvalidTLSCert,
  2847. )
  2848. }
  2849. crt, err := x509.ParseCertificate(derBlock.Bytes)
  2850. if err != nil {
  2851. return nil, util.NewI18nError(
  2852. util.NewValidationError(fmt.Sprintf("error parsing TLS certificate %d", idx)),
  2853. util.I18nErrorInvalidTLSCert,
  2854. )
  2855. }
  2856. if crt.PublicKeyAlgorithm == x509.RSA {
  2857. if rsaCert, ok := crt.PublicKey.(*rsa.PublicKey); ok {
  2858. if size := rsaCert.N.BitLen(); size < 2048 {
  2859. providerLog(logger.LevelError, "rsa cert with size %d not accepted, minimum 2048", size)
  2860. return nil, util.NewI18nError(
  2861. util.NewValidationError(fmt.Sprintf("invalid size %d for rsa cert at position %d, minimum 2048",
  2862. size, idx)),
  2863. util.I18nErrorKeySizeInvalid,
  2864. )
  2865. }
  2866. }
  2867. }
  2868. validateCerts = append(validateCerts, cert)
  2869. }
  2870. return validateCerts, nil
  2871. }
  2872. func validateBaseFilters(filters *sdk.BaseUserFilters) error {
  2873. checkEmptyFiltersStruct(filters)
  2874. if err := validateIPFilters(filters); err != nil {
  2875. return util.NewI18nError(err, util.I18nErrorIPFiltersInvalid)
  2876. }
  2877. if err := validateBandwidthLimitsFilter(filters); err != nil {
  2878. return util.NewI18nError(err, util.I18nErrorSourceBWLimitInvalid)
  2879. }
  2880. if len(filters.DeniedLoginMethods) >= len(ValidLoginMethods) {
  2881. return util.NewValidationError("invalid denied_login_methods")
  2882. }
  2883. for _, loginMethod := range filters.DeniedLoginMethods {
  2884. if !util.Contains(ValidLoginMethods, loginMethod) {
  2885. return util.NewValidationError(fmt.Sprintf("invalid login method: %q", loginMethod))
  2886. }
  2887. }
  2888. if err := validateFilterProtocols(filters); err != nil {
  2889. return err
  2890. }
  2891. if filters.TLSUsername != "" {
  2892. if !util.Contains(validTLSUsernames, string(filters.TLSUsername)) {
  2893. return util.NewValidationError(fmt.Sprintf("invalid TLS username: %q", filters.TLSUsername))
  2894. }
  2895. }
  2896. certs, err := validateTLSCerts(filters.TLSCerts)
  2897. if err != nil {
  2898. return err
  2899. }
  2900. filters.TLSCerts = certs
  2901. for _, opts := range filters.WebClient {
  2902. if !util.Contains(sdk.WebClientOptions, opts) {
  2903. return util.NewValidationError(fmt.Sprintf("invalid web client options %q", opts))
  2904. }
  2905. }
  2906. if filters.MaxSharesExpiration > 0 && filters.MaxSharesExpiration < filters.DefaultSharesExpiration {
  2907. return util.NewI18nError(
  2908. util.NewValidationError(fmt.Sprintf("default shares expiration: %d must be less than or equal to max shares expiration: %d",
  2909. filters.DefaultSharesExpiration, filters.MaxSharesExpiration)),
  2910. util.I18nErrorShareExpirationInvalid,
  2911. )
  2912. }
  2913. updateFiltersValues(filters)
  2914. if err := validateAccessTimeFilters(filters); err != nil {
  2915. return err
  2916. }
  2917. return validateFiltersPatternExtensions(filters)
  2918. }
  2919. func isTimeOfDayValid(value string) bool {
  2920. if len(value) != 5 {
  2921. return false
  2922. }
  2923. parts := strings.Split(value, ":")
  2924. if len(parts) != 2 {
  2925. return false
  2926. }
  2927. hour, err := strconv.Atoi(parts[0])
  2928. if err != nil {
  2929. return false
  2930. }
  2931. if hour < 0 || hour > 23 {
  2932. return false
  2933. }
  2934. minute, err := strconv.Atoi(parts[1])
  2935. if err != nil {
  2936. return false
  2937. }
  2938. if minute < 0 || minute > 59 {
  2939. return false
  2940. }
  2941. return true
  2942. }
  2943. func validateAccessTimeFilters(filters *sdk.BaseUserFilters) error {
  2944. for _, period := range filters.AccessTime {
  2945. if period.DayOfWeek < int(time.Sunday) || period.DayOfWeek > int(time.Saturday) {
  2946. return util.NewValidationError(fmt.Sprintf("invalid day of week: %d", period.DayOfWeek))
  2947. }
  2948. if !isTimeOfDayValid(period.From) || !isTimeOfDayValid(period.To) {
  2949. return util.NewI18nError(
  2950. util.NewValidationError("invalid time of day. Supported format: HH:MM"),
  2951. util.I18nErrorTimeOfDayInvalid,
  2952. )
  2953. }
  2954. if period.To <= period.From {
  2955. return util.NewI18nError(
  2956. util.NewValidationError("invalid time of day. The end time cannot be earlier than the start time"),
  2957. util.I18nErrorTimeOfDayConflict,
  2958. )
  2959. }
  2960. }
  2961. return nil
  2962. }
  2963. func validateCombinedUserFilters(user *User) error {
  2964. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
  2965. return util.NewI18nError(
  2966. util.NewValidationError("two-factor authentication cannot be disabled for a user with an active configuration"),
  2967. util.I18nErrorDisableActive2FA,
  2968. )
  2969. }
  2970. if user.Filters.RequirePasswordChange && util.Contains(user.Filters.WebClient, sdk.WebClientPasswordChangeDisabled) {
  2971. return util.NewI18nError(
  2972. util.NewValidationError("you cannot require password change and at the same time disallow it"),
  2973. util.I18nErrorPwdChangeConflict,
  2974. )
  2975. }
  2976. if len(user.Filters.TwoFactorAuthProtocols) > 0 && util.Contains(user.Filters.WebClient, sdk.WebClientMFADisabled) {
  2977. return util.NewI18nError(
  2978. util.NewValidationError("you cannot require two-factor authentication and at the same time disallow it"),
  2979. util.I18nError2FAConflict,
  2980. )
  2981. }
  2982. return nil
  2983. }
  2984. func validateBaseParams(user *User) error {
  2985. if user.Username == "" {
  2986. return util.NewI18nError(util.NewValidationError("username is mandatory"), util.I18nErrorUsernameRequired)
  2987. }
  2988. if err := checkReservedUsernames(user.Username); err != nil {
  2989. return util.NewI18nError(err, util.I18nErrorReservedUsername)
  2990. }
  2991. if user.Email != "" && !util.IsEmailValid(user.Email) {
  2992. return util.NewI18nError(
  2993. util.NewValidationError(fmt.Sprintf("email %q is not valid", user.Email)),
  2994. util.I18nErrorInvalidEmail,
  2995. )
  2996. }
  2997. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(user.Username) {
  2998. return util.NewI18nError(
  2999. util.NewValidationError(fmt.Sprintf("username %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", user.Username)),
  3000. util.I18nErrorInvalidUser,
  3001. )
  3002. }
  3003. if user.hasRedactedSecret() {
  3004. return util.NewValidationError("cannot save a user with a redacted secret")
  3005. }
  3006. if user.HomeDir == "" {
  3007. return util.NewI18nError(util.NewValidationError("home_dir is mandatory"), util.I18nErrorHomeRequired)
  3008. }
  3009. // we can have users with no passwords and public keys, they can authenticate via SSH user certs or OIDC
  3010. /*if user.Password == "" && len(user.PublicKeys) == 0 {
  3011. return util.NewValidationError("please set a password or at least a public_key")
  3012. }*/
  3013. if !filepath.IsAbs(user.HomeDir) {
  3014. return util.NewI18nError(
  3015. util.NewValidationError(fmt.Sprintf("home_dir must be an absolute path, actual value: %v", user.HomeDir)),
  3016. util.I18nErrorHomeInvalid,
  3017. )
  3018. }
  3019. if user.DownloadBandwidth < 0 {
  3020. user.DownloadBandwidth = 0
  3021. }
  3022. if user.UploadBandwidth < 0 {
  3023. user.UploadBandwidth = 0
  3024. }
  3025. if user.TotalDataTransfer > 0 {
  3026. // if a total data transfer is defined we reset the separate upload and download limits
  3027. user.UploadDataTransfer = 0
  3028. user.DownloadDataTransfer = 0
  3029. }
  3030. if user.Filters.IsAnonymous {
  3031. user.setAnonymousSettings()
  3032. }
  3033. err := user.FsConfig.Validate(user.GetEncryptionAdditionalData())
  3034. if err != nil {
  3035. return err
  3036. }
  3037. return nil
  3038. }
  3039. func hashPlainPassword(plainPwd string) (string, error) {
  3040. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  3041. pwd, err := bcrypt.GenerateFromPassword([]byte(plainPwd), config.PasswordHashing.BcryptOptions.Cost)
  3042. if err != nil {
  3043. return "", fmt.Errorf("bcrypt hashing error: %w", err)
  3044. }
  3045. return util.BytesToString(pwd), nil
  3046. }
  3047. pwd, err := argon2id.CreateHash(plainPwd, argon2Params)
  3048. if err != nil {
  3049. return "", fmt.Errorf("argon2ID hashing error: %w", err)
  3050. }
  3051. return pwd, nil
  3052. }
  3053. func createUserPasswordHash(user *User) error {
  3054. if user.Password != "" && !user.IsPasswordHashed() {
  3055. if minEntropy := user.getMinPasswordEntropy(); minEntropy > 0 {
  3056. if err := passwordvalidator.Validate(user.Password, minEntropy); err != nil {
  3057. return util.NewI18nError(util.NewValidationError(err.Error()), util.I18nErrorPasswordComplexity)
  3058. }
  3059. }
  3060. hashedPwd, err := hashPlainPassword(user.Password)
  3061. if err != nil {
  3062. return err
  3063. }
  3064. user.Password = hashedPwd
  3065. user.LastPasswordChange = util.GetTimeAsMsSinceEpoch(time.Now())
  3066. }
  3067. return nil
  3068. }
  3069. // ValidateFolder returns an error if the folder is not valid
  3070. // FIXME: this should be defined as Folder struct method
  3071. func ValidateFolder(folder *vfs.BaseVirtualFolder) error {
  3072. folder.FsConfig.SetEmptySecretsIfNil()
  3073. if folder.Name == "" {
  3074. return util.NewI18nError(util.NewValidationError("folder name is mandatory"), util.I18nErrorNameRequired)
  3075. }
  3076. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(folder.Name) {
  3077. return util.NewI18nError(
  3078. util.NewValidationError(fmt.Sprintf("folder name %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", folder.Name)),
  3079. util.I18nErrorInvalidName,
  3080. )
  3081. }
  3082. if folder.FsConfig.Provider == sdk.LocalFilesystemProvider || folder.FsConfig.Provider == sdk.CryptedFilesystemProvider ||
  3083. folder.MappedPath != "" {
  3084. cleanedMPath := filepath.Clean(folder.MappedPath)
  3085. if !filepath.IsAbs(cleanedMPath) {
  3086. return util.NewI18nError(
  3087. util.NewValidationError(fmt.Sprintf("invalid folder mapped path %q", folder.MappedPath)),
  3088. util.I18nErrorInvalidHomeDir,
  3089. )
  3090. }
  3091. folder.MappedPath = cleanedMPath
  3092. }
  3093. if folder.HasRedactedSecret() {
  3094. return errors.New("cannot save a folder with a redacted secret")
  3095. }
  3096. return folder.FsConfig.Validate(folder.GetEncryptionAdditionalData())
  3097. }
  3098. // ValidateUser returns an error if the user is not valid
  3099. // FIXME: this should be defined as User struct method
  3100. func ValidateUser(user *User) error {
  3101. user.OIDCCustomFields = nil
  3102. user.HasPassword = false
  3103. user.SetEmptySecretsIfNil()
  3104. buildUserHomeDir(user)
  3105. if err := validateBaseParams(user); err != nil {
  3106. return err
  3107. }
  3108. if err := validateUserGroups(user); err != nil {
  3109. return err
  3110. }
  3111. if err := validatePermissions(user); err != nil {
  3112. return err
  3113. }
  3114. if err := validateUserTOTPConfig(&user.Filters.TOTPConfig, user.Username); err != nil {
  3115. return util.NewI18nError(err, util.I18nError2FAInvalid)
  3116. }
  3117. if err := validateUserRecoveryCodes(user); err != nil {
  3118. return util.NewI18nError(err, util.I18nErrorRecoveryCodesInvalid)
  3119. }
  3120. vfolders, err := validateAssociatedVirtualFolders(user.VirtualFolders)
  3121. if err != nil {
  3122. return err
  3123. }
  3124. user.VirtualFolders = vfolders
  3125. if user.Status < 0 || user.Status > 1 {
  3126. return util.NewValidationError(fmt.Sprintf("invalid user status: %v", user.Status))
  3127. }
  3128. if err := createUserPasswordHash(user); err != nil {
  3129. return err
  3130. }
  3131. if err := validatePublicKeys(user); err != nil {
  3132. return err
  3133. }
  3134. if err := validateBaseFilters(&user.Filters.BaseUserFilters); err != nil {
  3135. return err
  3136. }
  3137. if !user.HasExternalAuth() {
  3138. user.Filters.ExternalAuthCacheTime = 0
  3139. }
  3140. return validateCombinedUserFilters(user)
  3141. }
  3142. func isPasswordOK(user *User, password string) (bool, error) {
  3143. if config.PasswordCaching {
  3144. found, match := cachedUserPasswords.Check(user.Username, password, user.Password)
  3145. if found {
  3146. return match, nil
  3147. }
  3148. }
  3149. match := false
  3150. updatePwd := true
  3151. var err error
  3152. switch {
  3153. case strings.HasPrefix(user.Password, bcryptPwdPrefix):
  3154. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
  3155. return match, ErrInvalidCredentials
  3156. }
  3157. match = true
  3158. updatePwd = config.PasswordHashing.Algo != HashingAlgoBcrypt
  3159. case strings.HasPrefix(user.Password, argonPwdPrefix):
  3160. match, err = argon2id.ComparePasswordAndHash(password, user.Password)
  3161. if err != nil {
  3162. providerLog(logger.LevelError, "error comparing password with argon hash: %v", err)
  3163. return match, err
  3164. }
  3165. updatePwd = config.PasswordHashing.Algo != HashingAlgoArgon2ID
  3166. case util.IsStringPrefixInSlice(user.Password, unixPwdPrefixes):
  3167. match, err = compareUnixPasswordAndHash(user, password)
  3168. if err != nil {
  3169. return match, err
  3170. }
  3171. case util.IsStringPrefixInSlice(user.Password, pbkdfPwdPrefixes):
  3172. match, err = comparePbkdf2PasswordAndHash(password, user.Password)
  3173. if err != nil {
  3174. return match, err
  3175. }
  3176. case util.IsStringPrefixInSlice(user.Password, digestPwdPrefixes):
  3177. match = compareDigestPasswordAndHash(user, password)
  3178. }
  3179. if err == nil && match {
  3180. cachedUserPasswords.Add(user.Username, password, user.Password)
  3181. if updatePwd {
  3182. convertUserPassword(user.Username, password)
  3183. }
  3184. }
  3185. return match, err
  3186. }
  3187. func convertUserPassword(username, plainPwd string) {
  3188. hashedPwd, err := hashPlainPassword(plainPwd)
  3189. if err == nil {
  3190. err = provider.updateUserPassword(username, hashedPwd)
  3191. }
  3192. if err != nil {
  3193. providerLog(logger.LevelWarn, "unable to convert password for user %s: %v", username, err)
  3194. } else {
  3195. providerLog(logger.LevelDebug, "password converted for user %s", username)
  3196. }
  3197. }
  3198. func checkUserAndTLSCertificate(user *User, protocol string, tlsCert *x509.Certificate) (User, error) {
  3199. err := user.LoadAndApplyGroupSettings()
  3200. if err != nil {
  3201. return *user, err
  3202. }
  3203. err = user.CheckLoginConditions()
  3204. if err != nil {
  3205. return *user, err
  3206. }
  3207. switch protocol {
  3208. case protocolFTP, protocolWebDAV:
  3209. for _, cert := range user.Filters.TLSCerts {
  3210. derBlock, _ := pem.Decode(util.StringToBytes(cert))
  3211. if derBlock != nil && bytes.Equal(derBlock.Bytes, tlsCert.Raw) {
  3212. return *user, nil
  3213. }
  3214. }
  3215. if user.Filters.TLSUsername == sdk.TLSUsernameCN {
  3216. if user.Username == tlsCert.Subject.CommonName {
  3217. return *user, nil
  3218. }
  3219. return *user, fmt.Errorf("CN %q does not match username %q", tlsCert.Subject.CommonName, user.Username)
  3220. }
  3221. return *user, errors.New("TLS certificate is not valid")
  3222. default:
  3223. return *user, fmt.Errorf("certificate authentication is not supported for protocol %v", protocol)
  3224. }
  3225. }
  3226. func checkUserAndPass(user *User, password, ip, protocol string) (User, error) {
  3227. err := user.LoadAndApplyGroupSettings()
  3228. if err != nil {
  3229. return *user, err
  3230. }
  3231. err = user.CheckLoginConditions()
  3232. if err != nil {
  3233. return *user, err
  3234. }
  3235. if protocol != protocolHTTP && user.MustChangePassword() {
  3236. return *user, errors.New("login not allowed, password change required")
  3237. }
  3238. if user.Filters.IsAnonymous {
  3239. user.setAnonymousSettings()
  3240. return *user, nil
  3241. }
  3242. password, err = checkUserPasscode(user, password, protocol)
  3243. if err != nil {
  3244. return *user, ErrInvalidCredentials
  3245. }
  3246. if user.Password == "" || password == "" {
  3247. return *user, errors.New("credentials cannot be null or empty")
  3248. }
  3249. if !user.Filters.Hooks.CheckPasswordDisabled {
  3250. hookResponse, err := executeCheckPasswordHook(user.Username, password, ip, protocol)
  3251. if err != nil {
  3252. providerLog(logger.LevelDebug, "error executing check password hook for user %q, ip %v, protocol %v: %v",
  3253. user.Username, ip, protocol, err)
  3254. return *user, errors.New("unable to check credentials")
  3255. }
  3256. switch hookResponse.Status {
  3257. case -1:
  3258. // no hook configured
  3259. case 1:
  3260. providerLog(logger.LevelDebug, "password accepted by check password hook for user %q, ip %v, protocol %v",
  3261. user.Username, ip, protocol)
  3262. return *user, nil
  3263. case 2:
  3264. providerLog(logger.LevelDebug, "partial success from check password hook for user %q, ip %v, protocol %v",
  3265. user.Username, ip, protocol)
  3266. password = hookResponse.ToVerify
  3267. default:
  3268. providerLog(logger.LevelDebug, "password rejected by check password hook for user %q, ip %v, protocol %v, status: %v",
  3269. user.Username, ip, protocol, hookResponse.Status)
  3270. return *user, ErrInvalidCredentials
  3271. }
  3272. }
  3273. match, err := isPasswordOK(user, password)
  3274. if !match {
  3275. err = ErrInvalidCredentials
  3276. }
  3277. return *user, err
  3278. }
  3279. func checkUserPasscode(user *User, password, protocol string) (string, error) {
  3280. if user.Filters.TOTPConfig.Enabled {
  3281. switch protocol {
  3282. case protocolFTP:
  3283. if util.Contains(user.Filters.TOTPConfig.Protocols, protocol) {
  3284. // the TOTP passcode has six digits
  3285. pwdLen := len(password)
  3286. if pwdLen < 7 {
  3287. providerLog(logger.LevelDebug, "password len %v is too short to contain a passcode, user %q, protocol %v",
  3288. pwdLen, user.Username, protocol)
  3289. return "", util.NewValidationError("password too short, cannot contain the passcode")
  3290. }
  3291. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3292. if err != nil {
  3293. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3294. user.Username, protocol, err)
  3295. return "", err
  3296. }
  3297. pwd := password[0:(pwdLen - 6)]
  3298. passcode := password[(pwdLen - 6):]
  3299. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  3300. user.Filters.TOTPConfig.Secret.GetPayload())
  3301. if !match || err != nil {
  3302. providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
  3303. user.Username, protocol, err)
  3304. return "", util.NewValidationError("invalid passcode")
  3305. }
  3306. return pwd, nil
  3307. }
  3308. }
  3309. }
  3310. return password, nil
  3311. }
  3312. func checkUserAndPubKey(user *User, pubKey []byte, isSSHCert bool) (User, string, error) {
  3313. err := user.LoadAndApplyGroupSettings()
  3314. if err != nil {
  3315. return *user, "", err
  3316. }
  3317. err = user.CheckLoginConditions()
  3318. if err != nil {
  3319. return *user, "", err
  3320. }
  3321. if isSSHCert {
  3322. return *user, "", nil
  3323. }
  3324. if len(user.PublicKeys) == 0 {
  3325. return *user, "", ErrInvalidCredentials
  3326. }
  3327. for idx, key := range user.PublicKeys {
  3328. storedKey, comment, _, _, err := ssh.ParseAuthorizedKey(util.StringToBytes(key))
  3329. if err != nil {
  3330. providerLog(logger.LevelError, "error parsing stored public key %d for user %s: %v", idx, user.Username, err)
  3331. return *user, "", err
  3332. }
  3333. if bytes.Equal(storedKey.Marshal(), pubKey) {
  3334. return *user, fmt.Sprintf("%s:%s", ssh.FingerprintSHA256(storedKey), comment), nil
  3335. }
  3336. }
  3337. return *user, "", ErrInvalidCredentials
  3338. }
  3339. func compareDigestPasswordAndHash(user *User, password string) bool {
  3340. if strings.HasPrefix(user.Password, md5DigestPwdPrefix) {
  3341. h := md5.New()
  3342. h.Write([]byte(password))
  3343. return fmt.Sprintf("%s%x", md5DigestPwdPrefix, h.Sum(nil)) == user.Password
  3344. }
  3345. if strings.HasPrefix(user.Password, sha256DigestPwdPrefix) {
  3346. h := sha256.New()
  3347. h.Write([]byte(password))
  3348. return fmt.Sprintf("%s%x", sha256DigestPwdPrefix, h.Sum(nil)) == user.Password
  3349. }
  3350. if strings.HasPrefix(user.Password, sha512DigestPwdPrefix) {
  3351. h := sha512.New()
  3352. h.Write([]byte(password))
  3353. return fmt.Sprintf("%s%x", sha512DigestPwdPrefix, h.Sum(nil)) == user.Password
  3354. }
  3355. return false
  3356. }
  3357. func compareUnixPasswordAndHash(user *User, password string) (bool, error) {
  3358. if strings.HasPrefix(user.Password, yescryptPwdPrefix) {
  3359. return compareYescryptPassword(user.Password, password)
  3360. }
  3361. var crypter crypt.Crypter
  3362. if strings.HasPrefix(user.Password, sha512cryptPwdPrefix) {
  3363. crypter = sha512_crypt.New()
  3364. } else if strings.HasPrefix(user.Password, sha256cryptPwdPrefix) {
  3365. crypter = sha256_crypt.New()
  3366. } else if strings.HasPrefix(user.Password, md5cryptPwdPrefix) {
  3367. crypter = md5_crypt.New()
  3368. } else if strings.HasPrefix(user.Password, md5cryptApr1PwdPrefix) {
  3369. crypter = apr1_crypt.New()
  3370. } else {
  3371. return false, errors.New("unix crypt: invalid or unsupported hash format")
  3372. }
  3373. if err := crypter.Verify(user.Password, []byte(password)); err != nil {
  3374. return false, err
  3375. }
  3376. return true, nil
  3377. }
  3378. func comparePbkdf2PasswordAndHash(password, hashedPassword string) (bool, error) {
  3379. vals := strings.Split(hashedPassword, "$")
  3380. if len(vals) != 5 {
  3381. return false, fmt.Errorf("pbkdf2: hash is not in the correct format")
  3382. }
  3383. iterations, err := strconv.Atoi(vals[2])
  3384. if err != nil {
  3385. return false, err
  3386. }
  3387. expected, err := base64.StdEncoding.DecodeString(vals[4])
  3388. if err != nil {
  3389. return false, err
  3390. }
  3391. var salt []byte
  3392. if util.IsStringPrefixInSlice(hashedPassword, pbkdfPwdB64SaltPrefixes) {
  3393. salt, err = base64.StdEncoding.DecodeString(vals[3])
  3394. if err != nil {
  3395. return false, err
  3396. }
  3397. } else {
  3398. salt = []byte(vals[3])
  3399. }
  3400. var hashFunc func() hash.Hash
  3401. if strings.HasPrefix(hashedPassword, pbkdf2SHA256Prefix) || strings.HasPrefix(hashedPassword, pbkdf2SHA256B64SaltPrefix) {
  3402. hashFunc = sha256.New
  3403. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA512Prefix) {
  3404. hashFunc = sha512.New
  3405. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA1Prefix) {
  3406. hashFunc = sha1.New
  3407. } else {
  3408. return false, fmt.Errorf("pbkdf2: invalid or unsupported hash format %v", vals[1])
  3409. }
  3410. df := pbkdf2.Key([]byte(password), salt, iterations, len(expected), hashFunc)
  3411. return subtle.ConstantTimeCompare(df, expected) == 1, nil
  3412. }
  3413. func getSSLMode() string {
  3414. if config.Driver == PGSQLDataProviderName || config.Driver == CockroachDataProviderName {
  3415. switch config.SSLMode {
  3416. case 0:
  3417. return "disable"
  3418. case 1:
  3419. return "require"
  3420. case 2:
  3421. return "verify-ca"
  3422. case 3:
  3423. return "verify-full"
  3424. case 4:
  3425. return "prefer"
  3426. case 5:
  3427. return "allow"
  3428. }
  3429. } else if config.Driver == MySQLDataProviderName {
  3430. if config.requireCustomTLSForMySQL() {
  3431. return "custom"
  3432. }
  3433. switch config.SSLMode {
  3434. case 0:
  3435. return "false"
  3436. case 1:
  3437. return "true"
  3438. case 2:
  3439. return "skip-verify"
  3440. case 3:
  3441. return "preferred"
  3442. }
  3443. }
  3444. return ""
  3445. }
  3446. func terminateInteractiveAuthProgram(cmd *exec.Cmd, isFinished bool) {
  3447. if isFinished {
  3448. return
  3449. }
  3450. providerLog(logger.LevelInfo, "kill interactive auth program after an unexpected error")
  3451. err := cmd.Process.Kill()
  3452. if err != nil {
  3453. providerLog(logger.LevelDebug, "error killing interactive auth program: %v", err)
  3454. }
  3455. }
  3456. func sendKeyboardAuthHTTPReq(url string, request *plugin.KeyboardAuthRequest) (*plugin.KeyboardAuthResponse, error) {
  3457. reqAsJSON, err := json.Marshal(request)
  3458. if err != nil {
  3459. providerLog(logger.LevelError, "error serializing keyboard interactive auth request: %v", err)
  3460. return nil, err
  3461. }
  3462. resp, err := httpclient.Post(url, "application/json", bytes.NewBuffer(reqAsJSON))
  3463. if err != nil {
  3464. providerLog(logger.LevelError, "error getting keyboard interactive auth hook HTTP response: %v", err)
  3465. return nil, err
  3466. }
  3467. defer resp.Body.Close()
  3468. if resp.StatusCode != http.StatusOK {
  3469. return nil, fmt.Errorf("wrong keyboard interactive auth http status code: %v, expected 200", resp.StatusCode)
  3470. }
  3471. var response plugin.KeyboardAuthResponse
  3472. err = render.DecodeJSON(resp.Body, &response)
  3473. return &response, err
  3474. }
  3475. func doBuiltinKeyboardInteractiveAuth(user *User, client ssh.KeyboardInteractiveChallenge,
  3476. ip, protocol string, isPartialAuth bool,
  3477. ) (int, error) {
  3478. if err := user.LoadAndApplyGroupSettings(); err != nil {
  3479. return 0, err
  3480. }
  3481. hasSecondFactor := user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH)
  3482. if !isPartialAuth || !hasSecondFactor {
  3483. answers, err := client("", "", []string{"Password: "}, []bool{false})
  3484. if err != nil {
  3485. return 0, err
  3486. }
  3487. if len(answers) != 1 {
  3488. return 0, fmt.Errorf("unexpected number of answers: %d", len(answers))
  3489. }
  3490. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  3491. if err != nil {
  3492. return 0, err
  3493. }
  3494. }
  3495. return checkKeyboardInteractiveSecondFactor(user, client, protocol)
  3496. }
  3497. func checkKeyboardInteractiveSecondFactor(user *User, client ssh.KeyboardInteractiveChallenge, protocol string) (int, error) {
  3498. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
  3499. return 1, nil
  3500. }
  3501. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3502. if err != nil {
  3503. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3504. user.Username, protocol, err)
  3505. return 0, err
  3506. }
  3507. answers, err := client("", "", []string{"Authentication code: "}, []bool{false})
  3508. if err != nil {
  3509. return 0, err
  3510. }
  3511. if len(answers) != 1 {
  3512. return 0, fmt.Errorf("unexpected number of answers: %v", len(answers))
  3513. }
  3514. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  3515. user.Filters.TOTPConfig.Secret.GetPayload())
  3516. if !match || err != nil {
  3517. providerLog(logger.LevelWarn, "invalid passcode for user %q, protocol %v, err: %v",
  3518. user.Username, protocol, err)
  3519. return 0, util.NewValidationError("invalid passcode")
  3520. }
  3521. return 1, nil
  3522. }
  3523. func executeKeyboardInteractivePlugin(user *User, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3524. authResult := 0
  3525. requestID := xid.New().String()
  3526. authStep := 1
  3527. req := &plugin.KeyboardAuthRequest{
  3528. Username: user.Username,
  3529. IP: ip,
  3530. Password: user.Password,
  3531. RequestID: requestID,
  3532. Step: authStep,
  3533. }
  3534. var response *plugin.KeyboardAuthResponse
  3535. var err error
  3536. for {
  3537. response, err = plugin.Handler.ExecuteKeyboardInteractiveStep(req)
  3538. if err != nil {
  3539. return authResult, err
  3540. }
  3541. if response.AuthResult != 0 {
  3542. return response.AuthResult, err
  3543. }
  3544. if err = response.Validate(); err != nil {
  3545. providerLog(logger.LevelInfo, "invalid response from keyboard interactive plugin: %v", err)
  3546. return authResult, err
  3547. }
  3548. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3549. if err != nil {
  3550. return authResult, err
  3551. }
  3552. authStep++
  3553. req = &plugin.KeyboardAuthRequest{
  3554. RequestID: requestID,
  3555. Step: authStep,
  3556. Username: user.Username,
  3557. Password: user.Password,
  3558. Answers: answers,
  3559. Questions: response.Questions,
  3560. }
  3561. }
  3562. }
  3563. func executeKeyboardInteractiveHTTPHook(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3564. authResult := 0
  3565. requestID := xid.New().String()
  3566. authStep := 1
  3567. req := &plugin.KeyboardAuthRequest{
  3568. Username: user.Username,
  3569. IP: ip,
  3570. Password: user.Password,
  3571. RequestID: requestID,
  3572. Step: authStep,
  3573. }
  3574. var response *plugin.KeyboardAuthResponse
  3575. var err error
  3576. for {
  3577. response, err = sendKeyboardAuthHTTPReq(authHook, req)
  3578. if err != nil {
  3579. return authResult, err
  3580. }
  3581. if response.AuthResult != 0 {
  3582. return response.AuthResult, err
  3583. }
  3584. if err = response.Validate(); err != nil {
  3585. providerLog(logger.LevelInfo, "invalid response from keyboard interactive http hook: %v", err)
  3586. return authResult, err
  3587. }
  3588. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3589. if err != nil {
  3590. return authResult, err
  3591. }
  3592. authStep++
  3593. req = &plugin.KeyboardAuthRequest{
  3594. RequestID: requestID,
  3595. Step: authStep,
  3596. Username: user.Username,
  3597. Password: user.Password,
  3598. Answers: answers,
  3599. Questions: response.Questions,
  3600. }
  3601. }
  3602. }
  3603. func getKeyboardInteractiveAnswers(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  3604. user *User, ip, protocol string,
  3605. ) ([]string, error) {
  3606. questions := response.Questions
  3607. answers, err := client("", response.Instruction, questions, response.Echos)
  3608. if err != nil {
  3609. providerLog(logger.LevelInfo, "error getting interactive auth client response: %v", err)
  3610. return answers, err
  3611. }
  3612. if len(answers) != len(questions) {
  3613. err = fmt.Errorf("client answers does not match questions, expected: %v actual: %v", questions, answers)
  3614. providerLog(logger.LevelInfo, "keyboard interactive auth error: %v", err)
  3615. return answers, err
  3616. }
  3617. if len(answers) == 1 && response.CheckPwd > 0 {
  3618. if response.CheckPwd == 2 {
  3619. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, protocolSSH) {
  3620. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to check TOTP passcode, TOTP is not enabled for user %q",
  3621. user.Username)
  3622. return answers, errors.New("TOTP not enabled for SSH protocol")
  3623. }
  3624. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  3625. if err != nil {
  3626. providerLog(logger.LevelError, "unable to decrypt TOTP secret for user %q, protocol %v, err: %v",
  3627. user.Username, protocol, err)
  3628. return answers, fmt.Errorf("unable to decrypt TOTP secret: %w", err)
  3629. }
  3630. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  3631. user.Filters.TOTPConfig.Secret.GetPayload())
  3632. if !match || err != nil {
  3633. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to validate passcode for user %q, match? %v, err: %v",
  3634. user.Username, match, err)
  3635. return answers, errors.New("unable to validate TOTP passcode")
  3636. }
  3637. } else {
  3638. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  3639. providerLog(logger.LevelInfo, "interactive auth hook requested password validation for user %q, validation error: %v",
  3640. user.Username, err)
  3641. if err != nil {
  3642. return answers, err
  3643. }
  3644. }
  3645. answers[0] = "OK"
  3646. }
  3647. return answers, err
  3648. }
  3649. func handleProgramInteractiveQuestions(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  3650. user *User, stdin io.WriteCloser, ip, protocol string,
  3651. ) error {
  3652. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  3653. if err != nil {
  3654. return err
  3655. }
  3656. for _, answer := range answers {
  3657. if runtime.GOOS == "windows" {
  3658. answer += "\r"
  3659. }
  3660. answer += "\n"
  3661. _, err = stdin.Write([]byte(answer))
  3662. if err != nil {
  3663. providerLog(logger.LevelError, "unable to write client answer to keyboard interactive program: %v", err)
  3664. return err
  3665. }
  3666. }
  3667. return nil
  3668. }
  3669. func executeKeyboardInteractiveProgram(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  3670. authResult := 0
  3671. timeout, env, args := command.GetConfig(authHook, command.HookKeyboardInteractive)
  3672. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3673. defer cancel()
  3674. cmd := exec.CommandContext(ctx, authHook, args...)
  3675. cmd.Env = append(env,
  3676. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", user.Username),
  3677. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  3678. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", user.Password))
  3679. stdout, err := cmd.StdoutPipe()
  3680. if err != nil {
  3681. return authResult, err
  3682. }
  3683. stdin, err := cmd.StdinPipe()
  3684. if err != nil {
  3685. return authResult, err
  3686. }
  3687. err = cmd.Start()
  3688. if err != nil {
  3689. return authResult, err
  3690. }
  3691. var once sync.Once
  3692. scanner := bufio.NewScanner(stdout)
  3693. for scanner.Scan() {
  3694. var response plugin.KeyboardAuthResponse
  3695. err = json.Unmarshal(scanner.Bytes(), &response)
  3696. if err != nil {
  3697. providerLog(logger.LevelInfo, "interactive auth error parsing response: %v", err)
  3698. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3699. break
  3700. }
  3701. if response.AuthResult != 0 {
  3702. authResult = response.AuthResult
  3703. break
  3704. }
  3705. if err = response.Validate(); err != nil {
  3706. providerLog(logger.LevelInfo, "invalid response from keyboard interactive program: %v", err)
  3707. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3708. break
  3709. }
  3710. go func() {
  3711. err := handleProgramInteractiveQuestions(client, &response, user, stdin, ip, protocol)
  3712. if err != nil {
  3713. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  3714. }
  3715. }()
  3716. }
  3717. stdin.Close()
  3718. once.Do(func() { terminateInteractiveAuthProgram(cmd, true) })
  3719. go func() {
  3720. _, err := cmd.Process.Wait()
  3721. if err != nil {
  3722. providerLog(logger.LevelWarn, "error waiting for %q process to exit: %v", authHook, err)
  3723. }
  3724. }()
  3725. return authResult, err
  3726. }
  3727. func doKeyboardInteractiveAuth(user *User, authHook string, client ssh.KeyboardInteractiveChallenge,
  3728. ip, protocol string, isPartialAuth bool,
  3729. ) (User, error) {
  3730. if err := user.LoadAndApplyGroupSettings(); err != nil {
  3731. return *user, err
  3732. }
  3733. var authResult int
  3734. var err error
  3735. if !user.Filters.Hooks.ExternalAuthDisabled {
  3736. if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
  3737. authResult, err = executeKeyboardInteractivePlugin(user, client, ip, protocol)
  3738. if authResult == 1 && err == nil {
  3739. authResult, err = checkKeyboardInteractiveSecondFactor(user, client, protocol)
  3740. }
  3741. } else if authHook != "" {
  3742. if strings.HasPrefix(authHook, "http") {
  3743. authResult, err = executeKeyboardInteractiveHTTPHook(user, authHook, client, ip, protocol)
  3744. } else {
  3745. authResult, err = executeKeyboardInteractiveProgram(user, authHook, client, ip, protocol)
  3746. }
  3747. } else {
  3748. authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
  3749. }
  3750. } else {
  3751. authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol, isPartialAuth)
  3752. }
  3753. if err != nil {
  3754. return *user, err
  3755. }
  3756. if authResult != 1 {
  3757. return *user, fmt.Errorf("keyboard interactive auth failed, result: %v", authResult)
  3758. }
  3759. err = user.CheckLoginConditions()
  3760. if err != nil {
  3761. return *user, err
  3762. }
  3763. return *user, nil
  3764. }
  3765. func isCheckPasswordHookDefined(protocol string) bool {
  3766. if config.CheckPasswordHook == "" {
  3767. return false
  3768. }
  3769. if config.CheckPasswordScope == 0 {
  3770. return true
  3771. }
  3772. switch protocol {
  3773. case protocolSSH:
  3774. return config.CheckPasswordScope&1 != 0
  3775. case protocolFTP:
  3776. return config.CheckPasswordScope&2 != 0
  3777. case protocolWebDAV:
  3778. return config.CheckPasswordScope&4 != 0
  3779. default:
  3780. return false
  3781. }
  3782. }
  3783. func getPasswordHookResponse(username, password, ip, protocol string) ([]byte, error) {
  3784. if strings.HasPrefix(config.CheckPasswordHook, "http") {
  3785. var result []byte
  3786. req := checkPasswordRequest{
  3787. Username: username,
  3788. Password: password,
  3789. IP: ip,
  3790. Protocol: protocol,
  3791. }
  3792. reqAsJSON, err := json.Marshal(req)
  3793. if err != nil {
  3794. return result, err
  3795. }
  3796. resp, err := httpclient.Post(config.CheckPasswordHook, "application/json", bytes.NewBuffer(reqAsJSON))
  3797. if err != nil {
  3798. providerLog(logger.LevelError, "error getting check password hook response: %v", err)
  3799. return result, err
  3800. }
  3801. defer resp.Body.Close()
  3802. if resp.StatusCode != http.StatusOK {
  3803. return result, fmt.Errorf("wrong http status code from chek password hook: %v, expected 200", resp.StatusCode)
  3804. }
  3805. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  3806. }
  3807. timeout, env, args := command.GetConfig(config.CheckPasswordHook, command.HookCheckPassword)
  3808. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3809. defer cancel()
  3810. cmd := exec.CommandContext(ctx, config.CheckPasswordHook, args...)
  3811. cmd.Env = append(env,
  3812. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
  3813. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
  3814. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  3815. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
  3816. )
  3817. return cmd.Output()
  3818. }
  3819. func executeCheckPasswordHook(username, password, ip, protocol string) (checkPasswordResponse, error) {
  3820. var response checkPasswordResponse
  3821. if !isCheckPasswordHookDefined(protocol) {
  3822. response.Status = -1
  3823. return response, nil
  3824. }
  3825. startTime := time.Now()
  3826. out, err := getPasswordHookResponse(username, password, ip, protocol)
  3827. providerLog(logger.LevelDebug, "check password hook executed, error: %v, elapsed: %v", err, time.Since(startTime))
  3828. if err != nil {
  3829. return response, err
  3830. }
  3831. err = json.Unmarshal(out, &response)
  3832. return response, err
  3833. }
  3834. func getPreLoginHookResponse(loginMethod, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  3835. if strings.HasPrefix(config.PreLoginHook, "http") {
  3836. var url *url.URL
  3837. var result []byte
  3838. url, err := url.Parse(config.PreLoginHook)
  3839. if err != nil {
  3840. providerLog(logger.LevelError, "invalid url for pre-login hook %q, error: %v", config.PreLoginHook, err)
  3841. return result, err
  3842. }
  3843. q := url.Query()
  3844. q.Add("login_method", loginMethod)
  3845. q.Add("ip", ip)
  3846. q.Add("protocol", protocol)
  3847. url.RawQuery = q.Encode()
  3848. resp, err := httpclient.Post(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  3849. if err != nil {
  3850. providerLog(logger.LevelWarn, "error getting pre-login hook response: %v", err)
  3851. return result, err
  3852. }
  3853. defer resp.Body.Close()
  3854. if resp.StatusCode == http.StatusNoContent {
  3855. return result, nil
  3856. }
  3857. if resp.StatusCode != http.StatusOK {
  3858. return result, fmt.Errorf("wrong pre-login hook http status code: %v, expected 200", resp.StatusCode)
  3859. }
  3860. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  3861. }
  3862. timeout, env, args := command.GetConfig(config.PreLoginHook, command.HookPreLogin)
  3863. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3864. defer cancel()
  3865. cmd := exec.CommandContext(ctx, config.PreLoginHook, args...)
  3866. cmd.Env = append(env,
  3867. fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
  3868. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
  3869. fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
  3870. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol),
  3871. )
  3872. return cmd.Output()
  3873. }
  3874. func executePreLoginHook(username, loginMethod, ip, protocol string, oidcTokenFields *map[string]any) (User, error) {
  3875. u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, oidcTokenFields)
  3876. if err != nil {
  3877. return u, err
  3878. }
  3879. if mergedUser.Filters.Hooks.PreLoginDisabled {
  3880. return u, nil
  3881. }
  3882. startTime := time.Now()
  3883. out, err := getPreLoginHookResponse(loginMethod, ip, protocol, userAsJSON)
  3884. if err != nil {
  3885. return u, fmt.Errorf("pre-login hook error: %v, username %q, ip %v, protocol %v elapsed %v",
  3886. err, username, ip, protocol, time.Since(startTime))
  3887. }
  3888. providerLog(logger.LevelDebug, "pre-login hook completed, elapsed: %s", time.Since(startTime))
  3889. if util.IsByteArrayEmpty(out) {
  3890. providerLog(logger.LevelDebug, "empty response from pre-login hook, no modification requested for user %q id: %d",
  3891. username, u.ID)
  3892. if u.ID == 0 {
  3893. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  3894. }
  3895. return u, nil
  3896. }
  3897. userID := u.ID
  3898. userUsedQuotaSize := u.UsedQuotaSize
  3899. userUsedQuotaFiles := u.UsedQuotaFiles
  3900. userUsedDownloadTransfer := u.UsedDownloadDataTransfer
  3901. userUsedUploadTransfer := u.UsedUploadDataTransfer
  3902. userLastQuotaUpdate := u.LastQuotaUpdate
  3903. userLastLogin := u.LastLogin
  3904. userFirstDownload := u.FirstDownload
  3905. userFirstUpload := u.FirstUpload
  3906. userLastPwdChange := u.LastPasswordChange
  3907. userCreatedAt := u.CreatedAt
  3908. totpConfig := u.Filters.TOTPConfig
  3909. recoveryCodes := u.Filters.RecoveryCodes
  3910. err = json.Unmarshal(out, &u)
  3911. if err != nil {
  3912. return u, fmt.Errorf("invalid pre-login hook response %q, error: %v", util.BytesToString(out), err)
  3913. }
  3914. u.ID = userID
  3915. u.UsedQuotaSize = userUsedQuotaSize
  3916. u.UsedQuotaFiles = userUsedQuotaFiles
  3917. u.UsedUploadDataTransfer = userUsedUploadTransfer
  3918. u.UsedDownloadDataTransfer = userUsedDownloadTransfer
  3919. u.LastQuotaUpdate = userLastQuotaUpdate
  3920. u.LastLogin = userLastLogin
  3921. u.LastPasswordChange = userLastPwdChange
  3922. u.FirstDownload = userFirstDownload
  3923. u.FirstUpload = userFirstUpload
  3924. u.CreatedAt = userCreatedAt
  3925. if userID == 0 {
  3926. err = provider.addUser(&u)
  3927. } else {
  3928. u.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  3929. // preserve TOTP config and recovery codes
  3930. u.Filters.TOTPConfig = totpConfig
  3931. u.Filters.RecoveryCodes = recoveryCodes
  3932. err = provider.updateUser(&u)
  3933. if err == nil {
  3934. webDAVUsersCache.swap(&u, "")
  3935. }
  3936. }
  3937. if err != nil {
  3938. return u, err
  3939. }
  3940. providerLog(logger.LevelDebug, "user %q added/updated from pre-login hook response, id: %d", username, userID)
  3941. if userID == 0 {
  3942. return provider.userExists(username, "")
  3943. }
  3944. return u, nil
  3945. }
  3946. // ExecutePostLoginHook executes the post login hook if defined
  3947. func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error) {
  3948. if config.PostLoginHook == "" {
  3949. return
  3950. }
  3951. if config.PostLoginScope == 1 && err == nil {
  3952. return
  3953. }
  3954. if config.PostLoginScope == 2 && err != nil {
  3955. return
  3956. }
  3957. go func() {
  3958. actionsConcurrencyGuard <- struct{}{}
  3959. defer func() {
  3960. <-actionsConcurrencyGuard
  3961. }()
  3962. status := "0"
  3963. if err == nil {
  3964. status = "1"
  3965. }
  3966. user.PrepareForRendering()
  3967. userAsJSON, err := json.Marshal(user)
  3968. if err != nil {
  3969. providerLog(logger.LevelError, "error serializing user in post login hook: %v", err)
  3970. return
  3971. }
  3972. if strings.HasPrefix(config.PostLoginHook, "http") {
  3973. var url *url.URL
  3974. url, err := url.Parse(config.PostLoginHook)
  3975. if err != nil {
  3976. providerLog(logger.LevelDebug, "Invalid post-login hook %q", config.PostLoginHook)
  3977. return
  3978. }
  3979. q := url.Query()
  3980. q.Add("login_method", loginMethod)
  3981. q.Add("ip", ip)
  3982. q.Add("protocol", protocol)
  3983. q.Add("status", status)
  3984. url.RawQuery = q.Encode()
  3985. startTime := time.Now()
  3986. respCode := 0
  3987. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  3988. if err == nil {
  3989. respCode = resp.StatusCode
  3990. resp.Body.Close()
  3991. }
  3992. providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, response code: %v, elapsed: %v err: %v",
  3993. user.Username, ip, protocol, respCode, time.Since(startTime), err)
  3994. return
  3995. }
  3996. timeout, env, args := command.GetConfig(config.PostLoginHook, command.HookPostLogin)
  3997. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  3998. defer cancel()
  3999. cmd := exec.CommandContext(ctx, config.PostLoginHook, args...)
  4000. cmd.Env = append(env,
  4001. fmt.Sprintf("SFTPGO_LOGIND_USER=%s", util.BytesToString(userAsJSON)),
  4002. fmt.Sprintf("SFTPGO_LOGIND_IP=%s", ip),
  4003. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%s", loginMethod),
  4004. fmt.Sprintf("SFTPGO_LOGIND_STATUS=%s", status),
  4005. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%s", protocol))
  4006. startTime := time.Now()
  4007. err = cmd.Run()
  4008. providerLog(logger.LevelDebug, "post login hook executed for user %q, ip %v, protocol %v, elapsed %v err: %v",
  4009. user.Username, ip, protocol, time.Since(startTime), err)
  4010. }()
  4011. }
  4012. func getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol string, cert *x509.Certificate,
  4013. user User,
  4014. ) ([]byte, error) {
  4015. var tlsCert string
  4016. if cert != nil {
  4017. var err error
  4018. tlsCert, err = util.EncodeTLSCertToPem(cert)
  4019. if err != nil {
  4020. return nil, err
  4021. }
  4022. }
  4023. if strings.HasPrefix(config.ExternalAuthHook, "http") {
  4024. var result []byte
  4025. authRequest := make(map[string]any)
  4026. authRequest["username"] = username
  4027. authRequest["ip"] = ip
  4028. authRequest["password"] = password
  4029. authRequest["public_key"] = pkey
  4030. authRequest["protocol"] = protocol
  4031. authRequest["keyboard_interactive"] = keyboardInteractive
  4032. authRequest["tls_cert"] = tlsCert
  4033. if user.ID > 0 {
  4034. authRequest["user"] = user
  4035. }
  4036. authRequestAsJSON, err := json.Marshal(authRequest)
  4037. if err != nil {
  4038. providerLog(logger.LevelError, "error serializing external auth request: %v", err)
  4039. return result, err
  4040. }
  4041. resp, err := httpclient.Post(config.ExternalAuthHook, "application/json", bytes.NewBuffer(authRequestAsJSON))
  4042. if err != nil {
  4043. providerLog(logger.LevelWarn, "error getting external auth hook HTTP response: %v", err)
  4044. return result, err
  4045. }
  4046. defer resp.Body.Close()
  4047. providerLog(logger.LevelDebug, "external auth hook executed, response code: %v", resp.StatusCode)
  4048. if resp.StatusCode != http.StatusOK {
  4049. return result, fmt.Errorf("wrong external auth http status code: %v, expected 200", resp.StatusCode)
  4050. }
  4051. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  4052. }
  4053. var userAsJSON []byte
  4054. var err error
  4055. if user.ID > 0 {
  4056. userAsJSON, err = json.Marshal(user)
  4057. if err != nil {
  4058. return nil, fmt.Errorf("unable to serialize user as JSON: %w", err)
  4059. }
  4060. }
  4061. timeout, env, args := command.GetConfig(config.ExternalAuthHook, command.HookExternalAuth)
  4062. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  4063. defer cancel()
  4064. cmd := exec.CommandContext(ctx, config.ExternalAuthHook, args...)
  4065. cmd.Env = append(env,
  4066. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%s", username),
  4067. fmt.Sprintf("SFTPGO_AUTHD_USER=%s", util.BytesToString(userAsJSON)),
  4068. fmt.Sprintf("SFTPGO_AUTHD_IP=%s", ip),
  4069. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%s", password),
  4070. fmt.Sprintf("SFTPGO_AUTHD_PUBLIC_KEY=%s", pkey),
  4071. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%s", protocol),
  4072. fmt.Sprintf("SFTPGO_AUTHD_TLS_CERT=%s", strings.ReplaceAll(tlsCert, "\n", "\\n")),
  4073. fmt.Sprintf("SFTPGO_AUTHD_KEYBOARD_INTERACTIVE=%v", keyboardInteractive))
  4074. return cmd.Output()
  4075. }
  4076. func updateUserFromExtAuthResponse(user *User, password, pkey string) {
  4077. if password != "" {
  4078. user.Password = password
  4079. }
  4080. if pkey != "" && !util.IsStringPrefixInSlice(pkey, user.PublicKeys) {
  4081. user.PublicKeys = append(user.PublicKeys, pkey)
  4082. }
  4083. user.LastPasswordChange = 0
  4084. }
  4085. func checkPasswordAfterEmptyExtAuthResponse(user *User, plainPwd, protocol string) error {
  4086. if plainPwd == "" {
  4087. return nil
  4088. }
  4089. match, err := isPasswordOK(user, plainPwd)
  4090. if match && err == nil {
  4091. return nil
  4092. }
  4093. hashedPwd, err := hashPlainPassword(plainPwd)
  4094. if err != nil {
  4095. providerLog(logger.LevelError, "unable to hash password for user %q after empty external response: %v",
  4096. user.Username, err)
  4097. return err
  4098. }
  4099. err = provider.updateUserPassword(user.Username, hashedPwd)
  4100. if err != nil {
  4101. providerLog(logger.LevelError, "unable to update password for user %q after empty external response: %v",
  4102. user.Username, err)
  4103. }
  4104. user.Password = hashedPwd
  4105. cachedUserPasswords.Add(user.Username, plainPwd, user.Password)
  4106. if protocol != protocolWebDAV {
  4107. webDAVUsersCache.swap(user, plainPwd)
  4108. }
  4109. providerLog(logger.LevelDebug, "updated password for user %q after empty external auth response", user.Username)
  4110. return nil
  4111. }
  4112. func doExternalAuth(username, password string, pubKey []byte, keyboardInteractive, ip, protocol string,
  4113. tlsCert *x509.Certificate,
  4114. ) (User, error) {
  4115. var user User
  4116. u, mergedUser, err := getUserForHook(username, nil)
  4117. if err != nil {
  4118. return user, err
  4119. }
  4120. if mergedUser.skipExternalAuth() {
  4121. return u, nil
  4122. }
  4123. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  4124. if err != nil {
  4125. return user, err
  4126. }
  4127. startTime := time.Now()
  4128. out, err := getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol, tlsCert, u)
  4129. if err != nil {
  4130. return user, fmt.Errorf("external auth error for user %q, elapsed: %s: %w", username, time.Since(startTime), err)
  4131. }
  4132. providerLog(logger.LevelDebug, "external auth completed for user %q, elapsed: %s", username, time.Since(startTime))
  4133. if util.IsByteArrayEmpty(out) {
  4134. providerLog(logger.LevelDebug, "empty response from external hook, no modification requested for user %q, id: %d",
  4135. username, u.ID)
  4136. if u.ID == 0 {
  4137. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  4138. }
  4139. err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
  4140. return u, err
  4141. }
  4142. err = json.Unmarshal(out, &user)
  4143. if err != nil {
  4144. return user, fmt.Errorf("invalid external auth response: %v", err)
  4145. }
  4146. // an empty username means authentication failure
  4147. if user.Username == "" {
  4148. return user, ErrInvalidCredentials
  4149. }
  4150. updateUserFromExtAuthResponse(&user, password, pkey)
  4151. // some users want to map multiple login usernames with a single SFTPGo account
  4152. // for example an SFTP user logins using "user1" or "user2" and the external auth
  4153. // returns "user" in both cases, so we use the username returned from
  4154. // external auth and not the one used to login
  4155. if user.Username != username {
  4156. u, err = provider.userExists(user.Username, "")
  4157. }
  4158. if u.ID > 0 && err == nil {
  4159. user.ID = u.ID
  4160. user.UsedQuotaSize = u.UsedQuotaSize
  4161. user.UsedQuotaFiles = u.UsedQuotaFiles
  4162. user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
  4163. user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
  4164. user.LastQuotaUpdate = u.LastQuotaUpdate
  4165. user.LastLogin = u.LastLogin
  4166. user.LastPasswordChange = u.LastPasswordChange
  4167. user.FirstDownload = u.FirstDownload
  4168. user.FirstUpload = u.FirstUpload
  4169. user.CreatedAt = u.CreatedAt
  4170. user.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  4171. // preserve TOTP config and recovery codes
  4172. user.Filters.TOTPConfig = u.Filters.TOTPConfig
  4173. user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
  4174. user, err = updateUserAfterExternalAuth(&user)
  4175. if err == nil {
  4176. if protocol != protocolWebDAV {
  4177. webDAVUsersCache.swap(&user, password)
  4178. }
  4179. cachedUserPasswords.Add(user.Username, password, user.Password)
  4180. }
  4181. return user, err
  4182. }
  4183. err = provider.addUser(&user)
  4184. if err != nil {
  4185. return user, err
  4186. }
  4187. return provider.userExists(user.Username, "")
  4188. }
  4189. func doPluginAuth(username, password string, pubKey []byte, ip, protocol string,
  4190. tlsCert *x509.Certificate, authScope int,
  4191. ) (User, error) {
  4192. var user User
  4193. u, mergedUser, userAsJSON, err := getUserAndJSONForHook(username, nil)
  4194. if err != nil {
  4195. return user, err
  4196. }
  4197. if mergedUser.skipExternalAuth() {
  4198. return u, nil
  4199. }
  4200. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  4201. if err != nil {
  4202. return user, err
  4203. }
  4204. startTime := time.Now()
  4205. out, err := plugin.Handler.Authenticate(username, password, ip, protocol, pkey, tlsCert, authScope, userAsJSON)
  4206. if err != nil {
  4207. return user, fmt.Errorf("plugin auth error for user %q: %v, elapsed: %v, auth scope: %d",
  4208. username, err, time.Since(startTime), authScope)
  4209. }
  4210. providerLog(logger.LevelDebug, "plugin auth completed for user %q, elapsed: %v, auth scope: %d",
  4211. username, time.Since(startTime), authScope)
  4212. if util.IsByteArrayEmpty(out) {
  4213. providerLog(logger.LevelDebug, "empty response from plugin auth, no modification requested for user %q id: %d, auth scope: %d",
  4214. username, u.ID, authScope)
  4215. if u.ID == 0 {
  4216. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %q does not exist", username))
  4217. }
  4218. err = checkPasswordAfterEmptyExtAuthResponse(&u, password, protocol)
  4219. return u, err
  4220. }
  4221. err = json.Unmarshal(out, &user)
  4222. if err != nil {
  4223. return user, fmt.Errorf("invalid plugin auth response: %v", err)
  4224. }
  4225. updateUserFromExtAuthResponse(&user, password, pkey)
  4226. if u.ID > 0 {
  4227. user.ID = u.ID
  4228. user.UsedQuotaSize = u.UsedQuotaSize
  4229. user.UsedQuotaFiles = u.UsedQuotaFiles
  4230. user.UsedUploadDataTransfer = u.UsedUploadDataTransfer
  4231. user.UsedDownloadDataTransfer = u.UsedDownloadDataTransfer
  4232. user.LastQuotaUpdate = u.LastQuotaUpdate
  4233. user.LastLogin = u.LastLogin
  4234. user.LastPasswordChange = u.LastPasswordChange
  4235. user.FirstDownload = u.FirstDownload
  4236. user.FirstUpload = u.FirstUpload
  4237. // preserve TOTP config and recovery codes
  4238. user.Filters.TOTPConfig = u.Filters.TOTPConfig
  4239. user.Filters.RecoveryCodes = u.Filters.RecoveryCodes
  4240. user, err = updateUserAfterExternalAuth(&user)
  4241. if err == nil {
  4242. if protocol != protocolWebDAV {
  4243. webDAVUsersCache.swap(&user, password)
  4244. }
  4245. cachedUserPasswords.Add(user.Username, password, user.Password)
  4246. }
  4247. return user, err
  4248. }
  4249. err = provider.addUser(&user)
  4250. if err != nil {
  4251. return user, err
  4252. }
  4253. return provider.userExists(user.Username, "")
  4254. }
  4255. func updateUserAfterExternalAuth(user *User) (User, error) {
  4256. if err := provider.updateUser(user); err != nil {
  4257. return *user, err
  4258. }
  4259. return provider.userExists(user.Username, "")
  4260. }
  4261. func getUserForHook(username string, oidcTokenFields *map[string]any) (User, User, error) {
  4262. u, err := provider.userExists(username, "")
  4263. if err != nil {
  4264. if !errors.Is(err, util.ErrNotFound) {
  4265. return u, u, err
  4266. }
  4267. u = User{
  4268. BaseUser: sdk.BaseUser{
  4269. ID: 0,
  4270. Username: username,
  4271. },
  4272. }
  4273. }
  4274. mergedUser := u.getACopy()
  4275. err = mergedUser.LoadAndApplyGroupSettings()
  4276. if err != nil {
  4277. return u, mergedUser, err
  4278. }
  4279. u.OIDCCustomFields = oidcTokenFields
  4280. return u, mergedUser, err
  4281. }
  4282. func getUserAndJSONForHook(username string, oidcTokenFields *map[string]any) (User, User, []byte, error) {
  4283. u, mergedUser, err := getUserForHook(username, oidcTokenFields)
  4284. if err != nil {
  4285. return u, mergedUser, nil, err
  4286. }
  4287. userAsJSON, err := json.Marshal(u)
  4288. if err != nil {
  4289. return u, mergedUser, userAsJSON, err
  4290. }
  4291. return u, mergedUser, userAsJSON, err
  4292. }
  4293. func isLastActivityRecent(lastActivity int64, minDelay time.Duration) bool {
  4294. lastActivityTime := util.GetTimeFromMsecSinceEpoch(lastActivity)
  4295. diff := -time.Until(lastActivityTime)
  4296. if diff < -10*time.Second {
  4297. return false
  4298. }
  4299. return diff < minDelay
  4300. }
  4301. func isExternalAuthConfigured(loginMethod string) bool {
  4302. if config.ExternalAuthHook != "" {
  4303. if config.ExternalAuthScope == 0 {
  4304. return true
  4305. }
  4306. switch loginMethod {
  4307. case LoginMethodPassword:
  4308. return config.ExternalAuthScope&1 != 0
  4309. case LoginMethodTLSCertificate:
  4310. return config.ExternalAuthScope&8 != 0
  4311. case LoginMethodTLSCertificateAndPwd:
  4312. return config.ExternalAuthScope&1 != 0 || config.ExternalAuthScope&8 != 0
  4313. }
  4314. }
  4315. switch loginMethod {
  4316. case LoginMethodPassword:
  4317. return plugin.Handler.HasAuthScope(plugin.AuthScopePassword)
  4318. case LoginMethodTLSCertificate:
  4319. return plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
  4320. case LoginMethodTLSCertificateAndPwd:
  4321. return plugin.Handler.HasAuthScope(plugin.AuthScopePassword) ||
  4322. plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate)
  4323. default:
  4324. return false
  4325. }
  4326. }
  4327. func getConfigPath(name, configDir string) string {
  4328. if !util.IsFileInputValid(name) {
  4329. return ""
  4330. }
  4331. if name != "" && !filepath.IsAbs(name) {
  4332. return filepath.Join(configDir, name)
  4333. }
  4334. return name
  4335. }
  4336. func checkReservedUsernames(username string) error {
  4337. if util.Contains(reservedUsers, username) {
  4338. return util.NewValidationError("this username is reserved")
  4339. }
  4340. return nil
  4341. }
  4342. func providerLog(level logger.LogLevel, format string, v ...any) {
  4343. logger.Log(level, logSender, "", format, v...)
  4344. }