dataprovider.go 159 KB

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