dataprovider.go 160 KB

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