1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
|
package smb2
import (
"context"
"crypto/rand"
"crypto/sha512"
"fmt"
"os"
"sync"
"sync/atomic"
"github.com/cloudsoda/go-smb2/internal/erref"
. "github.com/cloudsoda/go-smb2/internal/smb2"
)
// Negotiator contains options for func (*Dialer) Dial.
type Negotiator struct {
RequireMessageSigning bool // enforce signing?
ClientGuid [16]byte // if it's zero, generated by crypto/rand.
SpecifiedDialect uint16 // if it's zero, clientDialects is used. (See feature.go for more details)
}
func (n *Negotiator) makeRequest() (*NegotiateRequest, error) {
req := new(NegotiateRequest)
if n.RequireMessageSigning {
req.SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED
} else {
req.SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED
}
req.Capabilities = clientCapabilities
if n.ClientGuid == zero {
_, err := rand.Read(req.ClientGuid[:])
if err != nil {
return nil, &InternalError{err.Error()}
}
} else {
req.ClientGuid = n.ClientGuid
}
if n.SpecifiedDialect != UnknownSMB {
req.Dialects = []uint16{n.SpecifiedDialect}
switch n.SpecifiedDialect {
case SMB202:
case SMB210:
case SMB300:
case SMB302:
case SMB311:
hc := &HashContext{
HashAlgorithms: clientHashAlgorithms,
HashSalt: make([]byte, 32),
}
if _, err := rand.Read(hc.HashSalt); err != nil {
return nil, &InternalError{err.Error()}
}
cc := &CipherContext{
Ciphers: clientCiphers,
}
req.Contexts = append(req.Contexts, hc, cc)
default:
return nil, &InternalError{"unsupported dialect specified"}
}
} else {
req.Dialects = clientDialects
hc := &HashContext{
HashAlgorithms: clientHashAlgorithms,
HashSalt: make([]byte, 32),
}
if _, err := rand.Read(hc.HashSalt); err != nil {
return nil, &InternalError{err.Error()}
}
cc := &CipherContext{
Ciphers: clientCiphers,
}
req.Contexts = append(req.Contexts, hc, cc)
}
return req, nil
}
func (n *Negotiator) negotiate(t transport, a *account, ctx context.Context) (*conn, error) {
conn := &conn{
t: t,
outstandingRequests: newOutstandingRequests(),
account: a,
rdone: make(chan struct{}, 1),
wdone: make(chan struct{}, 1),
write: make(chan []byte, 1),
werr: make(chan error, 1),
}
go conn.runSender()
go conn.runReciever()
retry:
req, err := n.makeRequest()
if err != nil {
return nil, err
}
req.CreditCharge = 1
rr, err := conn.send(req, ctx)
if err != nil {
return nil, err
}
pkt, err := conn.recv(rr)
if err != nil {
return nil, err
}
res, err := accept(SMB2_NEGOTIATE, pkt)
if err != nil {
return nil, err
}
r := NegotiateResponseDecoder(res)
if r.IsInvalid() {
return nil, &InvalidResponseError{"broken negotiate response format"}
}
if r.DialectRevision() == SMB2 {
n.SpecifiedDialect = SMB210
goto retry
}
if n.SpecifiedDialect != UnknownSMB && n.SpecifiedDialect != r.DialectRevision() {
return nil, &InvalidResponseError{"unexpected dialect returned"}
}
conn.requireSigning = n.RequireMessageSigning || r.SecurityMode()&SMB2_NEGOTIATE_SIGNING_REQUIRED != 0
conn.capabilities = clientCapabilities & r.Capabilities()
conn.dialect = r.DialectRevision()
conn.maxTransactSize = r.MaxTransactSize()
conn.maxReadSize = r.MaxReadSize()
conn.maxWriteSize = r.MaxWriteSize()
conn.sequenceWindow = 1
// conn.gssNegotiateToken = r.SecurityBuffer()
// conn.clientGuid = n.ClientGuid
// copy(conn.serverGuid[:], r.ServerGuid())
if conn.dialect != SMB311 {
return conn, nil
}
// handle context for SMB311
list := r.NegotiateContextList()
for count := r.NegotiateContextCount(); count > 0; count-- {
ctx := NegotiateContextDecoder(list)
if ctx.IsInvalid() {
return nil, &InvalidResponseError{"broken negotiate context format"}
}
switch ctx.ContextType() {
case SMB2_PREAUTH_INTEGRITY_CAPABILITIES:
d := HashContextDataDecoder(ctx.Data())
if d.IsInvalid() {
return nil, &InvalidResponseError{"broken hash context data format"}
}
algs := d.HashAlgorithms()
if len(algs) != 1 {
return nil, &InvalidResponseError{"multiple hash algorithms"}
}
conn.preauthIntegrityHashId = algs[0]
switch conn.preauthIntegrityHashId {
case SHA512:
h := sha512.New()
h.Write(conn.preauthIntegrityHashValue[:])
h.Write(rr.pkt)
h.Sum(conn.preauthIntegrityHashValue[:0])
h.Reset()
h.Write(conn.preauthIntegrityHashValue[:])
h.Write(pkt)
h.Sum(conn.preauthIntegrityHashValue[:0])
default:
return nil, &InvalidResponseError{"unknown hash algorithm"}
}
case SMB2_ENCRYPTION_CAPABILITIES:
d := CipherContextDataDecoder(ctx.Data())
if d.IsInvalid() {
return nil, &InvalidResponseError{"broken cipher context data format"}
}
ciphs := d.Ciphers()
if len(ciphs) != 1 {
return nil, &InvalidResponseError{"multiple cipher algorithms"}
}
conn.cipherId = ciphs[0]
switch conn.cipherId {
case AES128CCM:
case AES128GCM:
default:
return nil, &InvalidResponseError{"unknown cipher algorithm"}
}
default:
// skip unsupported context
}
off := ctx.Next()
if len(list) < off {
list = nil
} else {
list = list[off:]
}
}
return conn, nil
}
type requestResponse struct {
msgId uint64
asyncId uint64
creditRequest uint16
pkt []byte // request packet
ctx context.Context
recv chan []byte
err error
}
type outstandingRequests struct {
m sync.Mutex
requests map[uint64]*requestResponse
}
func newOutstandingRequests() *outstandingRequests {
return &outstandingRequests{
requests: make(map[uint64]*requestResponse, 0),
}
}
func (r *outstandingRequests) pop(msgId uint64) (*requestResponse, bool) {
r.m.Lock()
defer r.m.Unlock()
rr, ok := r.requests[msgId]
if !ok {
return nil, false
}
delete(r.requests, msgId)
return rr, true
}
func (r *outstandingRequests) set(msgId uint64, rr *requestResponse) {
r.m.Lock()
defer r.m.Unlock()
r.requests[msgId] = rr
}
func (r *outstandingRequests) shutdown(err error) {
r.m.Lock()
defer r.m.Unlock()
for _, rr := range r.requests {
rr.err = err
close(rr.recv)
}
}
type conn struct {
t transport
session *session
outstandingRequests *outstandingRequests
sequenceWindow uint64
dialect uint16
maxTransactSize uint32
maxReadSize uint32
maxWriteSize uint32
requireSigning bool
capabilities uint32
preauthIntegrityHashId uint16
preauthIntegrityHashValue [64]byte
cipherId uint16
account *account
rdone chan struct{}
wdone chan struct{}
write chan []byte
werr chan error
m sync.Mutex
err error
// gssNegotiateToken []byte
// serverGuid [16]byte
// clientGuid [16]byte
_useSession int32 // receiver use session?
}
func (conn *conn) useSession() bool {
return atomic.LoadInt32(&conn._useSession) != 0
}
func (conn *conn) enableSession() {
atomic.StoreInt32(&conn._useSession, 1)
}
//nolint:unused // appears to be legacy, unsure, so leaving for now
func (conn *conn) sendRecv(cmd uint16, req Packet, ctx context.Context) (res []byte, err error) {
rr, err := conn.send(req, ctx)
if err != nil {
return nil, err
}
pkt, err := conn.recv(rr)
if err != nil {
return nil, err
}
return accept(cmd, pkt)
}
func (conn *conn) loanCredit(payloadSize int, ctx context.Context) (creditCharge uint16, grantedPayloadSize int, err error) {
if conn.capabilities&SMB2_GLOBAL_CAP_LARGE_MTU == 0 {
creditCharge = 1
} else {
creditCharge = uint16((payloadSize-1)/(64*1024) + 1)
}
creditCharge, isComplete, err := conn.account.loan(creditCharge, ctx)
if err != nil {
return creditCharge, 0, err
}
if isComplete {
return creditCharge, payloadSize, nil
}
return creditCharge, 64 * 1024 * int(creditCharge), nil
}
func (conn *conn) chargeCredit(creditCharge uint16) {
conn.account.charge(creditCharge, creditCharge)
}
func (conn *conn) send(req Packet, ctx context.Context) (rr *requestResponse, err error) {
return conn.sendWith(req, nil, ctx)
}
func (conn *conn) sendWith(req Packet, tc *treeConn, ctx context.Context) (rr *requestResponse, err error) {
conn.m.Lock()
defer conn.m.Unlock()
if conn.err != nil {
return nil, conn.err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// do nothing
}
rr, err = conn.makeRequestResponse(req, tc, ctx)
if err != nil {
return nil, err
}
select {
case conn.write <- rr.pkt:
select {
case err = <-conn.werr:
if err != nil {
conn.outstandingRequests.pop(rr.msgId)
return nil, &TransportError{err}
}
case <-ctx.Done():
conn.outstandingRequests.pop(rr.msgId)
return nil, ctx.Err()
}
case <-ctx.Done():
conn.outstandingRequests.pop(rr.msgId)
return nil, ctx.Err()
}
return rr, nil
}
func (conn *conn) makeRequestResponse(req Packet, tc *treeConn, ctx context.Context) (rr *requestResponse, err error) {
hdr := req.Header()
var msgId uint64
if _, ok := req.(*CancelRequest); !ok {
msgId = conn.sequenceWindow
creditCharge := hdr.CreditCharge
conn.sequenceWindow += uint64(creditCharge)
if hdr.CreditRequestResponse == 0 {
hdr.CreditRequestResponse = creditCharge
}
hdr.CreditRequestResponse += conn.account.opening()
}
hdr.MessageId = msgId
s := conn.session
if s != nil {
hdr.SessionId = s.sessionId
if tc != nil {
hdr.TreeId = tc.treeId
}
}
pkt := make([]byte, req.Size())
req.Encode(pkt)
if s != nil {
if _, ok := req.(*SessionSetupRequest); !ok {
if s.sessionFlags&SMB2_SESSION_FLAG_ENCRYPT_DATA != 0 || (tc != nil && tc.shareFlags&SMB2_SHAREFLAG_ENCRYPT_DATA != 0) {
pkt, err = s.encrypt(pkt)
if err != nil {
return nil, &InternalError{err.Error()}
}
} else {
if s.sessionFlags&(SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL) == 0 {
pkt = s.sign(pkt)
}
}
}
}
rr = &requestResponse{
msgId: msgId,
creditRequest: hdr.CreditRequestResponse,
pkt: pkt,
ctx: ctx,
recv: make(chan []byte, 1),
}
conn.outstandingRequests.set(msgId, rr)
return rr, nil
}
func (conn *conn) recv(rr *requestResponse) ([]byte, error) {
select {
case pkt := <-rr.recv:
if rr.err != nil {
return nil, rr.err
}
return pkt, nil
case <-rr.ctx.Done():
conn.outstandingRequests.pop(rr.msgId)
return nil, rr.ctx.Err()
}
}
func (conn *conn) runSender() {
for {
select {
case <-conn.wdone:
return
case pkt := <-conn.write:
_, err := conn.t.Write(pkt)
conn.werr <- err
}
}
}
func (conn *conn) runReciever() {
var err error
for {
n, e := conn.t.ReadSize()
if e != nil {
err = &TransportError{e}
goto exit
}
pkt := make([]byte, n)
_, e = conn.t.Read(pkt)
if e != nil {
err = &TransportError{e}
goto exit
}
hasSession := conn.useSession()
var isEncrypted bool
if hasSession {
pkt, e, isEncrypted = conn.tryDecrypt(pkt)
if e != nil {
logger.Println("skip:", e)
continue
}
p := PacketCodec(pkt)
if s := conn.session; s != nil {
if s.sessionId != p.SessionId() {
logger.Println("skip:", &InvalidResponseError{"unknown session id"})
continue
}
if tc, ok := s.treeConnTables[p.TreeId()]; ok {
if tc.treeId != p.TreeId() {
logger.Println("skip:", &InvalidResponseError{"unknown tree id"})
continue
}
}
}
}
var next []byte
for {
p := PacketCodec(pkt)
if off := p.NextCommand(); off != 0 {
pkt, next = pkt[:off], pkt[off:]
} else {
next = nil
}
if hasSession {
e = conn.tryVerify(pkt, isEncrypted)
}
e = conn.tryHandle(pkt, e)
if e != nil {
logger.Println("skip:", e)
}
if next == nil {
break
}
pkt = next
}
}
exit:
select {
case <-conn.rdone:
err = nil
default:
logger.Println("error:", err)
}
conn.m.Lock()
defer conn.m.Unlock()
conn.outstandingRequests.shutdown(err)
conn.err = err
close(conn.wdone)
}
func accept(cmd uint16, pkt []byte) (res []byte, err error) {
p := PacketCodec(pkt)
if command := p.Command(); cmd != command {
return nil, &InvalidResponseError{fmt.Sprintf("expected command: %v, got %v", cmd, command)}
}
status := erref.NtStatus(p.Status())
switch status {
case erref.STATUS_SUCCESS:
return p.Data(), nil
case erref.STATUS_OBJECT_NAME_COLLISION:
return nil, os.ErrExist
case erref.STATUS_OBJECT_NAME_NOT_FOUND, erref.STATUS_OBJECT_PATH_NOT_FOUND:
return nil, os.ErrNotExist
case erref.STATUS_ACCESS_DENIED, erref.STATUS_CANNOT_DELETE:
return nil, os.ErrPermission
}
switch cmd {
case SMB2_SESSION_SETUP:
if status == erref.STATUS_MORE_PROCESSING_REQUIRED {
return p.Data(), nil
}
case SMB2_QUERY_INFO:
if status == erref.STATUS_BUFFER_OVERFLOW {
return nil, &ResponseError{Code: uint32(status)}
}
case SMB2_IOCTL:
if status == erref.STATUS_BUFFER_OVERFLOW {
if !IoctlResponseDecoder(p.Data()).IsInvalid() {
return p.Data(), &ResponseError{Code: uint32(status)}
}
}
case SMB2_READ:
if status == erref.STATUS_BUFFER_OVERFLOW {
return nil, &ResponseError{Code: uint32(status)}
}
case SMB2_CHANGE_NOTIFY:
if status == erref.STATUS_NOTIFY_ENUM_DIR {
return nil, &ResponseError{Code: uint32(status)}
}
}
return nil, acceptError(uint32(status), p.Data())
}
func acceptError(status uint32, res []byte) error {
r := ErrorResponseDecoder(res)
if r.IsInvalid() {
return &InvalidResponseError{"broken error response format"}
}
eData := r.ErrorData()
if count := r.ErrorContextCount(); count != 0 {
data := make([][]byte, count)
for i := range data {
ctx := ErrorContextResponseDecoder(eData)
if ctx.IsInvalid() {
return &InvalidResponseError{"broken error context response format"}
}
data[i] = ctx.ErrorContextData()
next := ctx.Next()
if len(eData) < next {
return &InvalidResponseError{"broken error context response format"}
}
eData = eData[next:]
}
return &ResponseError{Code: status, data: data}
}
return &ResponseError{Code: status, data: [][]byte{eData}}
}
func (conn *conn) tryDecrypt(pkt []byte) ([]byte, error, bool) {
p := PacketCodec(pkt)
if p.IsInvalid() {
t := TransformCodec(pkt)
if t.IsInvalid() {
return nil, &InvalidResponseError{"broken packet header format"}, false
}
if t.Flags() != Encrypted {
return nil, &InvalidResponseError{"encrypted flag is not on"}, false
}
if conn.session == nil || conn.session.sessionId != t.SessionId() {
return nil, &InvalidResponseError{"unknown session id returned"}, false
}
pkt, err := conn.session.decrypt(pkt)
if err != nil {
return nil, &InvalidResponseError{err.Error()}, false
}
return pkt, nil, true
}
return pkt, nil, false
}
func (conn *conn) tryVerify(pkt []byte, isEncrypted bool) error {
p := PacketCodec(pkt)
msgId := p.MessageId()
if msgId != 0xFFFFFFFFFFFFFFFF {
if p.Flags()&SMB2_FLAGS_SIGNED != 0 {
if conn.session == nil || conn.session.sessionId != p.SessionId() {
return &InvalidResponseError{"unknown session id returned"}
} else {
if !conn.session.verify(pkt) {
return &InvalidResponseError{"unverified packet returned"}
}
}
} else {
if conn.requireSigning && !isEncrypted {
if conn.session != nil {
if conn.session.sessionFlags&(SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL) == 0 {
if conn.session.sessionId == p.SessionId() {
return &InvalidResponseError{"signing required"}
}
}
}
}
}
}
return nil
}
func (conn *conn) tryHandle(pkt []byte, e error) error {
p := PacketCodec(pkt)
msgId := p.MessageId()
rr, ok := conn.outstandingRequests.pop(msgId)
switch {
case !ok:
return &InvalidResponseError{"unknown message id returned"}
case e != nil:
rr.err = e
close(rr.recv)
case erref.NtStatus(p.Status()) == erref.STATUS_PENDING:
rr.asyncId = p.AsyncId()
conn.account.charge(p.CreditResponse(), rr.creditRequest)
conn.outstandingRequests.set(msgId, rr)
default:
conn.account.charge(p.CreditResponse(), rr.creditRequest)
rr.recv <- pkt
}
return nil
}
|