dataprovider.go 153 KB

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