tls.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package tls
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "crypto/x509"
  6. "crypto/x509/pkix"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "math/big"
  12. "os"
  13. "time"
  14. "filippo.io/edwards25519"
  15. "github.com/kr/pretty"
  16. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  17. )
  18. type (
  19. Key struct {
  20. point *edwards25519.Point
  21. }
  22. )
  23. // NewKey generates a new key.
  24. func NewKey() *Key {
  25. seed := make([]byte, 64)
  26. rand.Reader.Read(seed)
  27. s := (&edwards25519.Scalar{}).SetUniformBytes(seed)
  28. return &Key{(&edwards25519.Point{}).ScalarBaseMult(s)}
  29. }
  30. // Ed25519PrivateKey returns the private key in Edwards form used for EdDSA.
  31. func (n *Key) Ed25519PrivateKey() (ed25519.PrivateKey, error) {
  32. if n.point == nil {
  33. return ed25519.PrivateKey{}, errors.New("nil point")
  34. }
  35. if len(n.point.Bytes()) != ed25519.SeedSize {
  36. return ed25519.PrivateKey{}, errors.New("incorrect seed size")
  37. }
  38. return ed25519.NewKeyFromSeed(n.point.Bytes()), nil
  39. }
  40. // Curve25519PrivateKey returns the private key in Montogomery form used for ECDH.
  41. func (n *Key) Curve25519PrivateKey() (wgtypes.Key, error) {
  42. if n.point == nil {
  43. return wgtypes.Key{}, errors.New("nil point")
  44. }
  45. if len(n.point.Bytes()) != ed25519.SeedSize {
  46. return wgtypes.Key{}, errors.New("incorrect seed size")
  47. }
  48. return wgtypes.ParseKey(base64.StdEncoding.EncodeToString(n.point.BytesMontgomery()))
  49. }
  50. // Save : saves the private key to path.
  51. func (n *Key) Save(path string) error {
  52. f, err := os.Create(path)
  53. if err != nil {
  54. return err
  55. }
  56. defer f.Close()
  57. f.Write(n.point.Bytes())
  58. return nil
  59. }
  60. // Reads the private key from path.
  61. func ReadFrom(path string) (*Key, error) {
  62. key, err := os.ReadFile(path)
  63. if err != nil {
  64. return nil, err
  65. }
  66. point, err := (&edwards25519.Point{}).SetBytes(key)
  67. if err != nil {
  68. return nil, err
  69. }
  70. return &Key{point}, nil
  71. }
  72. // creates a new pkix.Name
  73. func NewName(commonName, country, org string) pkix.Name {
  74. res := NewCName(commonName)
  75. res.Country = []string{country}
  76. res.Organization = []string{org}
  77. return res
  78. }
  79. // creates a new pkix.Name with only a common name
  80. func NewCName(commonName string) pkix.Name {
  81. return pkix.Name{
  82. CommonName: commonName,
  83. }
  84. }
  85. // creates a new certificate signing request for a
  86. func NewCSR(key ed25519.PrivateKey, name pkix.Name) (*x509.CertificateRequest, error) {
  87. derCertRequest, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
  88. Subject: name,
  89. PublicKey: key.Public().(ed25519.PublicKey),
  90. }, key)
  91. if err != nil {
  92. return nil, err
  93. }
  94. csr, err := x509.ParseCertificateRequest(derCertRequest)
  95. if err != nil {
  96. return nil, err
  97. }
  98. return csr, nil
  99. }
  100. // returns a new self-signed certificate
  101. func SelfSignedCA(key ed25519.PrivateKey, req *x509.CertificateRequest, days int) (*x509.Certificate, error) {
  102. template := &x509.Certificate{
  103. BasicConstraintsValid: true,
  104. IsCA: true,
  105. Version: req.Version,
  106. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  107. NotAfter: time.Now().Add(duration(days)),
  108. NotBefore: time.Now(),
  109. SerialNumber: serialNumber(),
  110. PublicKey: key.Public(),
  111. Subject: pkix.Name{
  112. CommonName: req.Subject.CommonName,
  113. Organization: req.Subject.Organization,
  114. Country: req.Subject.Country,
  115. },
  116. }
  117. rootCa, err := x509.CreateCertificate(rand.Reader, template, template, req.PublicKey, key)
  118. if err != nil {
  119. return nil, err
  120. }
  121. result, err := x509.ParseCertificate(rootCa)
  122. if err != nil {
  123. return nil, err
  124. }
  125. return result, nil
  126. }
  127. // issues a new certificate from a parent certificate authority
  128. func NewEndEntityCert(key ed25519.PrivateKey, req *x509.CertificateRequest, parent *x509.Certificate, days int) (*x509.Certificate, error) {
  129. template := &x509.Certificate{
  130. Version: req.Version,
  131. NotBefore: time.Now(),
  132. NotAfter: time.Now().Add(duration(days)),
  133. SerialNumber: serialNumber(),
  134. SignatureAlgorithm: req.SignatureAlgorithm,
  135. PublicKeyAlgorithm: req.PublicKeyAlgorithm,
  136. PublicKey: req.PublicKey,
  137. Subject: req.Subject,
  138. SubjectKeyId: req.RawSubject,
  139. Issuer: parent.Subject,
  140. }
  141. pretty.Println(req.PublicKey)
  142. rootCa, err := x509.CreateCertificate(rand.Reader, template, parent, req.PublicKey, key)
  143. if err != nil {
  144. return nil, err
  145. }
  146. result, err := x509.ParseCertificate(rootCa)
  147. if err != nil {
  148. return nil, err
  149. }
  150. return result, nil
  151. }
  152. func SaveCert(path, name string, cert *x509.Certificate) error {
  153. //certbytes, err := x509.ParseCertificate(cert)
  154. if err := os.MkdirAll(path, 0644); err != nil {
  155. return fmt.Errorf("failed to create dir %s %w", path, err)
  156. }
  157. certOut, err := os.Create(path + name)
  158. if err != nil {
  159. return fmt.Errorf("failed to open certficate file for writing: %v", err)
  160. }
  161. defer certOut.Close()
  162. if err := pem.Encode(certOut, &pem.Block{
  163. Type: "CERTIFICATE",
  164. Bytes: cert.Raw,
  165. }); err != nil {
  166. return fmt.Errorf("failed to write certificate to file %v", err)
  167. }
  168. return nil
  169. }
  170. func SaveKey(path, name string, key ed25519.PrivateKey) error {
  171. //func SaveKey(name string, key *ecdsa.PrivateKey) error {
  172. if err := os.MkdirAll(path, 0644); err != nil {
  173. return fmt.Errorf("failed to create dir %s %w", path, err)
  174. }
  175. keyOut, err := os.Create(path + name)
  176. if err != nil {
  177. return fmt.Errorf("failed open key file for writing: %v", err)
  178. }
  179. defer keyOut.Close()
  180. privBytes, err := x509.MarshalPKCS8PrivateKey(key)
  181. if err != nil {
  182. return fmt.Errorf("failedto marshal key %v ", err)
  183. }
  184. if err := pem.Encode(keyOut, &pem.Block{
  185. Type: "PRIVATE KEY",
  186. Bytes: privBytes,
  187. }); err != nil {
  188. return fmt.Errorf("failed to write key to file %v", err)
  189. }
  190. return nil
  191. }
  192. func ReadCert(name string) (*x509.Certificate, error) {
  193. contents, err := os.ReadFile(name)
  194. if err != nil {
  195. return nil, fmt.Errorf("unable to read file %w", err)
  196. }
  197. block, _ := pem.Decode(contents)
  198. if block == nil || block.Type != "CERTIFICATE" {
  199. return nil, errors.New("not a cert " + block.Type)
  200. }
  201. cert, err := x509.ParseCertificate(block.Bytes)
  202. if err != nil {
  203. return nil, fmt.Errorf("unable to parse cert %w", err)
  204. }
  205. return cert, nil
  206. }
  207. func ReadKey(name string) (*ed25519.PrivateKey, error) {
  208. bytes, err := os.ReadFile(name)
  209. if err != nil {
  210. return nil, fmt.Errorf("unable to read file %w", err)
  211. }
  212. keyBytes, _ := pem.Decode(bytes)
  213. key, err := x509.ParsePKCS8PrivateKey(keyBytes.Bytes)
  214. if err != nil {
  215. return nil, fmt.Errorf("unable to parse file %w", err)
  216. }
  217. private := key.(ed25519.PrivateKey)
  218. return &private, nil
  219. }
  220. func serialNumber() *big.Int {
  221. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  222. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  223. if err != nil {
  224. return nil
  225. }
  226. return serialNumber
  227. }
  228. func duration(days int) time.Duration {
  229. hours := days * 24
  230. duration, err := time.ParseDuration(fmt.Sprintf("%dh", hours))
  231. if err != nil {
  232. duration = time.Until(time.Now().Add(time.Hour * 24))
  233. }
  234. return duration
  235. }