Integrate BACKBEAT SDK and resolve KACHING license validation
Major integrations and fixes: - Added BACKBEAT SDK integration for P2P operation timing - Implemented beat-aware status tracking for distributed operations - Added Docker secrets support for secure license management - Resolved KACHING license validation via HTTPS/TLS - Updated docker-compose configuration for clean stack deployment - Disabled rollback policies to prevent deployment failures - Added license credential storage (CHORUS-DEV-MULTI-001) Technical improvements: - BACKBEAT P2P operation tracking with phase management - Enhanced configuration system with file-based secrets - Improved error handling for license validation - Clean separation of KACHING and CHORUS deployment stacks 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
229
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/LICENSE.md
generated
vendored
Normal file
229
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,229 @@
|
||||
The contents of this repository are Copyright (c) corresponding authors and
|
||||
contributors, licensed under the `Permissive License Stack` meaning either of:
|
||||
|
||||
- Apache-2.0 Software License: https://www.apache.org/licenses/LICENSE-2.0
|
||||
([...4tr2kfsq](https://gateway.ipfs.io/ipfs/bafkreiankqxazcae4onkp436wag2lj3ccso4nawxqkkfckd6cg4tr2kfsq))
|
||||
|
||||
- MIT Software License: https://opensource.org/licenses/MIT
|
||||
([...vljevcba](https://gateway.ipfs.io/ipfs/bafkreiepofszg4gfe2gzuhojmksgemsub2h4uy2gewdnr35kswvljevcba))
|
||||
|
||||
You may not use the contents of this repository except in compliance
|
||||
with one of the listed Licenses. For an extended clarification of the
|
||||
intent behind the choice of Licensing please refer to
|
||||
https://protocol.ai/blog/announcing-the-permissive-license-stack/
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the terms listed in this notice is distributed on
|
||||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
either express or implied. See each License for the specific language
|
||||
governing permissions and limitations under that License.
|
||||
|
||||
<!--- SPDX-License-Identifier: Apache-2.0 OR MIT -->
|
||||
`SPDX-License-Identifier: Apache-2.0 OR MIT`
|
||||
|
||||
Verbatim copies of both licenses are included below:
|
||||
|
||||
<details><summary>Apache-2.0 Software License</summary>
|
||||
|
||||
```
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
```
|
||||
</details>
|
||||
|
||||
<details><summary>MIT Software License</summary>
|
||||
|
||||
```
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
```
|
||||
</details>
|
||||
46
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/crypto.go
generated
vendored
Normal file
46
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/crypto.go
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// encrypt calls the cipher's encryption. It encrypts the provided plaintext,
|
||||
// slice-appending the ciphertext on out.
|
||||
//
|
||||
// Usually you want to pass a 0-len slice to this method, with enough capacity
|
||||
// to accommodate the ciphertext in order to spare allocs.
|
||||
//
|
||||
// encrypt returns a new slice header, whose len is the length of the resulting
|
||||
// ciphertext, including the authentication tag.
|
||||
//
|
||||
// This method will not allocate if the supplied slice is large enough to
|
||||
// accommodate the encrypted data + authentication tag. If so, the returned
|
||||
// slice header should be a view of the original slice.
|
||||
//
|
||||
// With the poly1305 MAC function that noise-libp2p uses, the authentication tag
|
||||
// adds an overhead of 16 bytes.
|
||||
func (s *secureSession) encrypt(out, plaintext []byte) ([]byte, error) {
|
||||
if s.enc == nil {
|
||||
return nil, errors.New("cannot encrypt, handshake incomplete")
|
||||
}
|
||||
return s.enc.Encrypt(out, nil, plaintext)
|
||||
}
|
||||
|
||||
// decrypt calls the cipher's decryption. It decrypts the provided ciphertext,
|
||||
// slice-appending the plaintext on out.
|
||||
//
|
||||
// Usually you want to pass a 0-len slice to this method, with enough capacity
|
||||
// to accommodate the plaintext in order to spare allocs.
|
||||
//
|
||||
// decrypt returns a new slice header, whose len is the length of the resulting
|
||||
// plaintext, without the authentication tag.
|
||||
//
|
||||
// This method will not allocate if the supplied slice is large enough to
|
||||
// accommodate the plaintext. If so, the returned slice header should be a view
|
||||
// of the original slice.
|
||||
func (s *secureSession) decrypt(out, ciphertext []byte) ([]byte, error) {
|
||||
if s.dec == nil {
|
||||
return nil, errors.New("cannot decrypt, handshake incomplete")
|
||||
}
|
||||
return s.dec.Decrypt(out, nil, ciphertext)
|
||||
}
|
||||
297
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go
generated
vendored
Normal file
297
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go
generated
vendored
Normal file
@@ -0,0 +1,297 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"hash"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
"github.com/libp2p/go-libp2p/internal/sha256"
|
||||
"github.com/libp2p/go-libp2p/p2p/security/noise/pb"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
pool "github.com/libp2p/go-buffer-pool"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
//go:generate protoc --go_out=. --go_opt=Mpb/payload.proto=./pb pb/payload.proto
|
||||
|
||||
// payloadSigPrefix is prepended to our Noise static key before signing with
|
||||
// our libp2p identity key.
|
||||
const payloadSigPrefix = "noise-libp2p-static-key:"
|
||||
|
||||
type minioSHAFn struct{}
|
||||
|
||||
func (h minioSHAFn) Hash() hash.Hash { return sha256.New() }
|
||||
func (h minioSHAFn) HashName() string { return "SHA256" }
|
||||
|
||||
var shaHashFn noise.HashFunc = minioSHAFn{}
|
||||
|
||||
// All noise session share a fixed cipher suite
|
||||
var cipherSuite = noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, shaHashFn)
|
||||
|
||||
// runHandshake exchanges handshake messages with the remote peer to establish
|
||||
// a noise-libp2p session. It blocks until the handshake completes or fails.
|
||||
func (s *secureSession) runHandshake(ctx context.Context) (err error) {
|
||||
defer func() {
|
||||
if rerr := recover(); rerr != nil {
|
||||
fmt.Fprintf(os.Stderr, "caught panic: %s\n%s\n", rerr, debug.Stack())
|
||||
err = fmt.Errorf("panic in Noise handshake: %s", rerr)
|
||||
}
|
||||
}()
|
||||
|
||||
kp, err := noise.DH25519.GenerateKeypair(rand.Reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error generating static keypair: %w", err)
|
||||
}
|
||||
|
||||
cfg := noise.Config{
|
||||
CipherSuite: cipherSuite,
|
||||
Pattern: noise.HandshakeXX,
|
||||
Initiator: s.initiator,
|
||||
StaticKeypair: kp,
|
||||
Prologue: s.prologue,
|
||||
}
|
||||
|
||||
hs, err := noise.NewHandshakeState(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error initializing handshake state: %w", err)
|
||||
}
|
||||
|
||||
// set a deadline to complete the handshake, if one has been supplied.
|
||||
// clear it after we're done.
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
if err := s.SetDeadline(deadline); err == nil {
|
||||
// schedule the deadline removal once we're done handshaking.
|
||||
defer s.SetDeadline(time.Time{})
|
||||
}
|
||||
}
|
||||
|
||||
// We can re-use this buffer for all handshake messages.
|
||||
hbuf := pool.Get(2 << 10)
|
||||
defer pool.Put(hbuf)
|
||||
|
||||
if s.initiator {
|
||||
// stage 0 //
|
||||
// Handshake Msg Len = len(DH ephemeral key)
|
||||
if err := s.sendHandshakeMessage(hs, nil, hbuf); err != nil {
|
||||
return fmt.Errorf("error sending handshake message: %w", err)
|
||||
}
|
||||
|
||||
// stage 1 //
|
||||
plaintext, err := s.readHandshakeMessage(hs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading handshake message: %w", err)
|
||||
}
|
||||
rcvdEd, err := s.handleRemoteHandshakePayload(plaintext, hs.PeerStatic())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.initiatorEarlyDataHandler != nil {
|
||||
if err := s.initiatorEarlyDataHandler.Received(ctx, s.insecureConn, rcvdEd); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// stage 2 //
|
||||
// Handshake Msg Len = len(DHT static key) + MAC(static key is encrypted) + len(Payload) + MAC(payload is encrypted)
|
||||
var ed *pb.NoiseExtensions
|
||||
if s.initiatorEarlyDataHandler != nil {
|
||||
ed = s.initiatorEarlyDataHandler.Send(ctx, s.insecureConn, s.remoteID)
|
||||
}
|
||||
payload, err := s.generateHandshakePayload(kp, ed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.sendHandshakeMessage(hs, payload, hbuf); err != nil {
|
||||
return fmt.Errorf("error sending handshake message: %w", err)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
// stage 0 //
|
||||
if _, err := s.readHandshakeMessage(hs); err != nil {
|
||||
return fmt.Errorf("error reading handshake message: %w", err)
|
||||
}
|
||||
|
||||
// stage 1 //
|
||||
// Handshake Msg Len = len(DH ephemeral key) + len(DHT static key) + MAC(static key is encrypted) + len(Payload) +
|
||||
// MAC(payload is encrypted)
|
||||
var ed *pb.NoiseExtensions
|
||||
if s.responderEarlyDataHandler != nil {
|
||||
ed = s.responderEarlyDataHandler.Send(ctx, s.insecureConn, s.remoteID)
|
||||
}
|
||||
payload, err := s.generateHandshakePayload(kp, ed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.sendHandshakeMessage(hs, payload, hbuf); err != nil {
|
||||
return fmt.Errorf("error sending handshake message: %w", err)
|
||||
}
|
||||
|
||||
// stage 2 //
|
||||
plaintext, err := s.readHandshakeMessage(hs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading handshake message: %w", err)
|
||||
}
|
||||
rcvdEd, err := s.handleRemoteHandshakePayload(plaintext, hs.PeerStatic())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.responderEarlyDataHandler != nil {
|
||||
if err := s.responderEarlyDataHandler.Received(ctx, s.insecureConn, rcvdEd); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// setCipherStates sets the initial cipher states that will be used to protect
|
||||
// traffic after the handshake.
|
||||
//
|
||||
// It is called when the final handshake message is processed by
|
||||
// either sendHandshakeMessage or readHandshakeMessage.
|
||||
func (s *secureSession) setCipherStates(cs1, cs2 *noise.CipherState) {
|
||||
if s.initiator {
|
||||
s.enc = cs1
|
||||
s.dec = cs2
|
||||
} else {
|
||||
s.enc = cs2
|
||||
s.dec = cs1
|
||||
}
|
||||
}
|
||||
|
||||
// sendHandshakeMessage sends the next handshake message in the sequence.
|
||||
//
|
||||
// If payload is non-empty, it will be included in the handshake message.
|
||||
// If this is the final message in the sequence, calls setCipherStates
|
||||
// to initialize cipher states.
|
||||
func (s *secureSession) sendHandshakeMessage(hs *noise.HandshakeState, payload []byte, hbuf []byte) error {
|
||||
// the first two bytes will be the length of the noise handshake message.
|
||||
bz, cs1, cs2, err := hs.WriteMessage(hbuf[:LengthPrefixLength], payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// bz will also include the length prefix as we passed a slice of LengthPrefixLength length
|
||||
// to hs.Write().
|
||||
binary.BigEndian.PutUint16(bz, uint16(len(bz)-LengthPrefixLength))
|
||||
|
||||
_, err = s.writeMsgInsecure(bz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cs1 != nil && cs2 != nil {
|
||||
s.setCipherStates(cs1, cs2)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readHandshakeMessage reads a message from the insecure conn and tries to
|
||||
// process it as the expected next message in the handshake sequence.
|
||||
//
|
||||
// If the message contains a payload, it will be decrypted and returned.
|
||||
//
|
||||
// If this is the final message in the sequence, it calls setCipherStates
|
||||
// to initialize cipher states.
|
||||
func (s *secureSession) readHandshakeMessage(hs *noise.HandshakeState) ([]byte, error) {
|
||||
l, err := s.readNextInsecureMsgLen()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := pool.Get(l)
|
||||
defer pool.Put(buf)
|
||||
|
||||
if err := s.readNextMsgInsecure(buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg, cs1, cs2, err := hs.ReadMessage(nil, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cs1 != nil && cs2 != nil {
|
||||
s.setCipherStates(cs1, cs2)
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// generateHandshakePayload creates a libp2p handshake payload with a
|
||||
// signature of our static noise key.
|
||||
func (s *secureSession) generateHandshakePayload(localStatic noise.DHKey, ext *pb.NoiseExtensions) ([]byte, error) {
|
||||
// obtain the public key from the handshake session, so we can sign it with
|
||||
// our libp2p secret key.
|
||||
localKeyRaw, err := crypto.MarshalPublicKey(s.LocalPublicKey())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error serializing libp2p identity key: %w", err)
|
||||
}
|
||||
|
||||
// prepare payload to sign; perform signature.
|
||||
toSign := append([]byte(payloadSigPrefix), localStatic.Public...)
|
||||
signedPayload, err := s.localKey.Sign(toSign)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error sigining handshake payload: %w", err)
|
||||
}
|
||||
|
||||
// create payload
|
||||
payloadEnc, err := proto.Marshal(&pb.NoiseHandshakePayload{
|
||||
IdentityKey: localKeyRaw,
|
||||
IdentitySig: signedPayload,
|
||||
Extensions: ext,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error marshaling handshake payload: %w", err)
|
||||
}
|
||||
return payloadEnc, nil
|
||||
}
|
||||
|
||||
// handleRemoteHandshakePayload unmarshals the handshake payload object sent
|
||||
// by the remote peer and validates the signature against the peer's static Noise key.
|
||||
// It returns the data attached to the payload.
|
||||
func (s *secureSession) handleRemoteHandshakePayload(payload []byte, remoteStatic []byte) (*pb.NoiseExtensions, error) {
|
||||
// unmarshal payload
|
||||
nhp := new(pb.NoiseHandshakePayload)
|
||||
err := proto.Unmarshal(payload, nhp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error unmarshaling remote handshake payload: %w", err)
|
||||
}
|
||||
|
||||
// unpack remote peer's public libp2p key
|
||||
remotePubKey, err := crypto.UnmarshalPublicKey(nhp.GetIdentityKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := peer.IDFromPublicKey(remotePubKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check the peer ID if enabled
|
||||
if s.checkPeerID && s.remoteID != id {
|
||||
return nil, sec.ErrPeerIDMismatch{Expected: s.remoteID, Actual: id}
|
||||
}
|
||||
|
||||
// verify payload is signed by asserted remote libp2p key.
|
||||
sig := nhp.GetIdentitySig()
|
||||
msg := append([]byte(payloadSigPrefix), remoteStatic...)
|
||||
ok, err := remotePubKey.Verify(msg, sig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error verifying signature: %w", err)
|
||||
} else if !ok {
|
||||
return nil, fmt.Errorf("handshake signature invalid")
|
||||
}
|
||||
|
||||
// set remote peer key and id
|
||||
s.remoteID = id
|
||||
s.remoteKey = remotePubKey
|
||||
return nhp.Extensions, nil
|
||||
}
|
||||
239
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/pb/payload.pb.go
generated
vendored
Normal file
239
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/pb/payload.pb.go
generated
vendored
Normal file
@@ -0,0 +1,239 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.30.0
|
||||
// protoc v3.21.12
|
||||
// source: pb/payload.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type NoiseExtensions struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
WebtransportCerthashes [][]byte `protobuf:"bytes,1,rep,name=webtransport_certhashes,json=webtransportCerthashes" json:"webtransport_certhashes,omitempty"`
|
||||
StreamMuxers []string `protobuf:"bytes,2,rep,name=stream_muxers,json=streamMuxers" json:"stream_muxers,omitempty"`
|
||||
}
|
||||
|
||||
func (x *NoiseExtensions) Reset() {
|
||||
*x = NoiseExtensions{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_pb_payload_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *NoiseExtensions) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*NoiseExtensions) ProtoMessage() {}
|
||||
|
||||
func (x *NoiseExtensions) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_pb_payload_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use NoiseExtensions.ProtoReflect.Descriptor instead.
|
||||
func (*NoiseExtensions) Descriptor() ([]byte, []int) {
|
||||
return file_pb_payload_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *NoiseExtensions) GetWebtransportCerthashes() [][]byte {
|
||||
if x != nil {
|
||||
return x.WebtransportCerthashes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *NoiseExtensions) GetStreamMuxers() []string {
|
||||
if x != nil {
|
||||
return x.StreamMuxers
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type NoiseHandshakePayload struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
IdentityKey []byte `protobuf:"bytes,1,opt,name=identity_key,json=identityKey" json:"identity_key,omitempty"`
|
||||
IdentitySig []byte `protobuf:"bytes,2,opt,name=identity_sig,json=identitySig" json:"identity_sig,omitempty"`
|
||||
Extensions *NoiseExtensions `protobuf:"bytes,4,opt,name=extensions" json:"extensions,omitempty"`
|
||||
}
|
||||
|
||||
func (x *NoiseHandshakePayload) Reset() {
|
||||
*x = NoiseHandshakePayload{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_pb_payload_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *NoiseHandshakePayload) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*NoiseHandshakePayload) ProtoMessage() {}
|
||||
|
||||
func (x *NoiseHandshakePayload) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_pb_payload_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use NoiseHandshakePayload.ProtoReflect.Descriptor instead.
|
||||
func (*NoiseHandshakePayload) Descriptor() ([]byte, []int) {
|
||||
return file_pb_payload_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *NoiseHandshakePayload) GetIdentityKey() []byte {
|
||||
if x != nil {
|
||||
return x.IdentityKey
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *NoiseHandshakePayload) GetIdentitySig() []byte {
|
||||
if x != nil {
|
||||
return x.IdentitySig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *NoiseHandshakePayload) GetExtensions() *NoiseExtensions {
|
||||
if x != nil {
|
||||
return x.Extensions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_pb_payload_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_pb_payload_proto_rawDesc = []byte{
|
||||
0x0a, 0x10, 0x70, 0x62, 0x2f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x70, 0x72, 0x6f,
|
||||
0x74, 0x6f, 0x12, 0x02, 0x70, 0x62, 0x22, 0x6f, 0x0a, 0x0f, 0x4e, 0x6f, 0x69, 0x73, 0x65, 0x45,
|
||||
0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x37, 0x0a, 0x17, 0x77, 0x65, 0x62,
|
||||
0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x68, 0x61,
|
||||
0x73, 0x68, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x16, 0x77, 0x65, 0x62, 0x74,
|
||||
0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x43, 0x65, 0x72, 0x74, 0x68, 0x61, 0x73, 0x68,
|
||||
0x65, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x6d, 0x75, 0x78,
|
||||
0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x73, 0x74, 0x72, 0x65, 0x61,
|
||||
0x6d, 0x4d, 0x75, 0x78, 0x65, 0x72, 0x73, 0x22, 0x92, 0x01, 0x0a, 0x15, 0x4e, 0x6f, 0x69, 0x73,
|
||||
0x65, 0x48, 0x61, 0x6e, 0x64, 0x73, 0x68, 0x61, 0x6b, 0x65, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61,
|
||||
0x64, 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x6b, 0x65,
|
||||
0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74,
|
||||
0x79, 0x4b, 0x65, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79,
|
||||
0x5f, 0x73, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x69, 0x64, 0x65, 0x6e,
|
||||
0x74, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x12, 0x33, 0x0a, 0x0a, 0x65, 0x78, 0x74, 0x65, 0x6e,
|
||||
0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x70, 0x62,
|
||||
0x2e, 0x4e, 0x6f, 0x69, 0x73, 0x65, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73,
|
||||
0x52, 0x0a, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73,
|
||||
}
|
||||
|
||||
var (
|
||||
file_pb_payload_proto_rawDescOnce sync.Once
|
||||
file_pb_payload_proto_rawDescData = file_pb_payload_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_pb_payload_proto_rawDescGZIP() []byte {
|
||||
file_pb_payload_proto_rawDescOnce.Do(func() {
|
||||
file_pb_payload_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_payload_proto_rawDescData)
|
||||
})
|
||||
return file_pb_payload_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_pb_payload_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_pb_payload_proto_goTypes = []interface{}{
|
||||
(*NoiseExtensions)(nil), // 0: pb.NoiseExtensions
|
||||
(*NoiseHandshakePayload)(nil), // 1: pb.NoiseHandshakePayload
|
||||
}
|
||||
var file_pb_payload_proto_depIdxs = []int32{
|
||||
0, // 0: pb.NoiseHandshakePayload.extensions:type_name -> pb.NoiseExtensions
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_pb_payload_proto_init() }
|
||||
func file_pb_payload_proto_init() {
|
||||
if File_pb_payload_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_pb_payload_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*NoiseExtensions); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_pb_payload_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*NoiseHandshakePayload); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_pb_payload_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_pb_payload_proto_goTypes,
|
||||
DependencyIndexes: file_pb_payload_proto_depIdxs,
|
||||
MessageInfos: file_pb_payload_proto_msgTypes,
|
||||
}.Build()
|
||||
File_pb_payload_proto = out.File
|
||||
file_pb_payload_proto_rawDesc = nil
|
||||
file_pb_payload_proto_goTypes = nil
|
||||
file_pb_payload_proto_depIdxs = nil
|
||||
}
|
||||
13
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/pb/payload.proto
generated
vendored
Normal file
13
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/pb/payload.proto
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
syntax = "proto2";
|
||||
package pb;
|
||||
|
||||
message NoiseExtensions {
|
||||
repeated bytes webtransport_certhashes = 1;
|
||||
repeated string stream_muxers = 2;
|
||||
}
|
||||
|
||||
message NoiseHandshakePayload {
|
||||
optional bytes identity_key = 1;
|
||||
optional bytes identity_sig = 2;
|
||||
optional NoiseExtensions extensions = 4;
|
||||
}
|
||||
155
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/rw.go
generated
vendored
Normal file
155
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/rw.go
generated
vendored
Normal file
@@ -0,0 +1,155 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
pool "github.com/libp2p/go-buffer-pool"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
// MaxTransportMsgLength is the Noise-imposed maximum transport message length,
|
||||
// inclusive of the MAC size (16 bytes, Poly1305 for noise-libp2p).
|
||||
const MaxTransportMsgLength = 0xffff
|
||||
|
||||
// MaxPlaintextLength is the maximum payload size. It is MaxTransportMsgLength
|
||||
// minus the MAC size. Payloads over this size will be automatically chunked.
|
||||
const MaxPlaintextLength = MaxTransportMsgLength - chacha20poly1305.Overhead
|
||||
|
||||
// LengthPrefixLength is the length of the length prefix itself, which precedes
|
||||
// all transport messages in order to delimit them. In bytes.
|
||||
const LengthPrefixLength = 2
|
||||
|
||||
// Read reads from the secure connection, returning plaintext data in `buf`.
|
||||
//
|
||||
// Honours io.Reader in terms of behaviour.
|
||||
func (s *secureSession) Read(buf []byte) (int, error) {
|
||||
s.readLock.Lock()
|
||||
defer s.readLock.Unlock()
|
||||
|
||||
// 1. If we have queued received bytes:
|
||||
// 1a. If len(buf) < len(queued), saturate buf, update seek pointer, return.
|
||||
// 1b. If len(buf) >= len(queued), copy remaining to buf, release queued buffer back into pool, return.
|
||||
//
|
||||
// 2. Else, read the next message off the wire; next_len is length prefix.
|
||||
// 2a. If len(buf) >= next_len, copy the message to input buffer (zero-alloc path), and return.
|
||||
// 2b. If len(buf) >= (next_len - length of Authentication Tag), get buffer from pool, read encrypted message into it.
|
||||
// decrypt message directly into the input buffer and return the buffer obtained from the pool.
|
||||
// 2c. If len(buf) < next_len, obtain buffer from pool, copy entire message into it, saturate buf, update seek pointer.
|
||||
if s.qbuf != nil {
|
||||
// we have queued bytes; copy as much as we can.
|
||||
copied := copy(buf, s.qbuf[s.qseek:])
|
||||
s.qseek += copied
|
||||
if s.qseek == len(s.qbuf) {
|
||||
// queued buffer is now empty, reset and release.
|
||||
pool.Put(s.qbuf)
|
||||
s.qseek, s.qbuf = 0, nil
|
||||
}
|
||||
return copied, nil
|
||||
}
|
||||
|
||||
// length of the next encrypted message.
|
||||
nextMsgLen, err := s.readNextInsecureMsgLen()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// If the buffer is atleast as big as the encrypted message size,
|
||||
// we can read AND decrypt in place.
|
||||
if len(buf) >= nextMsgLen {
|
||||
if err := s.readNextMsgInsecure(buf[:nextMsgLen]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
dbuf, err := s.decrypt(buf[:0], buf[:nextMsgLen])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return len(dbuf), nil
|
||||
}
|
||||
|
||||
// otherwise, we get a buffer from the pool so we can read the message into it
|
||||
// and then decrypt in place, since we're retaining the buffer (or a view thereof).
|
||||
cbuf := pool.Get(nextMsgLen)
|
||||
if err := s.readNextMsgInsecure(cbuf); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if s.qbuf, err = s.decrypt(cbuf[:0], cbuf); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// copy as many bytes as we can; update seek pointer.
|
||||
s.qseek = copy(buf, s.qbuf)
|
||||
|
||||
return s.qseek, nil
|
||||
}
|
||||
|
||||
// Write encrypts the plaintext `in` data and sends it on the
|
||||
// secure connection.
|
||||
func (s *secureSession) Write(data []byte) (int, error) {
|
||||
s.writeLock.Lock()
|
||||
defer s.writeLock.Unlock()
|
||||
|
||||
var (
|
||||
written int
|
||||
cbuf []byte
|
||||
total = len(data)
|
||||
)
|
||||
|
||||
if total < MaxPlaintextLength {
|
||||
cbuf = pool.Get(total + chacha20poly1305.Overhead + LengthPrefixLength)
|
||||
} else {
|
||||
cbuf = pool.Get(MaxTransportMsgLength + LengthPrefixLength)
|
||||
}
|
||||
|
||||
defer pool.Put(cbuf)
|
||||
|
||||
for written < total {
|
||||
end := written + MaxPlaintextLength
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
|
||||
b, err := s.encrypt(cbuf[:LengthPrefixLength], data[written:end])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
binary.BigEndian.PutUint16(b, uint16(len(b)-LengthPrefixLength))
|
||||
|
||||
_, err = s.writeMsgInsecure(b)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
written = end
|
||||
}
|
||||
return written, nil
|
||||
}
|
||||
|
||||
// readNextInsecureMsgLen reads the length of the next message on the insecureConn channel.
|
||||
func (s *secureSession) readNextInsecureMsgLen() (int, error) {
|
||||
_, err := io.ReadFull(s.insecureReader, s.rlen[:])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return int(binary.BigEndian.Uint16(s.rlen[:])), err
|
||||
}
|
||||
|
||||
// readNextMsgInsecure tries to read exactly len(buf) bytes into buf from
|
||||
// the insecureConn channel and returns the error, if any.
|
||||
// Ideally, for reading a message, you'd first want to call `readNextInsecureMsgLen`
|
||||
// to determine the size of the next message to be read from the insecureConn channel and then call
|
||||
// this function with a buffer of exactly that size.
|
||||
func (s *secureSession) readNextMsgInsecure(buf []byte) error {
|
||||
_, err := io.ReadFull(s.insecureReader, buf)
|
||||
return err
|
||||
}
|
||||
|
||||
// writeMsgInsecure writes to the insecureConn conn.
|
||||
// data will be prefixed with its length in bytes, written as a 16-bit uint in network order.
|
||||
func (s *secureSession) writeMsgInsecure(data []byte) (int, error) {
|
||||
return s.insecureConn.Write(data)
|
||||
}
|
||||
140
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/session.go
generated
vendored
Normal file
140
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/session.go
generated
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/protocol"
|
||||
)
|
||||
|
||||
type secureSession struct {
|
||||
initiator bool
|
||||
checkPeerID bool
|
||||
|
||||
localID peer.ID
|
||||
localKey crypto.PrivKey
|
||||
remoteID peer.ID
|
||||
remoteKey crypto.PubKey
|
||||
|
||||
readLock sync.Mutex
|
||||
writeLock sync.Mutex
|
||||
|
||||
insecureConn net.Conn
|
||||
insecureReader *bufio.Reader // to cushion io read syscalls
|
||||
// we don't buffer writes to avoid introducing latency; optimisation possible. // TODO revisit
|
||||
|
||||
qseek int // queued bytes seek value.
|
||||
qbuf []byte // queued bytes buffer.
|
||||
rlen [2]byte // work buffer to read in the incoming message length.
|
||||
|
||||
enc *noise.CipherState
|
||||
dec *noise.CipherState
|
||||
|
||||
// noise prologue
|
||||
prologue []byte
|
||||
|
||||
initiatorEarlyDataHandler, responderEarlyDataHandler EarlyDataHandler
|
||||
|
||||
// ConnectionState holds state information releated to the secureSession entity.
|
||||
connectionState network.ConnectionState
|
||||
}
|
||||
|
||||
// newSecureSession creates a Noise session over the given insecureConn Conn, using
|
||||
// the libp2p identity keypair from the given Transport.
|
||||
func newSecureSession(tpt *Transport, ctx context.Context, insecure net.Conn, remote peer.ID, prologue []byte, initiatorEDH, responderEDH EarlyDataHandler, initiator, checkPeerID bool) (*secureSession, error) {
|
||||
s := &secureSession{
|
||||
insecureConn: insecure,
|
||||
insecureReader: bufio.NewReader(insecure),
|
||||
initiator: initiator,
|
||||
localID: tpt.localID,
|
||||
localKey: tpt.privateKey,
|
||||
remoteID: remote,
|
||||
prologue: prologue,
|
||||
initiatorEarlyDataHandler: initiatorEDH,
|
||||
responderEarlyDataHandler: responderEDH,
|
||||
checkPeerID: checkPeerID,
|
||||
}
|
||||
|
||||
// the go-routine we create to run the handshake will
|
||||
// write the result of the handshake to the respCh.
|
||||
respCh := make(chan error, 1)
|
||||
go func() {
|
||||
respCh <- s.runHandshake(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-respCh:
|
||||
if err != nil {
|
||||
_ = s.insecureConn.Close()
|
||||
}
|
||||
return s, err
|
||||
|
||||
case <-ctx.Done():
|
||||
// If the context has been cancelled, we close the underlying connection.
|
||||
// We then wait for the handshake to return because of the first error it encounters
|
||||
// so we don't return without cleaning up the go-routine.
|
||||
_ = s.insecureConn.Close()
|
||||
<-respCh
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *secureSession) LocalAddr() net.Addr {
|
||||
return s.insecureConn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *secureSession) LocalPeer() peer.ID {
|
||||
return s.localID
|
||||
}
|
||||
|
||||
func (s *secureSession) LocalPublicKey() crypto.PubKey {
|
||||
return s.localKey.GetPublic()
|
||||
}
|
||||
|
||||
func (s *secureSession) RemoteAddr() net.Addr {
|
||||
return s.insecureConn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (s *secureSession) RemotePeer() peer.ID {
|
||||
return s.remoteID
|
||||
}
|
||||
|
||||
func (s *secureSession) RemotePublicKey() crypto.PubKey {
|
||||
return s.remoteKey
|
||||
}
|
||||
|
||||
func (s *secureSession) ConnState() network.ConnectionState {
|
||||
return s.connectionState
|
||||
}
|
||||
|
||||
func (s *secureSession) SetDeadline(t time.Time) error {
|
||||
return s.insecureConn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (s *secureSession) SetReadDeadline(t time.Time) error {
|
||||
return s.insecureConn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (s *secureSession) SetWriteDeadline(t time.Time) error {
|
||||
return s.insecureConn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (s *secureSession) Close() error {
|
||||
return s.insecureConn.Close()
|
||||
}
|
||||
|
||||
func SessionWithConnState(s *secureSession, muxer protocol.ID) *secureSession {
|
||||
if s != nil {
|
||||
s.connectionState.StreamMultiplexer = muxer
|
||||
s.connectionState.UsedEarlyMuxerNegotiation = muxer != ""
|
||||
}
|
||||
return s
|
||||
}
|
||||
101
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/session_transport.go
generated
vendored
Normal file
101
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/session_transport.go
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/canonicallog"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/protocol"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
"github.com/libp2p/go-libp2p/p2p/security/noise/pb"
|
||||
|
||||
manet "github.com/multiformats/go-multiaddr/net"
|
||||
)
|
||||
|
||||
type SessionOption = func(*SessionTransport) error
|
||||
|
||||
// Prologue sets a prologue for the Noise session.
|
||||
// The handshake will only complete successfully if both parties set the same prologue.
|
||||
// See https://noiseprotocol.org/noise.html#prologue for details.
|
||||
func Prologue(prologue []byte) SessionOption {
|
||||
return func(s *SessionTransport) error {
|
||||
s.prologue = prologue
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// EarlyDataHandler defines what the application payload is for either the second
|
||||
// (if responder) or third (if initiator) handshake message, and defines the
|
||||
// logic for handling the other side's early data. Note the early data in the
|
||||
// second handshake message is encrypted, but the peer is not authenticated at that point.
|
||||
type EarlyDataHandler interface {
|
||||
// Send for the initiator is called for the client before sending the third
|
||||
// handshake message. Defines the application payload for the third message.
|
||||
// Send for the responder is called before sending the second handshake message.
|
||||
Send(context.Context, net.Conn, peer.ID) *pb.NoiseExtensions
|
||||
// Received for the initiator is called when the second handshake message
|
||||
// from the responder is received.
|
||||
// Received for the responder is called when the third handshake message
|
||||
// from the initiator is received.
|
||||
Received(context.Context, net.Conn, *pb.NoiseExtensions) error
|
||||
}
|
||||
|
||||
// EarlyData sets the `EarlyDataHandler` for the initiator and responder roles.
|
||||
// See `EarlyDataHandler` for more details.
|
||||
func EarlyData(initiator, responder EarlyDataHandler) SessionOption {
|
||||
return func(s *SessionTransport) error {
|
||||
s.initiatorEarlyDataHandler = initiator
|
||||
s.responderEarlyDataHandler = responder
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// DisablePeerIDCheck disables checking the remote peer ID for a noise connection.
|
||||
// For outbound connections, this is the equivalent of calling `SecureInbound` with an empty
|
||||
// peer ID. This is susceptible to MITM attacks since we do not verify the identity of the remote
|
||||
// peer.
|
||||
func DisablePeerIDCheck() SessionOption {
|
||||
return func(s *SessionTransport) error {
|
||||
s.disablePeerIDCheck = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var _ sec.SecureTransport = &SessionTransport{}
|
||||
|
||||
// SessionTransport can be used
|
||||
// to provide per-connection options
|
||||
type SessionTransport struct {
|
||||
t *Transport
|
||||
// options
|
||||
prologue []byte
|
||||
disablePeerIDCheck bool
|
||||
|
||||
protocolID protocol.ID
|
||||
|
||||
initiatorEarlyDataHandler, responderEarlyDataHandler EarlyDataHandler
|
||||
}
|
||||
|
||||
// SecureInbound runs the Noise handshake as the responder.
|
||||
// If p is empty, connections from any peer are accepted.
|
||||
func (i *SessionTransport) SecureInbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
checkPeerID := !i.disablePeerIDCheck && p != ""
|
||||
c, err := newSecureSession(i.t, ctx, insecure, p, i.prologue, i.initiatorEarlyDataHandler, i.responderEarlyDataHandler, false, checkPeerID)
|
||||
if err != nil {
|
||||
addr, maErr := manet.FromNetAddr(insecure.RemoteAddr())
|
||||
if maErr == nil {
|
||||
canonicallog.LogPeerStatus(100, p, addr, "handshake_failure", "noise", "err", err.Error())
|
||||
}
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
// SecureOutbound runs the Noise handshake as the initiator.
|
||||
func (i *SessionTransport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
return newSecureSession(i.t, ctx, insecure, p, i.prologue, i.initiatorEarlyDataHandler, i.responderEarlyDataHandler, true, !i.disablePeerIDCheck)
|
||||
}
|
||||
|
||||
func (i *SessionTransport) ID() protocol.ID {
|
||||
return i.protocolID
|
||||
}
|
||||
131
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/transport.go
generated
vendored
Normal file
131
vendor/github.com/libp2p/go-libp2p/p2p/security/noise/transport.go
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
package noise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/canonicallog"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/protocol"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
tptu "github.com/libp2p/go-libp2p/p2p/net/upgrader"
|
||||
"github.com/libp2p/go-libp2p/p2p/security/noise/pb"
|
||||
|
||||
manet "github.com/multiformats/go-multiaddr/net"
|
||||
)
|
||||
|
||||
// ID is the protocol ID for noise
|
||||
const ID = "/noise"
|
||||
const maxProtoNum = 100
|
||||
|
||||
type Transport struct {
|
||||
protocolID protocol.ID
|
||||
localID peer.ID
|
||||
privateKey crypto.PrivKey
|
||||
muxers []protocol.ID
|
||||
}
|
||||
|
||||
var _ sec.SecureTransport = &Transport{}
|
||||
|
||||
// New creates a new Noise transport using the given private key as its
|
||||
// libp2p identity key.
|
||||
func New(id protocol.ID, privkey crypto.PrivKey, muxers []tptu.StreamMuxer) (*Transport, error) {
|
||||
localID, err := peer.IDFromPrivateKey(privkey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
muxerIDs := make([]protocol.ID, 0, len(muxers))
|
||||
for _, m := range muxers {
|
||||
muxerIDs = append(muxerIDs, m.ID)
|
||||
}
|
||||
|
||||
return &Transport{
|
||||
protocolID: id,
|
||||
localID: localID,
|
||||
privateKey: privkey,
|
||||
muxers: muxerIDs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SecureInbound runs the Noise handshake as the responder.
|
||||
// If p is empty, connections from any peer are accepted.
|
||||
func (t *Transport) SecureInbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
responderEDH := newTransportEDH(t)
|
||||
c, err := newSecureSession(t, ctx, insecure, p, nil, nil, responderEDH, false, p != "")
|
||||
if err != nil {
|
||||
addr, maErr := manet.FromNetAddr(insecure.RemoteAddr())
|
||||
if maErr == nil {
|
||||
canonicallog.LogPeerStatus(100, p, addr, "handshake_failure", "noise", "err", err.Error())
|
||||
}
|
||||
}
|
||||
return SessionWithConnState(c, responderEDH.MatchMuxers(false)), err
|
||||
}
|
||||
|
||||
// SecureOutbound runs the Noise handshake as the initiator.
|
||||
func (t *Transport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
initiatorEDH := newTransportEDH(t)
|
||||
c, err := newSecureSession(t, ctx, insecure, p, nil, initiatorEDH, nil, true, true)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return SessionWithConnState(c, initiatorEDH.MatchMuxers(true)), err
|
||||
}
|
||||
|
||||
func (t *Transport) WithSessionOptions(opts ...SessionOption) (*SessionTransport, error) {
|
||||
st := &SessionTransport{t: t, protocolID: t.protocolID}
|
||||
for _, opt := range opts {
|
||||
if err := opt(st); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (t *Transport) ID() protocol.ID {
|
||||
return t.protocolID
|
||||
}
|
||||
|
||||
func matchMuxers(initiatorMuxers, responderMuxers []protocol.ID) protocol.ID {
|
||||
for _, initMuxer := range initiatorMuxers {
|
||||
for _, respMuxer := range responderMuxers {
|
||||
if initMuxer == respMuxer {
|
||||
return initMuxer
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type transportEarlyDataHandler struct {
|
||||
transport *Transport
|
||||
receivedMuxers []protocol.ID
|
||||
}
|
||||
|
||||
var _ EarlyDataHandler = &transportEarlyDataHandler{}
|
||||
|
||||
func newTransportEDH(t *Transport) *transportEarlyDataHandler {
|
||||
return &transportEarlyDataHandler{transport: t}
|
||||
}
|
||||
|
||||
func (i *transportEarlyDataHandler) Send(context.Context, net.Conn, peer.ID) *pb.NoiseExtensions {
|
||||
return &pb.NoiseExtensions{
|
||||
StreamMuxers: protocol.ConvertToStrings(i.transport.muxers),
|
||||
}
|
||||
}
|
||||
|
||||
func (i *transportEarlyDataHandler) Received(_ context.Context, _ net.Conn, extension *pb.NoiseExtensions) error {
|
||||
// Discard messages with size or the number of protocols exceeding extension limit for security.
|
||||
if extension != nil && len(extension.StreamMuxers) <= maxProtoNum {
|
||||
i.receivedMuxers = protocol.ConvertFromStrings(extension.GetStreamMuxers())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *transportEarlyDataHandler) MatchMuxers(isInitiator bool) protocol.ID {
|
||||
if isInitiator {
|
||||
return matchMuxers(i.transport.muxers, i.receivedMuxers)
|
||||
}
|
||||
return matchMuxers(i.receivedMuxers, i.transport.muxers)
|
||||
}
|
||||
7
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/LICENSE.md
generated
vendored
Normal file
7
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright 2018 Marten Seemann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
37
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/conn.go
generated
vendored
Normal file
37
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/conn.go
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
package libp2ptls
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
|
||||
ci "github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
)
|
||||
|
||||
type conn struct {
|
||||
*tls.Conn
|
||||
|
||||
localPeer peer.ID
|
||||
remotePeer peer.ID
|
||||
remotePubKey ci.PubKey
|
||||
connectionState network.ConnectionState
|
||||
}
|
||||
|
||||
var _ sec.SecureConn = &conn{}
|
||||
|
||||
func (c *conn) LocalPeer() peer.ID {
|
||||
return c.localPeer
|
||||
}
|
||||
|
||||
func (c *conn) RemotePeer() peer.ID {
|
||||
return c.remotePeer
|
||||
}
|
||||
|
||||
func (c *conn) RemotePublicKey() ci.PubKey {
|
||||
return c.remotePubKey
|
||||
}
|
||||
|
||||
func (c *conn) ConnState() network.ConnectionState {
|
||||
return c.connectionState
|
||||
}
|
||||
271
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go
generated
vendored
Normal file
271
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go
generated
vendored
Normal file
@@ -0,0 +1,271 @@
|
||||
package libp2ptls
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/asn1"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
ic "github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
)
|
||||
|
||||
const certValidityPeriod = 100 * 365 * 24 * time.Hour // ~100 years
|
||||
const certificatePrefix = "libp2p-tls-handshake:"
|
||||
const alpn string = "libp2p"
|
||||
|
||||
var extensionID = getPrefixedExtensionID([]int{1, 1})
|
||||
var extensionCritical bool // so we can mark the extension critical in tests
|
||||
|
||||
type signedKey struct {
|
||||
PubKey []byte
|
||||
Signature []byte
|
||||
}
|
||||
|
||||
// Identity is used to secure connections
|
||||
type Identity struct {
|
||||
config tls.Config
|
||||
}
|
||||
|
||||
// IdentityConfig is used to configure an Identity
|
||||
type IdentityConfig struct {
|
||||
CertTemplate *x509.Certificate
|
||||
}
|
||||
|
||||
// IdentityOption transforms an IdentityConfig to apply optional settings.
|
||||
type IdentityOption func(r *IdentityConfig)
|
||||
|
||||
// WithCertTemplate specifies the template to use when generating a new certificate.
|
||||
func WithCertTemplate(template *x509.Certificate) IdentityOption {
|
||||
return func(c *IdentityConfig) {
|
||||
c.CertTemplate = template
|
||||
}
|
||||
}
|
||||
|
||||
// NewIdentity creates a new identity
|
||||
func NewIdentity(privKey ic.PrivKey, opts ...IdentityOption) (*Identity, error) {
|
||||
config := IdentityConfig{}
|
||||
for _, opt := range opts {
|
||||
opt(&config)
|
||||
}
|
||||
|
||||
var err error
|
||||
if config.CertTemplate == nil {
|
||||
config.CertTemplate, err = certTemplate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
cert, err := keyToCertificate(privKey, config.CertTemplate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Identity{
|
||||
config: tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
InsecureSkipVerify: true, // This is not insecure here. We will verify the cert chain ourselves.
|
||||
ClientAuth: tls.RequireAnyClientCert,
|
||||
Certificates: []tls.Certificate{*cert},
|
||||
VerifyPeerCertificate: func(_ [][]byte, _ [][]*x509.Certificate) error {
|
||||
panic("tls config not specialized for peer")
|
||||
},
|
||||
NextProtos: []string{alpn},
|
||||
SessionTicketsDisabled: true,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ConfigForPeer creates a new single-use tls.Config that verifies the peer's
|
||||
// certificate chain and returns the peer's public key via the channel. If the
|
||||
// peer ID is empty, the returned config will accept any peer.
|
||||
//
|
||||
// It should be used to create a new tls.Config before securing either an
|
||||
// incoming or outgoing connection.
|
||||
func (i *Identity) ConfigForPeer(remote peer.ID) (*tls.Config, <-chan ic.PubKey) {
|
||||
keyCh := make(chan ic.PubKey, 1)
|
||||
// We need to check the peer ID in the VerifyPeerCertificate callback.
|
||||
// The tls.Config it is also used for listening, and we might also have concurrent dials.
|
||||
// Clone it so we can check for the specific peer ID we're dialing here.
|
||||
conf := i.config.Clone()
|
||||
// We're using InsecureSkipVerify, so the verifiedChains parameter will always be empty.
|
||||
// We need to parse the certificates ourselves from the raw certs.
|
||||
conf.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) (err error) {
|
||||
defer func() {
|
||||
if rerr := recover(); rerr != nil {
|
||||
fmt.Fprintf(os.Stderr, "panic when processing peer certificate in TLS handshake: %s\n%s\n", rerr, debug.Stack())
|
||||
err = fmt.Errorf("panic when processing peer certificate in TLS handshake: %s", rerr)
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
defer close(keyCh)
|
||||
|
||||
chain := make([]*x509.Certificate, len(rawCerts))
|
||||
for i := 0; i < len(rawCerts); i++ {
|
||||
cert, err := x509.ParseCertificate(rawCerts[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
chain[i] = cert
|
||||
}
|
||||
|
||||
pubKey, err := PubKeyFromCertChain(chain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if remote != "" && !remote.MatchesPublicKey(pubKey) {
|
||||
peerID, err := peer.IDFromPublicKey(pubKey)
|
||||
if err != nil {
|
||||
peerID = peer.ID(fmt.Sprintf("(not determined: %s)", err.Error()))
|
||||
}
|
||||
return sec.ErrPeerIDMismatch{Expected: remote, Actual: peerID}
|
||||
}
|
||||
keyCh <- pubKey
|
||||
return nil
|
||||
}
|
||||
return conf, keyCh
|
||||
}
|
||||
|
||||
// PubKeyFromCertChain verifies the certificate chain and extract the remote's public key.
|
||||
func PubKeyFromCertChain(chain []*x509.Certificate) (ic.PubKey, error) {
|
||||
if len(chain) != 1 {
|
||||
return nil, errors.New("expected one certificates in the chain")
|
||||
}
|
||||
cert := chain[0]
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(cert)
|
||||
var found bool
|
||||
var keyExt pkix.Extension
|
||||
// find the libp2p key extension, skipping all unknown extensions
|
||||
for _, ext := range cert.Extensions {
|
||||
if extensionIDEqual(ext.Id, extensionID) {
|
||||
keyExt = ext
|
||||
found = true
|
||||
for i, oident := range cert.UnhandledCriticalExtensions {
|
||||
if oident.Equal(ext.Id) {
|
||||
// delete the extension from UnhandledCriticalExtensions
|
||||
cert.UnhandledCriticalExtensions = append(cert.UnhandledCriticalExtensions[:i], cert.UnhandledCriticalExtensions[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, errors.New("expected certificate to contain the key extension")
|
||||
}
|
||||
if _, err := cert.Verify(x509.VerifyOptions{Roots: pool}); err != nil {
|
||||
// If we return an x509 error here, it will be sent on the wire.
|
||||
// Wrap the error to avoid that.
|
||||
return nil, fmt.Errorf("certificate verification failed: %s", err)
|
||||
}
|
||||
|
||||
var sk signedKey
|
||||
if _, err := asn1.Unmarshal(keyExt.Value, &sk); err != nil {
|
||||
return nil, fmt.Errorf("unmarshalling signed certificate failed: %s", err)
|
||||
}
|
||||
pubKey, err := ic.UnmarshalPublicKey(sk.PubKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unmarshalling public key failed: %s", err)
|
||||
}
|
||||
certKeyPub, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valid, err := pubKey.Verify(append([]byte(certificatePrefix), certKeyPub...), sk.Signature)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("signature verification failed: %s", err)
|
||||
}
|
||||
if !valid {
|
||||
return nil, errors.New("signature invalid")
|
||||
}
|
||||
return pubKey, nil
|
||||
}
|
||||
|
||||
// GenerateSignedExtension uses the provided private key to sign the public key, and returns the
|
||||
// signature within a pkix.Extension.
|
||||
// This extension is included in a certificate to cryptographically tie it to the libp2p private key.
|
||||
func GenerateSignedExtension(sk ic.PrivKey, pubKey crypto.PublicKey) (pkix.Extension, error) {
|
||||
keyBytes, err := ic.MarshalPublicKey(sk.GetPublic())
|
||||
if err != nil {
|
||||
return pkix.Extension{}, err
|
||||
}
|
||||
certKeyPub, err := x509.MarshalPKIXPublicKey(pubKey)
|
||||
if err != nil {
|
||||
return pkix.Extension{}, err
|
||||
}
|
||||
signature, err := sk.Sign(append([]byte(certificatePrefix), certKeyPub...))
|
||||
if err != nil {
|
||||
return pkix.Extension{}, err
|
||||
}
|
||||
value, err := asn1.Marshal(signedKey{
|
||||
PubKey: keyBytes,
|
||||
Signature: signature,
|
||||
})
|
||||
if err != nil {
|
||||
return pkix.Extension{}, err
|
||||
}
|
||||
|
||||
return pkix.Extension{Id: extensionID, Critical: extensionCritical, Value: value}, nil
|
||||
}
|
||||
|
||||
// keyToCertificate generates a new ECDSA private key and corresponding x509 certificate.
|
||||
// The certificate includes an extension that cryptographically ties it to the provided libp2p
|
||||
// private key to authenticate TLS connections.
|
||||
func keyToCertificate(sk ic.PrivKey, certTmpl *x509.Certificate) (*tls.Certificate, error) {
|
||||
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// after calling CreateCertificate, these will end up in Certificate.Extensions
|
||||
extension, err := GenerateSignedExtension(sk, certKey.Public())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certTmpl.ExtraExtensions = append(certTmpl.ExtraExtensions, extension)
|
||||
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, certTmpl, certTmpl, certKey.Public(), certKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tls.Certificate{
|
||||
Certificate: [][]byte{certDER},
|
||||
PrivateKey: certKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// certTemplate returns the template for generating an Identity's TLS certificates.
|
||||
func certTemplate() (*x509.Certificate, error) {
|
||||
bigNum := big.NewInt(1 << 62)
|
||||
sn, err := rand.Int(rand.Reader, bigNum)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
subjectSN, err := rand.Int(rand.Reader, bigNum)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &x509.Certificate{
|
||||
SerialNumber: sn,
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(certValidityPeriod),
|
||||
// According to RFC 3280, the issuer field must be set,
|
||||
// see https://datatracker.ietf.org/doc/html/rfc3280#section-4.1.2.4.
|
||||
Subject: pkix.Name{SerialNumber: subjectSN.String()},
|
||||
}, nil
|
||||
}
|
||||
22
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/extension.go
generated
vendored
Normal file
22
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/extension.go
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
package libp2ptls
|
||||
|
||||
var extensionPrefix = []int{1, 3, 6, 1, 4, 1, 53594}
|
||||
|
||||
// getPrefixedExtensionID returns an Object Identifier
|
||||
// that can be used in x509 Certificates.
|
||||
func getPrefixedExtensionID(suffix []int) []int {
|
||||
return append(extensionPrefix, suffix...)
|
||||
}
|
||||
|
||||
// extensionIDEqual compares two extension IDs.
|
||||
func extensionIDEqual(a, b []int) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
182
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/transport.go
generated
vendored
Normal file
182
vendor/github.com/libp2p/go-libp2p/p2p/security/tls/transport.go
generated
vendored
Normal file
@@ -0,0 +1,182 @@
|
||||
package libp2ptls
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/canonicallog"
|
||||
ci "github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/core/protocol"
|
||||
"github.com/libp2p/go-libp2p/core/sec"
|
||||
tptu "github.com/libp2p/go-libp2p/p2p/net/upgrader"
|
||||
|
||||
manet "github.com/multiformats/go-multiaddr/net"
|
||||
)
|
||||
|
||||
// ID is the protocol ID (used when negotiating with multistream)
|
||||
const ID = "/tls/1.0.0"
|
||||
|
||||
// Transport constructs secure communication sessions for a peer.
|
||||
type Transport struct {
|
||||
identity *Identity
|
||||
|
||||
localPeer peer.ID
|
||||
privKey ci.PrivKey
|
||||
muxers []protocol.ID
|
||||
protocolID protocol.ID
|
||||
}
|
||||
|
||||
var _ sec.SecureTransport = &Transport{}
|
||||
|
||||
// New creates a TLS encrypted transport
|
||||
func New(id protocol.ID, key ci.PrivKey, muxers []tptu.StreamMuxer) (*Transport, error) {
|
||||
localPeer, err := peer.IDFromPrivateKey(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
muxerIDs := make([]protocol.ID, 0, len(muxers))
|
||||
for _, m := range muxers {
|
||||
muxerIDs = append(muxerIDs, m.ID)
|
||||
}
|
||||
t := &Transport{
|
||||
protocolID: id,
|
||||
localPeer: localPeer,
|
||||
privKey: key,
|
||||
muxers: muxerIDs,
|
||||
}
|
||||
|
||||
identity, err := NewIdentity(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.identity = identity
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// SecureInbound runs the TLS handshake as a server.
|
||||
// If p is empty, connections from any peer are accepted.
|
||||
func (t *Transport) SecureInbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
config, keyCh := t.identity.ConfigForPeer(p)
|
||||
muxers := make([]string, 0, len(t.muxers))
|
||||
for _, muxer := range t.muxers {
|
||||
muxers = append(muxers, string(muxer))
|
||||
}
|
||||
// TLS' ALPN selection lets the server select the protocol, preferring the server's preferences.
|
||||
// We want to prefer the client's preference though.
|
||||
getConfigForClient := config.GetConfigForClient
|
||||
config.GetConfigForClient = func(info *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
alpnLoop:
|
||||
for _, proto := range info.SupportedProtos {
|
||||
for _, m := range muxers {
|
||||
if m == proto {
|
||||
// Match found. Select this muxer, as it's the client's preference.
|
||||
// There's no need to add the "libp2p" entry here.
|
||||
config.NextProtos = []string{proto}
|
||||
break alpnLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
if getConfigForClient != nil {
|
||||
return getConfigForClient(info)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
config.NextProtos = append(muxers, config.NextProtos...)
|
||||
cs, err := t.handshake(ctx, tls.Server(insecure, config), keyCh)
|
||||
if err != nil {
|
||||
addr, maErr := manet.FromNetAddr(insecure.RemoteAddr())
|
||||
if maErr == nil {
|
||||
canonicallog.LogPeerStatus(100, p, addr, "handshake_failure", "tls", "err", err.Error())
|
||||
}
|
||||
insecure.Close()
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// SecureOutbound runs the TLS handshake as a client.
|
||||
// Note that SecureOutbound will not return an error if the server doesn't
|
||||
// accept the certificate. This is due to the fact that in TLS 1.3, the client
|
||||
// sends its certificate and the ClientFinished in the same flight, and can send
|
||||
// application data immediately afterwards.
|
||||
// If the handshake fails, the server will close the connection. The client will
|
||||
// notice this after 1 RTT when calling Read.
|
||||
func (t *Transport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
|
||||
config, keyCh := t.identity.ConfigForPeer(p)
|
||||
muxers := make([]string, 0, len(t.muxers))
|
||||
for _, muxer := range t.muxers {
|
||||
muxers = append(muxers, (string)(muxer))
|
||||
}
|
||||
// Prepend the prefered muxers list to TLS config.
|
||||
config.NextProtos = append(muxers, config.NextProtos...)
|
||||
cs, err := t.handshake(ctx, tls.Client(insecure, config), keyCh)
|
||||
if err != nil {
|
||||
insecure.Close()
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
func (t *Transport) handshake(ctx context.Context, tlsConn *tls.Conn, keyCh <-chan ci.PubKey) (_sconn sec.SecureConn, err error) {
|
||||
defer func() {
|
||||
if rerr := recover(); rerr != nil {
|
||||
fmt.Fprintf(os.Stderr, "panic in TLS handshake: %s\n%s\n", rerr, debug.Stack())
|
||||
err = fmt.Errorf("panic in TLS handshake: %s", rerr)
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
// handshaking...
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Should be ready by this point, don't block.
|
||||
var remotePubKey ci.PubKey
|
||||
select {
|
||||
case remotePubKey = <-keyCh:
|
||||
default:
|
||||
}
|
||||
if remotePubKey == nil {
|
||||
return nil, errors.New("go-libp2p tls BUG: expected remote pub key to be set")
|
||||
}
|
||||
|
||||
return t.setupConn(tlsConn, remotePubKey)
|
||||
}
|
||||
|
||||
func (t *Transport) setupConn(tlsConn *tls.Conn, remotePubKey ci.PubKey) (sec.SecureConn, error) {
|
||||
remotePeerID, err := peer.IDFromPublicKey(remotePubKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nextProto := tlsConn.ConnectionState().NegotiatedProtocol
|
||||
// The special ALPN extension value "libp2p" is used by libp2p versions
|
||||
// that don't support early muxer negotiation. If we see this sepcial
|
||||
// value selected, that means we are handshaking with a version that does
|
||||
// not support early muxer negotiation. In this case return empty nextProto
|
||||
// to indicate no muxer is selected.
|
||||
if nextProto == "libp2p" {
|
||||
nextProto = ""
|
||||
}
|
||||
|
||||
return &conn{
|
||||
Conn: tlsConn,
|
||||
localPeer: t.localPeer,
|
||||
remotePeer: remotePeerID,
|
||||
remotePubKey: remotePubKey,
|
||||
connectionState: network.ConnectionState{
|
||||
StreamMultiplexer: protocol.ID(nextProto),
|
||||
UsedEarlyMuxerNegotiation: nextProto != "",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *Transport) ID() protocol.ID {
|
||||
return t.protocolID
|
||||
}
|
||||
Reference in New Issue
Block a user