auth.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package dbus
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "io"
  7. "os"
  8. "strconv"
  9. )
  10. // AuthStatus represents the Status of an authentication mechanism.
  11. type AuthStatus byte
  12. const (
  13. // AuthOk signals that authentication is finished; the next command
  14. // from the server should be an OK.
  15. AuthOk AuthStatus = iota
  16. // AuthContinue signals that additional data is needed; the next command
  17. // from the server should be a DATA.
  18. AuthContinue
  19. // AuthError signals an error; the server sent invalid data or some
  20. // other unexpected thing happened and the current authentication
  21. // process should be aborted.
  22. AuthError
  23. )
  24. type authState byte
  25. const (
  26. waitingForData authState = iota
  27. waitingForOk
  28. waitingForReject
  29. )
  30. // Auth defines the behaviour of an authentication mechanism.
  31. type Auth interface {
  32. // Return the name of the mechnism, the argument to the first AUTH command
  33. // and the next status.
  34. FirstData() (name, resp []byte, status AuthStatus)
  35. // Process the given DATA command, and return the argument to the DATA
  36. // command and the next status. If len(resp) == 0, no DATA command is sent.
  37. HandleData(data []byte) (resp []byte, status AuthStatus)
  38. }
  39. // Auth authenticates the connection, trying the given list of authentication
  40. // mechanisms (in that order). If nil is passed, the EXTERNAL and
  41. // DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
  42. // connections, this method must be called before sending any messages to the
  43. // bus. Auth must not be called on shared connections.
  44. func (conn *Conn) Auth(methods []Auth) error {
  45. if methods == nil {
  46. uid := strconv.Itoa(os.Getuid())
  47. methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
  48. }
  49. in := bufio.NewReader(conn.transport)
  50. err := conn.transport.SendNullByte()
  51. if err != nil {
  52. return err
  53. }
  54. err = authWriteLine(conn.transport, []byte("AUTH"))
  55. if err != nil {
  56. return err
  57. }
  58. s, err := authReadLine(in)
  59. if err != nil {
  60. return err
  61. }
  62. if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
  63. return errors.New("dbus: authentication protocol error")
  64. }
  65. s = s[1:]
  66. for _, v := range s {
  67. for _, m := range methods {
  68. if name, data, status := m.FirstData(); bytes.Equal(v, name) {
  69. var ok bool
  70. err = authWriteLine(conn.transport, []byte("AUTH"), []byte(v), data)
  71. if err != nil {
  72. return err
  73. }
  74. switch status {
  75. case AuthOk:
  76. err, ok = conn.tryAuth(m, waitingForOk, in)
  77. case AuthContinue:
  78. err, ok = conn.tryAuth(m, waitingForData, in)
  79. default:
  80. panic("dbus: invalid authentication status")
  81. }
  82. if err != nil {
  83. return err
  84. }
  85. if ok {
  86. if conn.transport.SupportsUnixFDs() {
  87. err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
  88. if err != nil {
  89. return err
  90. }
  91. line, err := authReadLine(in)
  92. if err != nil {
  93. return err
  94. }
  95. switch {
  96. case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
  97. conn.EnableUnixFDs()
  98. conn.unixFD = true
  99. case bytes.Equal(line[0], []byte("ERROR")):
  100. default:
  101. return errors.New("dbus: authentication protocol error")
  102. }
  103. }
  104. err = authWriteLine(conn.transport, []byte("BEGIN"))
  105. if err != nil {
  106. return err
  107. }
  108. go conn.inWorker()
  109. go conn.outWorker()
  110. return nil
  111. }
  112. }
  113. }
  114. }
  115. return errors.New("dbus: authentication failed")
  116. }
  117. // tryAuth tries to authenticate with m as the mechanism, using state as the
  118. // initial authState and in for reading input. It returns (nil, true) on
  119. // success, (nil, false) on a REJECTED and (someErr, false) if some other
  120. // error occured.
  121. func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
  122. for {
  123. s, err := authReadLine(in)
  124. if err != nil {
  125. return err, false
  126. }
  127. switch {
  128. case state == waitingForData && string(s[0]) == "DATA":
  129. if len(s) != 2 {
  130. err = authWriteLine(conn.transport, []byte("ERROR"))
  131. if err != nil {
  132. return err, false
  133. }
  134. continue
  135. }
  136. data, status := m.HandleData(s[1])
  137. switch status {
  138. case AuthOk, AuthContinue:
  139. if len(data) != 0 {
  140. err = authWriteLine(conn.transport, []byte("DATA"), data)
  141. if err != nil {
  142. return err, false
  143. }
  144. }
  145. if status == AuthOk {
  146. state = waitingForOk
  147. }
  148. case AuthError:
  149. err = authWriteLine(conn.transport, []byte("ERROR"))
  150. if err != nil {
  151. return err, false
  152. }
  153. }
  154. case state == waitingForData && string(s[0]) == "REJECTED":
  155. return nil, false
  156. case state == waitingForData && string(s[0]) == "ERROR":
  157. err = authWriteLine(conn.transport, []byte("CANCEL"))
  158. if err != nil {
  159. return err, false
  160. }
  161. state = waitingForReject
  162. case state == waitingForData && string(s[0]) == "OK":
  163. if len(s) != 2 {
  164. err = authWriteLine(conn.transport, []byte("CANCEL"))
  165. if err != nil {
  166. return err, false
  167. }
  168. state = waitingForReject
  169. }
  170. conn.uuid = string(s[1])
  171. return nil, true
  172. case state == waitingForData:
  173. err = authWriteLine(conn.transport, []byte("ERROR"))
  174. if err != nil {
  175. return err, false
  176. }
  177. case state == waitingForOk && string(s[0]) == "OK":
  178. if len(s) != 2 {
  179. err = authWriteLine(conn.transport, []byte("CANCEL"))
  180. if err != nil {
  181. return err, false
  182. }
  183. state = waitingForReject
  184. }
  185. conn.uuid = string(s[1])
  186. return nil, true
  187. case state == waitingForOk && string(s[0]) == "REJECTED":
  188. return nil, false
  189. case state == waitingForOk && (string(s[0]) == "DATA" ||
  190. string(s[0]) == "ERROR"):
  191. err = authWriteLine(conn.transport, []byte("CANCEL"))
  192. if err != nil {
  193. return err, false
  194. }
  195. state = waitingForReject
  196. case state == waitingForOk:
  197. err = authWriteLine(conn.transport, []byte("ERROR"))
  198. if err != nil {
  199. return err, false
  200. }
  201. case state == waitingForReject && string(s[0]) == "REJECTED":
  202. return nil, false
  203. case state == waitingForReject:
  204. return errors.New("dbus: authentication protocol error"), false
  205. default:
  206. panic("dbus: invalid auth state")
  207. }
  208. }
  209. }
  210. // authReadLine reads a line and separates it into its fields.
  211. func authReadLine(in *bufio.Reader) ([][]byte, error) {
  212. data, err := in.ReadBytes('\n')
  213. if err != nil {
  214. return nil, err
  215. }
  216. data = bytes.TrimSuffix(data, []byte("\r\n"))
  217. return bytes.Split(data, []byte{' '}), nil
  218. }
  219. // authWriteLine writes the given line in the authentication protocol format
  220. // (elements of data separated by a " " and terminated by "\r\n").
  221. func authWriteLine(out io.Writer, data ...[]byte) error {
  222. buf := make([]byte, 0)
  223. for i, v := range data {
  224. buf = append(buf, v...)
  225. if i != len(data)-1 {
  226. buf = append(buf, ' ')
  227. }
  228. }
  229. buf = append(buf, '\r')
  230. buf = append(buf, '\n')
  231. n, err := out.Write(buf)
  232. if err != nil {
  233. return err
  234. }
  235. if n != len(buf) {
  236. return io.ErrUnexpectedEOF
  237. }
  238. return nil
  239. }