(req dto.RootCertOperate)
| 436 | } |
| 437 | |
| 438 | func (u *SSHService) CreateRootCert(req dto.RootCertOperate) error { |
| 439 | if cmd.CheckIllegal(req.EncryptionMode, req.PassPhrase) { |
| 440 | return buserr.New("ErrCmdIllegal") |
| 441 | } |
| 442 | certItem, _ := hostRepo.GetCert(repo.WithByName(req.Name)) |
| 443 | if certItem.ID != 0 { |
| 444 | return buserr.New("ErrRecordExist") |
| 445 | } |
| 446 | currentUser, err := user.Current() |
| 447 | if err != nil { |
| 448 | return fmt.Errorf("load current user failed, err: %v", err) |
| 449 | } |
| 450 | var cert model.RootCert |
| 451 | if err := copier.Copy(&cert, req); err != nil { |
| 452 | return err |
| 453 | } |
| 454 | privatePath := fmt.Sprintf("%s/.ssh/%s", currentUser.HomeDir, req.Name) |
| 455 | publicPath := fmt.Sprintf("%s/.ssh/%s.pub", currentUser.HomeDir, req.Name) |
| 456 | authFilePath := currentUser.HomeDir + "/.ssh/authorized_keys" |
| 457 | |
| 458 | if info, err := os.Stat(authFilePath); err == nil && info.Size() > 0 { |
| 459 | f, err := os.Open(authFilePath) |
| 460 | if err != nil { |
| 461 | return err |
| 462 | } |
| 463 | defer func() { _ = f.Close() }() |
| 464 | |
| 465 | if _, err := f.Seek(-1, 2); err == nil { |
| 466 | buf := make([]byte, 1) |
| 467 | if _, err := f.Read(buf); err == nil && buf[0] != '\n' { |
| 468 | appendFile, err := os.OpenFile(authFilePath, os.O_APPEND|os.O_WRONLY, 0600) |
| 469 | if err != nil { |
| 470 | return err |
| 471 | } |
| 472 | if _, err := appendFile.Write([]byte("\n")); err != nil { |
| 473 | _ = appendFile.Close() |
| 474 | return err |
| 475 | } |
| 476 | _ = appendFile.Close() |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | if req.Mode == "input" || req.Mode == "import" { |
| 482 | if err := os.WriteFile(privatePath, []byte(req.PrivateKey), constant.FilePerm); err != nil { |
| 483 | return err |
| 484 | } |
| 485 | if err := os.WriteFile(publicPath, []byte(req.PublicKey), constant.FilePerm); err != nil { |
| 486 | return err |
| 487 | } |
| 488 | } else { |
| 489 | tmpPrivatePath := privatePath + ".tmp" |
| 490 | tmpPublicPath := privatePath + ".tmp.pub" |
| 491 | cmdMgr := cmd.NewCommandMgr(cmd.WithTimeout(2 * time.Minute)) |
| 492 | args := []string{ |
| 493 | "-t", req.EncryptionMode, |
| 494 | "-f", tmpPrivatePath, |
| 495 | "-N", req.PassPhrase, |
nothing calls this directly
no test coverage detected