tls.go 7.9 KB

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