dataprovider.go 147 KB

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