dataprovider.go 147 KB

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