dataprovider.go 143 KB

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