ctx.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // Copyright (C) 2017. See AUTHORS.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package openssl
  15. // #include "shim.h"
  16. import "C"
  17. import (
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "os"
  22. "runtime"
  23. "sync"
  24. "time"
  25. "unsafe"
  26. "github.com/spacemonkeygo/spacelog"
  27. )
  28. var (
  29. ssl_ctx_idx = C.X_SSL_CTX_new_index()
  30. logger = spacelog.GetLogger()
  31. )
  32. type Ctx struct {
  33. ctx *C.SSL_CTX
  34. cert *Certificate
  35. chain []*Certificate
  36. key PrivateKey
  37. verify_cb VerifyCallback
  38. sni_cb TLSExtServernameCallback
  39. ticket_store_mu sync.Mutex
  40. ticket_store *TicketStore
  41. }
  42. //export get_ssl_ctx_idx
  43. func get_ssl_ctx_idx() C.int {
  44. return ssl_ctx_idx
  45. }
  46. func newCtx(method *C.SSL_METHOD) (*Ctx, error) {
  47. runtime.LockOSThread()
  48. defer runtime.UnlockOSThread()
  49. ctx := C.SSL_CTX_new(method)
  50. if ctx == nil {
  51. return nil, errorFromErrorQueue()
  52. }
  53. c := &Ctx{ctx: ctx}
  54. C.SSL_CTX_set_ex_data(ctx, get_ssl_ctx_idx(), unsafe.Pointer(c))
  55. runtime.SetFinalizer(c, func(c *Ctx) {
  56. C.SSL_CTX_free(c.ctx)
  57. })
  58. return c, nil
  59. }
  60. type SSLVersion int
  61. const (
  62. SSLv3 SSLVersion = 0x02 // Vulnerable to "POODLE" attack.
  63. TLSv1 SSLVersion = 0x03
  64. TLSv1_1 SSLVersion = 0x04
  65. TLSv1_2 SSLVersion = 0x05
  66. // Make sure to disable SSLv2 and SSLv3 if you use this. SSLv3 is vulnerable
  67. // to the "POODLE" attack, and SSLv2 is what, just don't even.
  68. AnyVersion SSLVersion = 0x06
  69. )
  70. // NewCtxWithVersion creates an SSL context that is specific to the provided
  71. // SSL version. See http://www.openssl.org/docs/ssl/SSL_CTX_new.html for more.
  72. func NewCtxWithVersion(version SSLVersion) (*Ctx, error) {
  73. var method *C.SSL_METHOD
  74. switch version {
  75. case SSLv3:
  76. method = C.X_SSLv3_method()
  77. case TLSv1:
  78. method = C.X_TLSv1_method()
  79. case TLSv1_1:
  80. method = C.X_TLSv1_1_method()
  81. case TLSv1_2:
  82. method = C.X_TLSv1_2_method()
  83. case AnyVersion:
  84. method = C.X_SSLv23_method()
  85. }
  86. if method == nil {
  87. return nil, errors.New("unknown ssl/tls version")
  88. }
  89. return newCtx(method)
  90. }
  91. // NewCtx creates a context that supports any TLS version 1.0 and newer.
  92. func NewCtx() (*Ctx, error) {
  93. c, err := NewCtxWithVersion(AnyVersion)
  94. if err == nil {
  95. c.SetOptions(NoSSLv2 | NoSSLv3)
  96. }
  97. return c, err
  98. }
  99. // NewCtxFromFiles calls NewCtx, loads the provided files, and configures the
  100. // context to use them.
  101. func NewCtxFromFiles(cert_file string, key_file string) (*Ctx, error) {
  102. ctx, err := NewCtx()
  103. if err != nil {
  104. return nil, err
  105. }
  106. cert_bytes, err := ioutil.ReadFile(cert_file)
  107. if err != nil {
  108. return nil, err
  109. }
  110. certs := SplitPEM(cert_bytes)
  111. if len(certs) == 0 {
  112. return nil, fmt.Errorf("No PEM certificate found in '%s'", cert_file)
  113. }
  114. first, certs := certs[0], certs[1:]
  115. cert, err := LoadCertificateFromPEM(first)
  116. if err != nil {
  117. return nil, err
  118. }
  119. err = ctx.UseCertificate(cert)
  120. if err != nil {
  121. return nil, err
  122. }
  123. for _, pem := range certs {
  124. cert, err := LoadCertificateFromPEM(pem)
  125. if err != nil {
  126. return nil, err
  127. }
  128. err = ctx.AddChainCertificate(cert)
  129. if err != nil {
  130. return nil, err
  131. }
  132. }
  133. key_bytes, err := ioutil.ReadFile(key_file)
  134. if err != nil {
  135. return nil, err
  136. }
  137. key, err := LoadPrivateKeyFromPEM(key_bytes)
  138. if err != nil {
  139. return nil, err
  140. }
  141. err = ctx.UsePrivateKey(key)
  142. if err != nil {
  143. return nil, err
  144. }
  145. return ctx, nil
  146. }
  147. // EllipticCurve repesents the ASN.1 OID of an elliptic curve.
  148. // see https://www.openssl.org/docs/apps/ecparam.html for a list of implemented curves.
  149. type EllipticCurve int
  150. const (
  151. // P-256: X9.62/SECG curve over a 256 bit prime field
  152. Prime256v1 EllipticCurve = C.NID_X9_62_prime256v1
  153. // P-384: NIST/SECG curve over a 384 bit prime field
  154. Secp384r1 EllipticCurve = C.NID_secp384r1
  155. )
  156. // SetEllipticCurve sets the elliptic curve used by the SSL context to
  157. // enable an ECDH cipher suite to be selected during the handshake.
  158. func (c *Ctx) SetEllipticCurve(curve EllipticCurve) error {
  159. runtime.LockOSThread()
  160. defer runtime.UnlockOSThread()
  161. k := C.EC_KEY_new_by_curve_name(C.int(curve))
  162. if k == nil {
  163. return errors.New("Unknown curve")
  164. }
  165. defer C.EC_KEY_free(k)
  166. if int(C.X_SSL_CTX_set_tmp_ecdh(c.ctx, k)) != 1 {
  167. return errorFromErrorQueue()
  168. }
  169. return nil
  170. }
  171. // UseCertificate configures the context to present the given certificate to
  172. // peers.
  173. func (c *Ctx) UseCertificate(cert *Certificate) error {
  174. runtime.LockOSThread()
  175. defer runtime.UnlockOSThread()
  176. c.cert = cert
  177. if int(C.SSL_CTX_use_certificate(c.ctx, cert.x)) != 1 {
  178. return errorFromErrorQueue()
  179. }
  180. return nil
  181. }
  182. // AddChainCertificate adds a certificate to the chain presented in the
  183. // handshake.
  184. func (c *Ctx) AddChainCertificate(cert *Certificate) error {
  185. runtime.LockOSThread()
  186. defer runtime.UnlockOSThread()
  187. c.chain = append(c.chain, cert)
  188. if int(C.X_SSL_CTX_add_extra_chain_cert(c.ctx, cert.x)) != 1 {
  189. return errorFromErrorQueue()
  190. }
  191. // OpenSSL takes ownership via SSL_CTX_add_extra_chain_cert
  192. runtime.SetFinalizer(cert, nil)
  193. return nil
  194. }
  195. // UsePrivateKey configures the context to use the given private key for SSL
  196. // handshakes.
  197. func (c *Ctx) UsePrivateKey(key PrivateKey) error {
  198. runtime.LockOSThread()
  199. defer runtime.UnlockOSThread()
  200. c.key = key
  201. if int(C.SSL_CTX_use_PrivateKey(c.ctx, key.evpPKey())) != 1 {
  202. return errorFromErrorQueue()
  203. }
  204. return nil
  205. }
  206. type CertificateStore struct {
  207. store *C.X509_STORE
  208. // for GC
  209. ctx *Ctx
  210. certs []*Certificate
  211. }
  212. // Allocate a new, empty CertificateStore
  213. func NewCertificateStore() (*CertificateStore, error) {
  214. s := C.X509_STORE_new()
  215. if s == nil {
  216. return nil, errors.New("failed to allocate X509_STORE")
  217. }
  218. store := &CertificateStore{store: s}
  219. runtime.SetFinalizer(store, func(s *CertificateStore) {
  220. C.X509_STORE_free(s.store)
  221. })
  222. return store, nil
  223. }
  224. // Parse a chained PEM file, loading all certificates into the Store.
  225. func (s *CertificateStore) LoadCertificatesFromPEM(data []byte) error {
  226. pems := SplitPEM(data)
  227. for _, pem := range pems {
  228. cert, err := LoadCertificateFromPEM(pem)
  229. if err != nil {
  230. return err
  231. }
  232. err = s.AddCertificate(cert)
  233. if err != nil {
  234. return err
  235. }
  236. }
  237. return nil
  238. }
  239. // GetCertificateStore returns the context's certificate store that will be
  240. // used for peer validation.
  241. func (c *Ctx) GetCertificateStore() *CertificateStore {
  242. // we don't need to dealloc the cert store pointer here, because it points
  243. // to a ctx internal. so we do need to keep the ctx around
  244. return &CertificateStore{
  245. store: C.SSL_CTX_get_cert_store(c.ctx),
  246. ctx: c}
  247. }
  248. // AddCertificate marks the provided Certificate as a trusted certificate in
  249. // the given CertificateStore.
  250. func (s *CertificateStore) AddCertificate(cert *Certificate) error {
  251. runtime.LockOSThread()
  252. defer runtime.UnlockOSThread()
  253. s.certs = append(s.certs, cert)
  254. if int(C.X509_STORE_add_cert(s.store, cert.x)) != 1 {
  255. return errorFromErrorQueue()
  256. }
  257. return nil
  258. }
  259. type CertificateStoreCtx struct {
  260. ctx *C.X509_STORE_CTX
  261. ssl_ctx *Ctx
  262. }
  263. func (self *CertificateStoreCtx) VerifyResult() VerifyResult {
  264. return VerifyResult(C.X509_STORE_CTX_get_error(self.ctx))
  265. }
  266. func (self *CertificateStoreCtx) Err() error {
  267. code := C.X509_STORE_CTX_get_error(self.ctx)
  268. if code == C.X509_V_OK {
  269. return nil
  270. }
  271. return fmt.Errorf("openssl: %s",
  272. C.GoString(C.X509_verify_cert_error_string(C.long(code))))
  273. }
  274. func (self *CertificateStoreCtx) Depth() int {
  275. return int(C.X509_STORE_CTX_get_error_depth(self.ctx))
  276. }
  277. // the certicate returned is only valid for the lifetime of the underlying
  278. // X509_STORE_CTX
  279. func (self *CertificateStoreCtx) GetCurrentCert() *Certificate {
  280. x509 := C.X509_STORE_CTX_get_current_cert(self.ctx)
  281. if x509 == nil {
  282. return nil
  283. }
  284. // add a ref
  285. if 1 != C.X_X509_add_ref(x509) {
  286. return nil
  287. }
  288. cert := &Certificate{
  289. x: x509,
  290. }
  291. runtime.SetFinalizer(cert, func(cert *Certificate) {
  292. C.X509_free(cert.x)
  293. })
  294. return cert
  295. }
  296. // LoadVerifyLocations tells the context to trust all certificate authorities
  297. // provided in either the ca_file or the ca_path.
  298. // See http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html for
  299. // more.
  300. func (c *Ctx) LoadVerifyLocations(ca_file string, ca_path string) error {
  301. runtime.LockOSThread()
  302. defer runtime.UnlockOSThread()
  303. var c_ca_file, c_ca_path *C.char
  304. if ca_file != "" {
  305. c_ca_file = C.CString(ca_file)
  306. defer C.free(unsafe.Pointer(c_ca_file))
  307. }
  308. if ca_path != "" {
  309. c_ca_path = C.CString(ca_path)
  310. defer C.free(unsafe.Pointer(c_ca_path))
  311. }
  312. if C.SSL_CTX_load_verify_locations(c.ctx, c_ca_file, c_ca_path) != 1 {
  313. return errorFromErrorQueue()
  314. }
  315. return nil
  316. }
  317. type Options int
  318. const (
  319. // NoCompression is only valid if you are using OpenSSL 1.0.1 or newer
  320. NoCompression Options = C.SSL_OP_NO_COMPRESSION
  321. NoSSLv2 Options = C.SSL_OP_NO_SSLv2
  322. NoSSLv3 Options = C.SSL_OP_NO_SSLv3
  323. NoTLSv1 Options = C.SSL_OP_NO_TLSv1
  324. CipherServerPreference Options = C.SSL_OP_CIPHER_SERVER_PREFERENCE
  325. NoSessionResumptionOrRenegotiation Options = C.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  326. NoTicket Options = C.SSL_OP_NO_TICKET
  327. )
  328. // SetOptions sets context options. See
  329. // http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
  330. func (c *Ctx) SetOptions(options Options) Options {
  331. return Options(C.X_SSL_CTX_set_options(
  332. c.ctx, C.long(options)))
  333. }
  334. func (c *Ctx) ClearOptions(options Options) Options {
  335. return Options(C.X_SSL_CTX_clear_options(
  336. c.ctx, C.long(options)))
  337. }
  338. // GetOptions returns context options. See
  339. // https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
  340. func (c *Ctx) GetOptions() Options {
  341. return Options(C.X_SSL_CTX_get_options(c.ctx))
  342. }
  343. type Modes int
  344. const (
  345. // ReleaseBuffers is only valid if you are using OpenSSL 1.0.1 or newer
  346. ReleaseBuffers Modes = C.SSL_MODE_RELEASE_BUFFERS
  347. )
  348. // SetMode sets context modes. See
  349. // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html
  350. func (c *Ctx) SetMode(modes Modes) Modes {
  351. return Modes(C.X_SSL_CTX_set_mode(c.ctx, C.long(modes)))
  352. }
  353. // GetMode returns context modes. See
  354. // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html
  355. func (c *Ctx) GetMode() Modes {
  356. return Modes(C.X_SSL_CTX_get_mode(c.ctx))
  357. }
  358. type VerifyOptions int
  359. const (
  360. VerifyNone VerifyOptions = C.SSL_VERIFY_NONE
  361. VerifyPeer VerifyOptions = C.SSL_VERIFY_PEER
  362. VerifyFailIfNoPeerCert VerifyOptions = C.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  363. VerifyClientOnce VerifyOptions = C.SSL_VERIFY_CLIENT_ONCE
  364. )
  365. type VerifyCallback func(ok bool, store *CertificateStoreCtx) bool
  366. //export go_ssl_ctx_verify_cb_thunk
  367. func go_ssl_ctx_verify_cb_thunk(p unsafe.Pointer, ok C.int, ctx *C.X509_STORE_CTX) C.int {
  368. defer func() {
  369. if err := recover(); err != nil {
  370. logger.Critf("openssl: verify callback panic'd: %v", err)
  371. os.Exit(1)
  372. }
  373. }()
  374. verify_cb := (*Ctx)(p).verify_cb
  375. // set up defaults just in case verify_cb is nil
  376. if verify_cb != nil {
  377. store := &CertificateStoreCtx{ctx: ctx}
  378. if verify_cb(ok == 1, store) {
  379. ok = 1
  380. } else {
  381. ok = 0
  382. }
  383. }
  384. return ok
  385. }
  386. // SetVerify controls peer verification settings. See
  387. // http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
  388. func (c *Ctx) SetVerify(options VerifyOptions, verify_cb VerifyCallback) {
  389. c.verify_cb = verify_cb
  390. if verify_cb != nil {
  391. C.SSL_CTX_set_verify(c.ctx, C.int(options), (*[0]byte)(C.X_SSL_CTX_verify_cb))
  392. } else {
  393. C.SSL_CTX_set_verify(c.ctx, C.int(options), nil)
  394. }
  395. }
  396. func (c *Ctx) SetVerifyMode(options VerifyOptions) {
  397. c.SetVerify(options, c.verify_cb)
  398. }
  399. func (c *Ctx) SetVerifyCallback(verify_cb VerifyCallback) {
  400. c.SetVerify(c.VerifyMode(), verify_cb)
  401. }
  402. func (c *Ctx) GetVerifyCallback() VerifyCallback {
  403. return c.verify_cb
  404. }
  405. func (c *Ctx) VerifyMode() VerifyOptions {
  406. return VerifyOptions(C.SSL_CTX_get_verify_mode(c.ctx))
  407. }
  408. // SetVerifyDepth controls how many certificates deep the certificate
  409. // verification logic is willing to follow a certificate chain. See
  410. // https://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
  411. func (c *Ctx) SetVerifyDepth(depth int) {
  412. C.SSL_CTX_set_verify_depth(c.ctx, C.int(depth))
  413. }
  414. // GetVerifyDepth controls how many certificates deep the certificate
  415. // verification logic is willing to follow a certificate chain. See
  416. // https://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
  417. func (c *Ctx) GetVerifyDepth() int {
  418. return int(C.SSL_CTX_get_verify_depth(c.ctx))
  419. }
  420. type TLSExtServernameCallback func(ssl *SSL) SSLTLSExtErr
  421. // SetTLSExtServernameCallback sets callback function for Server Name Indication
  422. // (SNI) rfc6066 (http://tools.ietf.org/html/rfc6066). See
  423. // http://stackoverflow.com/questions/22373332/serving-multiple-domains-in-one-box-with-sni
  424. func (c *Ctx) SetTLSExtServernameCallback(sni_cb TLSExtServernameCallback) {
  425. c.sni_cb = sni_cb
  426. C.X_SSL_CTX_set_tlsext_servername_callback(c.ctx, (*[0]byte)(C.sni_cb))
  427. }
  428. func (c *Ctx) SetSessionId(session_id []byte) error {
  429. runtime.LockOSThread()
  430. defer runtime.UnlockOSThread()
  431. var ptr *C.uchar
  432. if len(session_id) > 0 {
  433. ptr = (*C.uchar)(unsafe.Pointer(&session_id[0]))
  434. }
  435. if int(C.SSL_CTX_set_session_id_context(c.ctx, ptr,
  436. C.uint(len(session_id)))) == 0 {
  437. return errorFromErrorQueue()
  438. }
  439. return nil
  440. }
  441. // SetCipherList sets the list of available ciphers. The format of the list is
  442. // described at http://www.openssl.org/docs/apps/ciphers.html, but see
  443. // http://www.openssl.org/docs/ssl/SSL_CTX_set_cipher_list.html for more.
  444. func (c *Ctx) SetCipherList(list string) error {
  445. runtime.LockOSThread()
  446. defer runtime.UnlockOSThread()
  447. clist := C.CString(list)
  448. defer C.free(unsafe.Pointer(clist))
  449. if int(C.SSL_CTX_set_cipher_list(c.ctx, clist)) == 0 {
  450. return errorFromErrorQueue()
  451. }
  452. return nil
  453. }
  454. type SessionCacheModes int
  455. const (
  456. SessionCacheOff SessionCacheModes = C.SSL_SESS_CACHE_OFF
  457. SessionCacheClient SessionCacheModes = C.SSL_SESS_CACHE_CLIENT
  458. SessionCacheServer SessionCacheModes = C.SSL_SESS_CACHE_SERVER
  459. SessionCacheBoth SessionCacheModes = C.SSL_SESS_CACHE_BOTH
  460. NoAutoClear SessionCacheModes = C.SSL_SESS_CACHE_NO_AUTO_CLEAR
  461. NoInternalLookup SessionCacheModes = C.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
  462. NoInternalStore SessionCacheModes = C.SSL_SESS_CACHE_NO_INTERNAL_STORE
  463. NoInternal SessionCacheModes = C.SSL_SESS_CACHE_NO_INTERNAL
  464. )
  465. // SetSessionCacheMode enables or disables session caching. See
  466. // http://www.openssl.org/docs/ssl/SSL_CTX_set_session_cache_mode.html
  467. func (c *Ctx) SetSessionCacheMode(modes SessionCacheModes) SessionCacheModes {
  468. return SessionCacheModes(
  469. C.X_SSL_CTX_set_session_cache_mode(c.ctx, C.long(modes)))
  470. }
  471. // Set session cache timeout. Returns previously set value.
  472. // See https://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html
  473. func (c *Ctx) SetTimeout(t time.Duration) time.Duration {
  474. prev := C.X_SSL_CTX_set_timeout(c.ctx, C.long(t/time.Second))
  475. return time.Duration(prev) * time.Second
  476. }
  477. // Get session cache timeout.
  478. // See https://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html
  479. func (c *Ctx) GetTimeout() time.Duration {
  480. return time.Duration(C.X_SSL_CTX_get_timeout(c.ctx)) * time.Second
  481. }
  482. // Set session cache size. Returns previously set value.
  483. // https://www.openssl.org/docs/ssl/SSL_CTX_sess_set_cache_size.html
  484. func (c *Ctx) SessSetCacheSize(t int) int {
  485. return int(C.X_SSL_CTX_sess_set_cache_size(c.ctx, C.long(t)))
  486. }
  487. // Get session cache size.
  488. // https://www.openssl.org/docs/ssl/SSL_CTX_sess_set_cache_size.html
  489. func (c *Ctx) SessGetCacheSize() int {
  490. return int(C.X_SSL_CTX_sess_get_cache_size(c.ctx))
  491. }