You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh_key.go 38KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bufio"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "encoding/base64"
  12. "encoding/binary"
  13. "encoding/pem"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "math/big"
  19. "os"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/process"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/timeutil"
  29. "code.gitea.io/gitea/modules/util"
  30. "golang.org/x/crypto/ssh"
  31. "xorm.io/builder"
  32. "xorm.io/xorm"
  33. )
  34. const (
  35. tplCommentPrefix = `# gitea public key`
  36. tplCommand = "%s --config=%s serv key-%d"
  37. tplPublicKey = tplCommentPrefix + "\n" + `command=%s,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  38. authorizedPrincipalsFile = "authorized_principals"
  39. )
  40. var sshOpLocker sync.Mutex
  41. // KeyType specifies the key type
  42. type KeyType int
  43. const (
  44. // KeyTypeUser specifies the user key
  45. KeyTypeUser = iota + 1
  46. // KeyTypeDeploy specifies the deploy key
  47. KeyTypeDeploy
  48. // KeyTypePrincipal specifies the authorized principal key
  49. KeyTypePrincipal
  50. )
  51. // PublicKey represents a user or deploy SSH public key.
  52. type PublicKey struct {
  53. ID int64 `xorm:"pk autoincr"`
  54. OwnerID int64 `xorm:"INDEX NOT NULL"`
  55. Name string `xorm:"NOT NULL"`
  56. Fingerprint string `xorm:"INDEX NOT NULL"`
  57. Content string `xorm:"TEXT NOT NULL"`
  58. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  59. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  60. LoginSourceID int64 `xorm:"NOT NULL DEFAULT 0"`
  61. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  62. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  63. HasRecentActivity bool `xorm:"-"`
  64. HasUsed bool `xorm:"-"`
  65. }
  66. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  67. func (key *PublicKey) AfterLoad() {
  68. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  69. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > timeutil.TimeStampNow()
  70. }
  71. // OmitEmail returns content of public key without email address.
  72. func (key *PublicKey) OmitEmail() string {
  73. return strings.Join(strings.Split(key.Content, " ")[:2], " ")
  74. }
  75. // AuthorizedString returns formatted public key string for authorized_keys file.
  76. func (key *PublicKey) AuthorizedString() string {
  77. return fmt.Sprintf(tplPublicKey, util.ShellEscape(fmt.Sprintf(tplCommand, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf), key.ID)), key.Content)
  78. }
  79. func extractTypeFromBase64Key(key string) (string, error) {
  80. b, err := base64.StdEncoding.DecodeString(key)
  81. if err != nil || len(b) < 4 {
  82. return "", fmt.Errorf("invalid key format: %v", err)
  83. }
  84. keyLength := int(binary.BigEndian.Uint32(b))
  85. if len(b) < 4+keyLength {
  86. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  87. }
  88. return string(b[4 : 4+keyLength]), nil
  89. }
  90. const ssh2keyStart = "---- BEGIN SSH2 PUBLIC KEY ----"
  91. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  92. func parseKeyString(content string) (string, error) {
  93. // remove whitespace at start and end
  94. content = strings.TrimSpace(content)
  95. var keyType, keyContent, keyComment string
  96. if strings.HasPrefix(content, ssh2keyStart) {
  97. // Parse SSH2 file format.
  98. // Transform all legal line endings to a single "\n".
  99. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  100. lines := strings.Split(content, "\n")
  101. continuationLine := false
  102. for _, line := range lines {
  103. // Skip lines that:
  104. // 1) are a continuation of the previous line,
  105. // 2) contain ":" as that are comment lines
  106. // 3) contain "-" as that are begin and end tags
  107. if continuationLine || strings.ContainsAny(line, ":-") {
  108. continuationLine = strings.HasSuffix(line, "\\")
  109. } else {
  110. keyContent += line
  111. }
  112. }
  113. t, err := extractTypeFromBase64Key(keyContent)
  114. if err != nil {
  115. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  116. }
  117. keyType = t
  118. } else {
  119. if strings.Contains(content, "-----BEGIN") {
  120. // Convert PEM Keys to OpenSSH format
  121. // Transform all legal line endings to a single "\n".
  122. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  123. block, _ := pem.Decode([]byte(content))
  124. if block == nil {
  125. return "", fmt.Errorf("failed to parse PEM block containing the public key")
  126. }
  127. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  128. if err != nil {
  129. var pk rsa.PublicKey
  130. _, err2 := asn1.Unmarshal(block.Bytes, &pk)
  131. if err2 != nil {
  132. return "", fmt.Errorf("failed to parse DER encoded public key as either PKIX or PEM RSA Key: %v %v", err, err2)
  133. }
  134. pub = &pk
  135. }
  136. sshKey, err := ssh.NewPublicKey(pub)
  137. if err != nil {
  138. return "", fmt.Errorf("unable to convert to ssh public key: %v", err)
  139. }
  140. content = string(ssh.MarshalAuthorizedKey(sshKey))
  141. }
  142. // Parse OpenSSH format.
  143. // Remove all newlines
  144. content = strings.NewReplacer("\r\n", "", "\n", "").Replace(content)
  145. parts := strings.SplitN(content, " ", 3)
  146. switch len(parts) {
  147. case 0:
  148. return "", errors.New("empty key")
  149. case 1:
  150. keyContent = parts[0]
  151. case 2:
  152. keyType = parts[0]
  153. keyContent = parts[1]
  154. default:
  155. keyType = parts[0]
  156. keyContent = parts[1]
  157. keyComment = parts[2]
  158. }
  159. // If keyType is not given, extract it from content. If given, validate it.
  160. t, err := extractTypeFromBase64Key(keyContent)
  161. if err != nil {
  162. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  163. }
  164. if len(keyType) == 0 {
  165. keyType = t
  166. } else if keyType != t {
  167. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  168. }
  169. }
  170. // Finally we need to check whether we can actually read the proposed key:
  171. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(keyType + " " + keyContent + " " + keyComment))
  172. if err != nil {
  173. return "", fmt.Errorf("invalid ssh public key: %v", err)
  174. }
  175. return keyType + " " + keyContent + " " + keyComment, nil
  176. }
  177. // writeTmpKeyFile writes key content to a temporary file
  178. // and returns the name of that file, along with any possible errors.
  179. func writeTmpKeyFile(content string) (string, error) {
  180. tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gitea_keytest")
  181. if err != nil {
  182. return "", fmt.Errorf("TempFile: %v", err)
  183. }
  184. defer tmpFile.Close()
  185. if _, err = tmpFile.WriteString(content); err != nil {
  186. return "", fmt.Errorf("WriteString: %v", err)
  187. }
  188. return tmpFile.Name(), nil
  189. }
  190. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  191. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  192. tmpName, err := writeTmpKeyFile(key)
  193. if err != nil {
  194. return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
  195. }
  196. defer func() {
  197. if err := util.Remove(tmpName); err != nil {
  198. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpName, err)
  199. }
  200. }()
  201. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  202. if err != nil {
  203. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  204. }
  205. if strings.Contains(stdout, "is not a public key file") {
  206. return "", 0, ErrKeyUnableVerify{stdout}
  207. }
  208. fields := strings.Split(stdout, " ")
  209. if len(fields) < 4 {
  210. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  211. }
  212. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  213. length, err := strconv.ParseInt(fields[0], 10, 32)
  214. if err != nil {
  215. return "", 0, err
  216. }
  217. return strings.ToLower(keyType), int(length), nil
  218. }
  219. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  220. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  221. fields := strings.Fields(keyLine)
  222. if len(fields) < 2 {
  223. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  224. }
  225. raw, err := base64.StdEncoding.DecodeString(fields[1])
  226. if err != nil {
  227. return "", 0, err
  228. }
  229. pkey, err := ssh.ParsePublicKey(raw)
  230. if err != nil {
  231. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  232. return "", 0, ErrKeyUnableVerify{err.Error()}
  233. }
  234. return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
  235. }
  236. // The ssh library can parse the key, so next we find out what key exactly we have.
  237. switch pkey.Type() {
  238. case ssh.KeyAlgoDSA:
  239. rawPub := struct {
  240. Name string
  241. P, Q, G, Y *big.Int
  242. }{}
  243. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  244. return "", 0, err
  245. }
  246. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  247. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  248. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  249. case ssh.KeyAlgoRSA:
  250. rawPub := struct {
  251. Name string
  252. E *big.Int
  253. N *big.Int
  254. }{}
  255. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  256. return "", 0, err
  257. }
  258. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  259. case ssh.KeyAlgoECDSA256:
  260. return "ecdsa", 256, nil
  261. case ssh.KeyAlgoECDSA384:
  262. return "ecdsa", 384, nil
  263. case ssh.KeyAlgoECDSA521:
  264. return "ecdsa", 521, nil
  265. case ssh.KeyAlgoED25519:
  266. return "ed25519", 256, nil
  267. case ssh.KeyAlgoSKECDSA256:
  268. return "ecdsa-sk", 256, nil
  269. case ssh.KeyAlgoSKED25519:
  270. return "ed25519-sk", 256, nil
  271. }
  272. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  273. }
  274. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  275. // It returns the actual public key line on success.
  276. func CheckPublicKeyString(content string) (_ string, err error) {
  277. if setting.SSH.Disabled {
  278. return "", ErrSSHDisabled{}
  279. }
  280. content, err = parseKeyString(content)
  281. if err != nil {
  282. return "", err
  283. }
  284. content = strings.TrimRight(content, "\n\r")
  285. if strings.ContainsAny(content, "\n\r") {
  286. return "", errors.New("only a single line with a single key please")
  287. }
  288. // remove any unnecessary whitespace now
  289. content = strings.TrimSpace(content)
  290. if !setting.SSH.MinimumKeySizeCheck {
  291. return content, nil
  292. }
  293. var (
  294. fnName string
  295. keyType string
  296. length int
  297. )
  298. if setting.SSH.StartBuiltinServer {
  299. fnName = "SSHNativeParsePublicKey"
  300. keyType, length, err = SSHNativeParsePublicKey(content)
  301. } else {
  302. fnName = "SSHKeyGenParsePublicKey"
  303. keyType, length, err = SSHKeyGenParsePublicKey(content)
  304. }
  305. if err != nil {
  306. return "", fmt.Errorf("%s: %v", fnName, err)
  307. }
  308. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  309. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  310. return content, nil
  311. } else if found && length < minLen {
  312. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  313. }
  314. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  315. }
  316. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  317. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  318. // Don't need to rewrite this file if builtin SSH server is enabled.
  319. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  320. return nil
  321. }
  322. sshOpLocker.Lock()
  323. defer sshOpLocker.Unlock()
  324. if setting.SSH.RootPath != "" {
  325. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  326. // This of course doesn't guarantee that this is the right directory for authorized_keys
  327. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  328. // right user it will at least be created properly.
  329. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  330. if err != nil {
  331. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  332. return err
  333. }
  334. }
  335. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  336. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
  337. if err != nil {
  338. return err
  339. }
  340. defer f.Close()
  341. // Note: chmod command does not support in Windows.
  342. if !setting.IsWindows {
  343. fi, err := f.Stat()
  344. if err != nil {
  345. return err
  346. }
  347. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  348. if fi.Mode().Perm() > 0o600 {
  349. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  350. if err = f.Chmod(0o600); err != nil {
  351. return err
  352. }
  353. }
  354. }
  355. for _, key := range keys {
  356. if key.Type == KeyTypePrincipal {
  357. continue
  358. }
  359. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  360. return err
  361. }
  362. }
  363. return nil
  364. }
  365. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  366. // it is OK to use same key as deploy key for multiple repositories/users.
  367. func checkKeyFingerprint(e Engine, fingerprint string) error {
  368. has, err := e.Get(&PublicKey{
  369. Fingerprint: fingerprint,
  370. })
  371. if err != nil {
  372. return err
  373. } else if has {
  374. return ErrKeyAlreadyExist{0, fingerprint, ""}
  375. }
  376. return nil
  377. }
  378. func calcFingerprintSSHKeygen(publicKeyContent string) (string, error) {
  379. // Calculate fingerprint.
  380. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  381. if err != nil {
  382. return "", err
  383. }
  384. defer func() {
  385. if err := util.Remove(tmpPath); err != nil {
  386. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpPath, err)
  387. }
  388. }()
  389. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  390. if err != nil {
  391. if strings.Contains(stderr, "is not a public key file") {
  392. return "", ErrKeyUnableVerify{stderr}
  393. }
  394. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  395. } else if len(stdout) < 2 {
  396. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  397. }
  398. return strings.Split(stdout, " ")[1], nil
  399. }
  400. func calcFingerprintNative(publicKeyContent string) (string, error) {
  401. // Calculate fingerprint.
  402. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
  403. if err != nil {
  404. return "", err
  405. }
  406. return ssh.FingerprintSHA256(pk), nil
  407. }
  408. func calcFingerprint(publicKeyContent string) (string, error) {
  409. // Call the method based on configuration
  410. var (
  411. fnName, fp string
  412. err error
  413. )
  414. if setting.SSH.StartBuiltinServer {
  415. fnName = "calcFingerprintNative"
  416. fp, err = calcFingerprintNative(publicKeyContent)
  417. } else {
  418. fnName = "calcFingerprintSSHKeygen"
  419. fp, err = calcFingerprintSSHKeygen(publicKeyContent)
  420. }
  421. if err != nil {
  422. if IsErrKeyUnableVerify(err) {
  423. log.Info("%s", publicKeyContent)
  424. return "", err
  425. }
  426. return "", fmt.Errorf("%s: %v", fnName, err)
  427. }
  428. return fp, nil
  429. }
  430. func addKey(e Engine, key *PublicKey) (err error) {
  431. if len(key.Fingerprint) == 0 {
  432. key.Fingerprint, err = calcFingerprint(key.Content)
  433. if err != nil {
  434. return err
  435. }
  436. }
  437. // Save SSH key.
  438. if _, err = e.Insert(key); err != nil {
  439. return err
  440. }
  441. return appendAuthorizedKeysToFile(key)
  442. }
  443. // AddPublicKey adds new public key to database and authorized_keys file.
  444. func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*PublicKey, error) {
  445. log.Trace(content)
  446. fingerprint, err := calcFingerprint(content)
  447. if err != nil {
  448. return nil, err
  449. }
  450. sess := x.NewSession()
  451. defer sess.Close()
  452. if err = sess.Begin(); err != nil {
  453. return nil, err
  454. }
  455. if err := checkKeyFingerprint(sess, fingerprint); err != nil {
  456. return nil, err
  457. }
  458. // Key name of same user cannot be duplicated.
  459. has, err := sess.
  460. Where("owner_id = ? AND name = ?", ownerID, name).
  461. Get(new(PublicKey))
  462. if err != nil {
  463. return nil, err
  464. } else if has {
  465. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  466. }
  467. key := &PublicKey{
  468. OwnerID: ownerID,
  469. Name: name,
  470. Fingerprint: fingerprint,
  471. Content: content,
  472. Mode: AccessModeWrite,
  473. Type: KeyTypeUser,
  474. LoginSourceID: loginSourceID,
  475. }
  476. if err = addKey(sess, key); err != nil {
  477. return nil, fmt.Errorf("addKey: %v", err)
  478. }
  479. return key, sess.Commit()
  480. }
  481. // GetPublicKeyByID returns public key by given ID.
  482. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  483. key := new(PublicKey)
  484. has, err := x.
  485. ID(keyID).
  486. Get(key)
  487. if err != nil {
  488. return nil, err
  489. } else if !has {
  490. return nil, ErrKeyNotExist{keyID}
  491. }
  492. return key, nil
  493. }
  494. func searchPublicKeyByContentWithEngine(e Engine, content string) (*PublicKey, error) {
  495. key := new(PublicKey)
  496. has, err := e.
  497. Where("content like ?", content+"%").
  498. Get(key)
  499. if err != nil {
  500. return nil, err
  501. } else if !has {
  502. return nil, ErrKeyNotExist{}
  503. }
  504. return key, nil
  505. }
  506. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  507. // and returns public key found.
  508. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  509. return searchPublicKeyByContentWithEngine(x, content)
  510. }
  511. func searchPublicKeyByContentExactWithEngine(e Engine, content string) (*PublicKey, error) {
  512. key := new(PublicKey)
  513. has, err := e.
  514. Where("content = ?", content).
  515. Get(key)
  516. if err != nil {
  517. return nil, err
  518. } else if !has {
  519. return nil, ErrKeyNotExist{}
  520. }
  521. return key, nil
  522. }
  523. // SearchPublicKeyByContentExact searches content
  524. // and returns public key found.
  525. func SearchPublicKeyByContentExact(content string) (*PublicKey, error) {
  526. return searchPublicKeyByContentExactWithEngine(x, content)
  527. }
  528. // SearchPublicKey returns a list of public keys matching the provided arguments.
  529. func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
  530. keys := make([]*PublicKey, 0, 5)
  531. cond := builder.NewCond()
  532. if uid != 0 {
  533. cond = cond.And(builder.Eq{"owner_id": uid})
  534. }
  535. if fingerprint != "" {
  536. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  537. }
  538. return keys, x.Where(cond).Find(&keys)
  539. }
  540. // ListPublicKeys returns a list of public keys belongs to given user.
  541. func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
  542. sess := x.Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal)
  543. if listOptions.Page != 0 {
  544. sess = listOptions.setSessionPagination(sess)
  545. keys := make([]*PublicKey, 0, listOptions.PageSize)
  546. return keys, sess.Find(&keys)
  547. }
  548. keys := make([]*PublicKey, 0, 5)
  549. return keys, sess.Find(&keys)
  550. }
  551. // ListPublicLdapSSHKeys returns a list of synchronized public ldap ssh keys belongs to given user and login source.
  552. func ListPublicLdapSSHKeys(uid, loginSourceID int64) ([]*PublicKey, error) {
  553. keys := make([]*PublicKey, 0, 5)
  554. return keys, x.
  555. Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID).
  556. Find(&keys)
  557. }
  558. // UpdatePublicKeyUpdated updates public key use time.
  559. func UpdatePublicKeyUpdated(id int64) error {
  560. // Check if key exists before update as affected rows count is unreliable
  561. // and will return 0 affected rows if two updates are made at the same time
  562. if cnt, err := x.ID(id).Count(&PublicKey{}); err != nil {
  563. return err
  564. } else if cnt != 1 {
  565. return ErrKeyNotExist{id}
  566. }
  567. _, err := x.ID(id).Cols("updated_unix").Update(&PublicKey{
  568. UpdatedUnix: timeutil.TimeStampNow(),
  569. })
  570. if err != nil {
  571. return err
  572. }
  573. return nil
  574. }
  575. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  576. func deletePublicKeys(e Engine, keyIDs ...int64) error {
  577. if len(keyIDs) == 0 {
  578. return nil
  579. }
  580. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  581. return err
  582. }
  583. // PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key
  584. func PublicKeysAreExternallyManaged(keys []*PublicKey) ([]bool, error) {
  585. sources := make([]*LoginSource, 0, 5)
  586. externals := make([]bool, len(keys))
  587. keyloop:
  588. for i, key := range keys {
  589. if key.LoginSourceID == 0 {
  590. externals[i] = false
  591. continue keyloop
  592. }
  593. var source *LoginSource
  594. sourceloop:
  595. for _, s := range sources {
  596. if s.ID == key.LoginSourceID {
  597. source = s
  598. break sourceloop
  599. }
  600. }
  601. if source == nil {
  602. var err error
  603. source, err = GetLoginSourceByID(key.LoginSourceID)
  604. if err != nil {
  605. if IsErrLoginSourceNotExist(err) {
  606. externals[i] = false
  607. sources[i] = &LoginSource{
  608. ID: key.LoginSourceID,
  609. }
  610. continue keyloop
  611. }
  612. return nil, err
  613. }
  614. }
  615. ldapSource := source.LDAP()
  616. if ldapSource != nil &&
  617. source.IsSyncEnabled &&
  618. (source.Type == LoginLDAP || source.Type == LoginDLDAP) &&
  619. len(strings.TrimSpace(ldapSource.AttributeSSHPublicKey)) > 0 {
  620. // Disable setting SSH keys for this user
  621. externals[i] = true
  622. }
  623. }
  624. return externals, nil
  625. }
  626. // PublicKeyIsExternallyManaged returns whether the provided KeyID represents an externally managed Key
  627. func PublicKeyIsExternallyManaged(id int64) (bool, error) {
  628. key, err := GetPublicKeyByID(id)
  629. if err != nil {
  630. return false, err
  631. }
  632. if key.LoginSourceID == 0 {
  633. return false, nil
  634. }
  635. source, err := GetLoginSourceByID(key.LoginSourceID)
  636. if err != nil {
  637. if IsErrLoginSourceNotExist(err) {
  638. return false, nil
  639. }
  640. return false, err
  641. }
  642. ldapSource := source.LDAP()
  643. if ldapSource != nil &&
  644. source.IsSyncEnabled &&
  645. (source.Type == LoginLDAP || source.Type == LoginDLDAP) &&
  646. len(strings.TrimSpace(ldapSource.AttributeSSHPublicKey)) > 0 {
  647. // Disable setting SSH keys for this user
  648. return true, nil
  649. }
  650. return false, nil
  651. }
  652. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  653. func DeletePublicKey(doer *User, id int64) (err error) {
  654. key, err := GetPublicKeyByID(id)
  655. if err != nil {
  656. return err
  657. }
  658. // Check if user has access to delete this key.
  659. if !doer.IsAdmin && doer.ID != key.OwnerID {
  660. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  661. }
  662. sess := x.NewSession()
  663. defer sess.Close()
  664. if err = sess.Begin(); err != nil {
  665. return err
  666. }
  667. if err = deletePublicKeys(sess, id); err != nil {
  668. return err
  669. }
  670. if err = sess.Commit(); err != nil {
  671. return err
  672. }
  673. sess.Close()
  674. if key.Type == KeyTypePrincipal {
  675. return RewriteAllPrincipalKeys()
  676. }
  677. return RewriteAllPublicKeys()
  678. }
  679. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  680. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  681. // outside any session scope independently.
  682. func RewriteAllPublicKeys() error {
  683. return rewriteAllPublicKeys(x)
  684. }
  685. func rewriteAllPublicKeys(e Engine) error {
  686. // Don't rewrite key if internal server
  687. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  688. return nil
  689. }
  690. sshOpLocker.Lock()
  691. defer sshOpLocker.Unlock()
  692. if setting.SSH.RootPath != "" {
  693. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  694. // This of course doesn't guarantee that this is the right directory for authorized_keys
  695. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  696. // right user it will at least be created properly.
  697. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  698. if err != nil {
  699. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  700. return err
  701. }
  702. }
  703. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  704. tmpPath := fPath + ".tmp"
  705. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
  706. if err != nil {
  707. return err
  708. }
  709. defer func() {
  710. t.Close()
  711. if err := util.Remove(tmpPath); err != nil {
  712. log.Warn("Unable to remove temporary authorized keys file: %s: Error: %v", tmpPath, err)
  713. }
  714. }()
  715. if setting.SSH.AuthorizedKeysBackup {
  716. isExist, err := util.IsExist(fPath)
  717. if err != nil {
  718. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  719. return err
  720. }
  721. if isExist {
  722. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  723. if err = util.CopyFile(fPath, bakPath); err != nil {
  724. return err
  725. }
  726. }
  727. }
  728. if err := regeneratePublicKeys(e, t); err != nil {
  729. return err
  730. }
  731. t.Close()
  732. return os.Rename(tmpPath, fPath)
  733. }
  734. // RegeneratePublicKeys regenerates the authorized_keys file
  735. func RegeneratePublicKeys(t io.StringWriter) error {
  736. return regeneratePublicKeys(x, t)
  737. }
  738. func regeneratePublicKeys(e Engine, t io.StringWriter) error {
  739. if err := e.Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  740. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  741. return err
  742. }); err != nil {
  743. return err
  744. }
  745. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  746. isExist, err := util.IsExist(fPath)
  747. if err != nil {
  748. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  749. return err
  750. }
  751. if isExist {
  752. f, err := os.Open(fPath)
  753. if err != nil {
  754. return err
  755. }
  756. scanner := bufio.NewScanner(f)
  757. for scanner.Scan() {
  758. line := scanner.Text()
  759. if strings.HasPrefix(line, tplCommentPrefix) {
  760. scanner.Scan()
  761. continue
  762. }
  763. _, err = t.WriteString(line + "\n")
  764. if err != nil {
  765. f.Close()
  766. return err
  767. }
  768. }
  769. f.Close()
  770. }
  771. return nil
  772. }
  773. // ________ .__ ____ __.
  774. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  775. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  776. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  777. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  778. // \/ \/|__| \/ \/ \/\/
  779. // DeployKey represents deploy key information and its relation with repository.
  780. type DeployKey struct {
  781. ID int64 `xorm:"pk autoincr"`
  782. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  783. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  784. Name string
  785. Fingerprint string
  786. Content string `xorm:"-"`
  787. Mode AccessMode `xorm:"NOT NULL DEFAULT 1"`
  788. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  789. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  790. HasRecentActivity bool `xorm:"-"`
  791. HasUsed bool `xorm:"-"`
  792. }
  793. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  794. func (key *DeployKey) AfterLoad() {
  795. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  796. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > timeutil.TimeStampNow()
  797. }
  798. // GetContent gets associated public key content.
  799. func (key *DeployKey) GetContent() error {
  800. pkey, err := GetPublicKeyByID(key.KeyID)
  801. if err != nil {
  802. return err
  803. }
  804. key.Content = pkey.Content
  805. return nil
  806. }
  807. // IsReadOnly checks if the key can only be used for read operations
  808. func (key *DeployKey) IsReadOnly() bool {
  809. return key.Mode == AccessModeRead
  810. }
  811. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  812. // Note: We want error detail, not just true or false here.
  813. has, err := e.
  814. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  815. Get(new(DeployKey))
  816. if err != nil {
  817. return err
  818. } else if has {
  819. return ErrDeployKeyAlreadyExist{keyID, repoID}
  820. }
  821. has, err = e.
  822. Where("repo_id = ? AND name = ?", repoID, name).
  823. Get(new(DeployKey))
  824. if err != nil {
  825. return err
  826. } else if has {
  827. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  828. }
  829. return nil
  830. }
  831. // addDeployKey adds new key-repo relation.
  832. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string, mode AccessMode) (*DeployKey, error) {
  833. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  834. return nil, err
  835. }
  836. key := &DeployKey{
  837. KeyID: keyID,
  838. RepoID: repoID,
  839. Name: name,
  840. Fingerprint: fingerprint,
  841. Mode: mode,
  842. }
  843. _, err := e.Insert(key)
  844. return key, err
  845. }
  846. // HasDeployKey returns true if public key is a deploy key of given repository.
  847. func HasDeployKey(keyID, repoID int64) bool {
  848. has, _ := x.
  849. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  850. Get(new(DeployKey))
  851. return has
  852. }
  853. // AddDeployKey add new deploy key to database and authorized_keys file.
  854. func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
  855. fingerprint, err := calcFingerprint(content)
  856. if err != nil {
  857. return nil, err
  858. }
  859. accessMode := AccessModeRead
  860. if !readOnly {
  861. accessMode = AccessModeWrite
  862. }
  863. sess := x.NewSession()
  864. defer sess.Close()
  865. if err = sess.Begin(); err != nil {
  866. return nil, err
  867. }
  868. pkey := &PublicKey{
  869. Fingerprint: fingerprint,
  870. }
  871. has, err := sess.Get(pkey)
  872. if err != nil {
  873. return nil, err
  874. }
  875. if has {
  876. if pkey.Type != KeyTypeDeploy {
  877. return nil, ErrKeyAlreadyExist{0, fingerprint, ""}
  878. }
  879. } else {
  880. // First time use this deploy key.
  881. pkey.Mode = accessMode
  882. pkey.Type = KeyTypeDeploy
  883. pkey.Content = content
  884. pkey.Name = name
  885. if err = addKey(sess, pkey); err != nil {
  886. return nil, fmt.Errorf("addKey: %v", err)
  887. }
  888. }
  889. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
  890. if err != nil {
  891. return nil, err
  892. }
  893. return key, sess.Commit()
  894. }
  895. // GetDeployKeyByID returns deploy key by given ID.
  896. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  897. return getDeployKeyByID(x, id)
  898. }
  899. func getDeployKeyByID(e Engine, id int64) (*DeployKey, error) {
  900. key := new(DeployKey)
  901. has, err := e.ID(id).Get(key)
  902. if err != nil {
  903. return nil, err
  904. } else if !has {
  905. return nil, ErrDeployKeyNotExist{id, 0, 0}
  906. }
  907. return key, nil
  908. }
  909. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  910. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  911. return getDeployKeyByRepo(x, keyID, repoID)
  912. }
  913. func getDeployKeyByRepo(e Engine, keyID, repoID int64) (*DeployKey, error) {
  914. key := &DeployKey{
  915. KeyID: keyID,
  916. RepoID: repoID,
  917. }
  918. has, err := e.Get(key)
  919. if err != nil {
  920. return nil, err
  921. } else if !has {
  922. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  923. }
  924. return key, nil
  925. }
  926. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  927. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  928. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  929. return err
  930. }
  931. // UpdateDeployKey updates deploy key information.
  932. func UpdateDeployKey(key *DeployKey) error {
  933. _, err := x.ID(key.ID).AllCols().Update(key)
  934. return err
  935. }
  936. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  937. func DeleteDeployKey(doer *User, id int64) error {
  938. sess := x.NewSession()
  939. defer sess.Close()
  940. if err := sess.Begin(); err != nil {
  941. return err
  942. }
  943. if err := deleteDeployKey(sess, doer, id); err != nil {
  944. return err
  945. }
  946. return sess.Commit()
  947. }
  948. func deleteDeployKey(sess Engine, doer *User, id int64) error {
  949. key, err := getDeployKeyByID(sess, id)
  950. if err != nil {
  951. if IsErrDeployKeyNotExist(err) {
  952. return nil
  953. }
  954. return fmt.Errorf("GetDeployKeyByID: %v", err)
  955. }
  956. // Check if user has access to delete this key.
  957. if !doer.IsAdmin {
  958. repo, err := getRepositoryByID(sess, key.RepoID)
  959. if err != nil {
  960. return fmt.Errorf("GetRepositoryByID: %v", err)
  961. }
  962. has, err := isUserRepoAdmin(sess, repo, doer)
  963. if err != nil {
  964. return fmt.Errorf("GetUserRepoPermission: %v", err)
  965. } else if !has {
  966. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  967. }
  968. }
  969. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  970. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  971. }
  972. // Check if this is the last reference to same key content.
  973. has, err := sess.
  974. Where("key_id = ?", key.KeyID).
  975. Get(new(DeployKey))
  976. if err != nil {
  977. return err
  978. } else if !has {
  979. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  980. return err
  981. }
  982. // after deleted the public keys, should rewrite the public keys file
  983. if err = rewriteAllPublicKeys(sess); err != nil {
  984. return err
  985. }
  986. }
  987. return nil
  988. }
  989. // ListDeployKeys returns all deploy keys by given repository ID.
  990. func ListDeployKeys(repoID int64, listOptions ListOptions) ([]*DeployKey, error) {
  991. return listDeployKeys(x, repoID, listOptions)
  992. }
  993. func listDeployKeys(e Engine, repoID int64, listOptions ListOptions) ([]*DeployKey, error) {
  994. sess := e.Where("repo_id = ?", repoID)
  995. if listOptions.Page != 0 {
  996. sess = listOptions.setSessionPagination(sess)
  997. keys := make([]*DeployKey, 0, listOptions.PageSize)
  998. return keys, sess.Find(&keys)
  999. }
  1000. keys := make([]*DeployKey, 0, 5)
  1001. return keys, sess.Find(&keys)
  1002. }
  1003. // SearchDeployKeys returns a list of deploy keys matching the provided arguments.
  1004. func SearchDeployKeys(repoID, keyID int64, fingerprint string) ([]*DeployKey, error) {
  1005. keys := make([]*DeployKey, 0, 5)
  1006. cond := builder.NewCond()
  1007. if repoID != 0 {
  1008. cond = cond.And(builder.Eq{"repo_id": repoID})
  1009. }
  1010. if keyID != 0 {
  1011. cond = cond.And(builder.Eq{"key_id": keyID})
  1012. }
  1013. if fingerprint != "" {
  1014. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  1015. }
  1016. return keys, x.Where(cond).Find(&keys)
  1017. }
  1018. // __________ .__ .__ .__
  1019. // \______ _______|__| ____ ____ |_____________ | | ______
  1020. // | ___\_ __ | |/ \_/ ___\| \____ \__ \ | | / ___/
  1021. // | | | | \| | | \ \___| | |_> / __ \| |__\___ \
  1022. // |____| |__| |__|___| /\___ |__| __(____ |____/____ >
  1023. // \/ \/ |__| \/ \/
  1024. // AddPrincipalKey adds new principal to database and authorized_principals file.
  1025. func AddPrincipalKey(ownerID int64, content string, loginSourceID int64) (*PublicKey, error) {
  1026. sess := x.NewSession()
  1027. defer sess.Close()
  1028. if err := sess.Begin(); err != nil {
  1029. return nil, err
  1030. }
  1031. // Principals cannot be duplicated.
  1032. has, err := sess.
  1033. Where("content = ? AND type = ?", content, KeyTypePrincipal).
  1034. Get(new(PublicKey))
  1035. if err != nil {
  1036. return nil, err
  1037. } else if has {
  1038. return nil, ErrKeyAlreadyExist{0, "", content}
  1039. }
  1040. key := &PublicKey{
  1041. OwnerID: ownerID,
  1042. Name: content,
  1043. Content: content,
  1044. Mode: AccessModeWrite,
  1045. Type: KeyTypePrincipal,
  1046. LoginSourceID: loginSourceID,
  1047. }
  1048. if err = addPrincipalKey(sess, key); err != nil {
  1049. return nil, fmt.Errorf("addKey: %v", err)
  1050. }
  1051. if err = sess.Commit(); err != nil {
  1052. return nil, err
  1053. }
  1054. sess.Close()
  1055. return key, RewriteAllPrincipalKeys()
  1056. }
  1057. func addPrincipalKey(e Engine, key *PublicKey) (err error) {
  1058. // Save Key representing a principal.
  1059. if _, err = e.Insert(key); err != nil {
  1060. return err
  1061. }
  1062. return nil
  1063. }
  1064. // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines
  1065. func CheckPrincipalKeyString(user *User, content string) (_ string, err error) {
  1066. if setting.SSH.Disabled {
  1067. return "", ErrSSHDisabled{}
  1068. }
  1069. content = strings.TrimSpace(content)
  1070. if strings.ContainsAny(content, "\r\n") {
  1071. return "", errors.New("only a single line with a single principal please")
  1072. }
  1073. // check all the allowed principals, email, username or anything
  1074. // if any matches, return ok
  1075. for _, v := range setting.SSH.AuthorizedPrincipalsAllow {
  1076. switch v {
  1077. case "anything":
  1078. return content, nil
  1079. case "email":
  1080. emails, err := GetEmailAddresses(user.ID)
  1081. if err != nil {
  1082. return "", err
  1083. }
  1084. for _, email := range emails {
  1085. if !email.IsActivated {
  1086. continue
  1087. }
  1088. if content == email.Email {
  1089. return content, nil
  1090. }
  1091. }
  1092. case "username":
  1093. if content == user.Name {
  1094. return content, nil
  1095. }
  1096. }
  1097. }
  1098. return "", fmt.Errorf("didn't match allowed principals: %s", setting.SSH.AuthorizedPrincipalsAllow)
  1099. }
  1100. // RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again.
  1101. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  1102. // outside any session scope independently.
  1103. func RewriteAllPrincipalKeys() error {
  1104. return rewriteAllPrincipalKeys(x)
  1105. }
  1106. func rewriteAllPrincipalKeys(e Engine) error {
  1107. // Don't rewrite key if internal server
  1108. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedPrincipalsFile {
  1109. return nil
  1110. }
  1111. sshOpLocker.Lock()
  1112. defer sshOpLocker.Unlock()
  1113. if setting.SSH.RootPath != "" {
  1114. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  1115. // This of course doesn't guarantee that this is the right directory for authorized_keys
  1116. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  1117. // right user it will at least be created properly.
  1118. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  1119. if err != nil {
  1120. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  1121. return err
  1122. }
  1123. }
  1124. fPath := filepath.Join(setting.SSH.RootPath, authorizedPrincipalsFile)
  1125. tmpPath := fPath + ".tmp"
  1126. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
  1127. if err != nil {
  1128. return err
  1129. }
  1130. defer func() {
  1131. t.Close()
  1132. os.Remove(tmpPath)
  1133. }()
  1134. if setting.SSH.AuthorizedPrincipalsBackup {
  1135. isExist, err := util.IsExist(fPath)
  1136. if err != nil {
  1137. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  1138. return err
  1139. }
  1140. if isExist {
  1141. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  1142. if err = util.CopyFile(fPath, bakPath); err != nil {
  1143. return err
  1144. }
  1145. }
  1146. }
  1147. if err := regeneratePrincipalKeys(e, t); err != nil {
  1148. return err
  1149. }
  1150. t.Close()
  1151. return os.Rename(tmpPath, fPath)
  1152. }
  1153. // ListPrincipalKeys returns a list of principals belongs to given user.
  1154. func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
  1155. sess := x.Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal)
  1156. if listOptions.Page != 0 {
  1157. sess = listOptions.setSessionPagination(sess)
  1158. keys := make([]*PublicKey, 0, listOptions.PageSize)
  1159. return keys, sess.Find(&keys)
  1160. }
  1161. keys := make([]*PublicKey, 0, 5)
  1162. return keys, sess.Find(&keys)
  1163. }
  1164. // RegeneratePrincipalKeys regenerates the authorized_principals file
  1165. func RegeneratePrincipalKeys(t io.StringWriter) error {
  1166. return regeneratePrincipalKeys(x, t)
  1167. }
  1168. func regeneratePrincipalKeys(e Engine, t io.StringWriter) error {
  1169. if err := e.Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  1170. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  1171. return err
  1172. }); err != nil {
  1173. return err
  1174. }
  1175. fPath := filepath.Join(setting.SSH.RootPath, authorizedPrincipalsFile)
  1176. isExist, err := util.IsExist(fPath)
  1177. if err != nil {
  1178. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  1179. return err
  1180. }
  1181. if isExist {
  1182. f, err := os.Open(fPath)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. scanner := bufio.NewScanner(f)
  1187. for scanner.Scan() {
  1188. line := scanner.Text()
  1189. if strings.HasPrefix(line, tplCommentPrefix) {
  1190. scanner.Scan()
  1191. continue
  1192. }
  1193. _, err = t.WriteString(line + "\n")
  1194. if err != nil {
  1195. f.Close()
  1196. return err
  1197. }
  1198. }
  1199. f.Close()
  1200. }
  1201. return nil
  1202. }