本文整理汇总了Golang中golang.org/x/crypto/ssh.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: parseECDSACert
func parseECDSACert(req []byte) (*AddedKey, error) {
var k ecdsaCertMsg
if err := ssh.Unmarshal(req, &k); err != nil {
return nil, err
}
pubKey, err := ssh.ParsePublicKey(k.CertBytes)
if err != nil {
return nil, err
}
cert, ok := pubKey.(*ssh.Certificate)
if !ok {
return nil, errors.New("agent: bad ECDSA certificate")
}
// An ECDSA publickey as marshaled by ecdsaPublicKey.Marshal() in keys.go
var ecdsaPub struct {
Name string
ID string
Key []byte
}
if err := ssh.Unmarshal(cert.Key.Marshal(), &ecdsaPub); err != nil {
return nil, err
}
priv, err := unmarshalECDSA(ecdsaPub.ID, ecdsaPub.Key, k.D)
if err != nil {
return nil, err
}
return &AddedKey{PrivateKey: priv, Certificate: cert, Comment: k.Comments}, nil
}
示例2: insertIdentity
func (s *server) insertIdentity(req []byte) error {
var record struct {
Type string `sshtype:"17"`
Rest []byte `ssh:"rest"`
}
if err := ssh.Unmarshal(req, &record); err != nil {
return err
}
switch record.Type {
case ssh.KeyAlgoRSA:
var k rsaKeyMsg
if err := ssh.Unmarshal(req, &k); err != nil {
return err
}
priv := rsa.PrivateKey{
PublicKey: rsa.PublicKey{
E: int(k.E.Int64()),
N: k.N,
},
D: k.D,
Primes: []*big.Int{k.P, k.Q},
}
priv.Precompute()
return s.agent.Add(AddedKey{PrivateKey: &priv, Comment: k.Comments})
}
return fmt.Errorf("not implemented: %s", record.Type)
}
示例3: handleRequests
func (s *sshServer) handleRequests(channel ssh.Channel, in <-chan *ssh.Request) error {
env := make(map[string]string)
for req := range in {
switch req.Type {
default:
log.Printf("unrecognized ssh request type=%q payload=%s wantreply=%t", req.Type, req.Payload, req.WantReply)
req.Reply(false, nil) // unhandled; tell them so
case "env":
var e envReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
env[string(e.Key)] = string(e.Val)
case "exec":
var e execReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
var cmdbuf bytes.Buffer
for k, v := range env {
cmdbuf.WriteString(k)
cmdbuf.WriteByte('=')
cmdbuf.WriteString(v)
cmdbuf.WriteByte(' ')
}
cmdbuf.Write(e.Command)
log.Printf("Running command %q", cmdbuf.String())
cmd := &packer.RemoteCmd{Command: cmdbuf.String()}
cmd.Stdout = channel
cmd.Stderr = channel.Stderr()
var rc int
if err := s.comm.Start(cmd); err != nil {
rc = 255 // TODO: What is a better choice here?
} else {
cmd.Wait()
rc = cmd.ExitStatus
}
channel.CloseWrite()
channel.SendRequest("exit-status", false, []byte{0, 0, 0, byte(rc)})
channel.Close()
}
}
return nil
}
示例4: SSHNativeParsePublicKey
// SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
// NOTE: ed25519 is not supported.
func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
fields := strings.Fields(keyLine)
if len(fields) < 2 {
return "", 0, fmt.Errorf("not enough fields in public key line: %s", string(keyLine))
}
raw, err := base64.StdEncoding.DecodeString(fields[1])
if err != nil {
return "", 0, err
}
pkey, err := ssh.ParsePublicKey(raw)
if err != nil {
if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
return "", 0, ErrKeyUnableVerify{err.Error()}
}
return "", 0, fmt.Errorf("ssh.ParsePublicKey: %v", err)
}
// The ssh library can parse the key, so next we find out what key exactly we have.
switch pkey.Type() {
case ssh.KeyAlgoDSA:
rawPub := struct {
Name string
P, Q, G, Y *big.Int
}{}
if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
return "", 0, err
}
// as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
// see dsa keys != 1024 bit, but as it seems to work, we will not check here
return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
case ssh.KeyAlgoRSA:
rawPub := struct {
Name string
E *big.Int
N *big.Int
}{}
if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
return "", 0, err
}
return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
case ssh.KeyAlgoECDSA256:
return "ecdsa", 256, nil
case ssh.KeyAlgoECDSA384:
return "ecdsa", 384, nil
case ssh.KeyAlgoECDSA521:
return "ecdsa", 521, nil
case "ssh-ed25519": // TODO replace with ssh constant when available
return "ed25519", 256, nil
}
return "", 0, fmt.Errorf("Unsupported key length detection for type: %s", pkey.Type())
}
示例5: decodeClient
// decodeClient decodes a response packet's raw data into its corresponding
// message structure.
func decodeClient(packet []byte) (interface{}, error) {
var msg interface{}
switch packet[0] {
case fxpPacketVersion:
msg = new(fxpVersionMsg)
case fxpPacketStatus:
msg = new(fxpStatusResp)
case fxpPacketHandle:
msg = new(fxpHandleResp)
case fxpPacketData:
msg = new(fxpDataResp)
case fxpPacketName:
msg = new(fxpNameResp)
case fxpPacketAttrs:
msg = new(fxpAttrsResp)
case fxpPacketExtendedReply:
msg = new(fxpExtendedResp)
default:
return nil, UnexpectedMessageError{0, packet[0]}
}
if err := ssh.Unmarshal(packet, msg); err != nil {
return nil, err
}
return msg, nil
}
示例6: handlePtyRequest
func (sess *session) handlePtyRequest(request *ssh.Request) {
logger := sess.logger.Session("handle-pty-request")
var ptyRequestMessage ptyRequestMsg
err := ssh.Unmarshal(request.Payload, &ptyRequestMessage)
if err != nil {
logger.Error("unmarshal-failed", err)
if request.WantReply {
request.Reply(false, nil)
}
return
}
sess.Lock()
defer sess.Unlock()
sess.allocPty = true
sess.ptyRequest = ptyRequestMessage
sess.env["TERM"] = ptyRequestMessage.Term
if request.WantReply {
request.Reply(true, nil)
}
}
示例7: handleSignalRequest
func (sess *session) handleSignalRequest(request *ssh.Request) {
logger := sess.logger.Session("handle-signal-request")
type signalMsg struct {
Signal string
}
var signalMessage signalMsg
err := ssh.Unmarshal(request.Payload, &signalMessage)
if err != nil {
logger.Error("unmarshal-failed", err)
if request.WantReply {
request.Reply(false, nil)
}
return
}
sess.Lock()
defer sess.Unlock()
cmd := sess.command
if cmd != nil {
signal := signals.SyscallSignals[ssh.Signal(signalMessage.Signal)]
err := sess.runner.Signal(cmd, signal)
if err != nil {
logger.Error("process-signal-failed", err)
}
}
if request.WantReply {
request.Reply(true, nil)
}
}
示例8: handleSSHChannel
func handleSSHChannel(newChan ssh.NewChannel, session *Session) {
ch, reqs, err := newChan.Accept()
if err != nil {
log.Println("handle channel failed:", err)
return
}
exitCh := make(chan int)
go func() {
status := struct{ Status uint32 }{uint32(<-exitCh)}
_, err = ch.SendRequest("exit-status", false, ssh.Marshal(&status))
assert(err)
ch.Close()
}()
for req := range reqs {
go func(req *ssh.Request) {
if req.WantReply {
req.Reply(true, nil)
}
switch req.Type {
case "exec":
var payload = struct{ Value string }{}
ssh.Unmarshal(req.Payload, &payload)
line := strings.Trim(payload.Value, "\n")
var args []string
if line != "" {
args = strings.Split(line, " ")
}
RunCmd(args, ch, ch, ch.Stderr(), exitCh, session)
}
}(req)
}
}
示例9: insertIdentity
func (s *server) insertIdentity(req []byte) error {
var record struct {
Type string `sshtype:"17|25"`
Rest []byte `ssh:"rest"`
}
if err := ssh.Unmarshal(req, &record); err != nil {
return err
}
var addedKey *AddedKey
var err error
switch record.Type {
case ssh.KeyAlgoRSA:
addedKey, err = parseRSAKey(req)
case ssh.KeyAlgoDSA:
addedKey, err = parseDSAKey(req)
case ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521:
addedKey, err = parseECDSACert(req)
case ssh.CertAlgoRSAv01:
addedKey, err = parseRSACert(req)
case ssh.CertAlgoDSAv01:
addedKey, err = parseDSACert(req)
case ssh.CertAlgoECDSA256v01, ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01:
addedKey, err = parseECDSACert(req)
default:
return fmt.Errorf("agent: not implemented: %q", record.Type)
}
if err != nil {
return err
}
return s.agent.Add(*addedKey)
}
示例10: handleNewPortForwardChannel
func (sshClient *sshClient) handleNewPortForwardChannel(newChannel ssh.NewChannel) {
defer sshClient.channelHandlerWaitGroup.Done()
// http://tools.ietf.org/html/rfc4254#section-7.2
var directTcpipExtraData struct {
HostToConnect string
PortToConnect uint32
OriginatorIPAddress string
OriginatorPort uint32
}
err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
if err != nil {
sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
return
}
// Intercept TCP port forwards to a specified udpgw server and handle directly.
// TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
isUDPChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
fmt.Sprintf("%s:%d",
directTcpipExtraData.HostToConnect,
directTcpipExtraData.PortToConnect)
if isUDPChannel {
sshClient.handleUDPChannel(newChannel)
} else {
sshClient.handleTCPChannel(
directTcpipExtraData.HostToConnect, int(directTcpipExtraData.PortToConnect), newChannel)
}
}
示例11: handleEnv
func (h *sshHandler) handleEnv(req *ssh.Request) {
var pair EnvVar
ssh.Unmarshal(req.Payload, &pair)
envvar := fmt.Sprintf("%s=%s", pair.Name, pair.Value)
h.Env = append(h.Env, envvar)
req.Reply(true, nil)
}
示例12: HandleNewChannel
func (handler *DirectTcpipChannelHandler) HandleNewChannel(logger lager.Logger, newChannel ssh.NewChannel) {
type channelOpenDirectTcpipMsg struct {
TargetAddr string
TargetPort uint32
OriginAddr string
OriginPort uint32
}
var directTcpipMessage channelOpenDirectTcpipMsg
err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipMessage)
if err != nil {
newChannel.Reject(ssh.ConnectionFailed, "Failed to parse open channel message")
return
}
destination := fmt.Sprintf("%s:%d", directTcpipMessage.TargetAddr, directTcpipMessage.TargetPort)
conn, err := handler.dialer.Dial("tcp", destination)
if err != nil {
newChannel.Reject(ssh.ConnectionFailed, err.Error())
return
}
channel, requests, err := newChannel.Accept()
go ssh.DiscardRequests(requests)
wg := &sync.WaitGroup{}
wg.Add(2)
go helpers.CopyAndClose(logger.Session("to-target"), wg, conn, channel)
go helpers.CopyAndClose(logger.Session("to-channel"), wg, channel, conn)
wg.Wait()
}
示例13: handleExecRequest
func (sess *session) handleExecRequest(request *ssh.Request) {
logger := sess.logger.Session("handle-exec-request")
type execMsg struct {
Command string
}
var execMessage execMsg
err := ssh.Unmarshal(request.Payload, &execMessage)
if err != nil {
logger.Error("unmarshal-failed", err)
if request.WantReply {
request.Reply(false, nil)
}
return
}
if scpRegex.MatchString(execMessage.Command) {
logger.Info("handling-scp-command", lager.Data{"Command": execMessage.Command})
sess.executeSCP(execMessage.Command, request)
} else {
logger.Info("executeShell", lager.Data{"request": request, "command": execMessage.Command})
sess.executeShell(request, "-c", execMessage.Command)
}
}
示例14: cleanExec
// cleanExec cleans the exec string.
func cleanExec(pay []byte) string {
e := &ExecCmd{}
ssh.Unmarshal(pay, e)
// TODO: Minimal escaping of values in command. There is probably a better
// way of doing this.
r := strings.NewReplacer("$", "", "`", "'")
return r.Replace(e.Value)
}
示例15: parseEd25519Key
func parseEd25519Key(req []byte) (*AddedKey, error) {
var k ed25519KeyMsg
if err := ssh.Unmarshal(req, &k); err != nil {
return nil, err
}
priv := ed25519.PrivateKey(k.Priv)
return &AddedKey{PrivateKey: &priv, Comment: k.Comments}, nil
}