mmgen-autosign 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmgen-autosign: Auto-sign MMGen transactions
  20. """
  21. import sys,os,subprocess,time,signal
  22. from stat import *
  23. from mmgen.common import *
  24. prog_name = os.path.basename(sys.argv[0])
  25. opts_data = lambda: {
  26. 'desc': 'Auto-sign MMGen transactions',
  27. 'usage':'[opts] [command]',
  28. 'options': """
  29. -h, --help Print this help message
  30. --, --longhelp Print help message for long options (common options)
  31. -l, --led Use status LED to signal standby, busy and error
  32. -s, --stealth-led Stealth LED mode - signal busy and error only, and only
  33. after successful authorization.
  34. """,
  35. 'notes': """
  36. COMMANDS
  37. gen_secret - generate the shared secret and copy to /dev/shm and USB stick
  38. wait - start in loop mode: wait - mount - sign - unmount - wait
  39. USAGE NOTES
  40. If invoked with no command, the program mounts the USB stick, signs any
  41. unsigned transactions, unmounts the USB stick and exits.
  42. If invoked with 'wait', the program waits in a loop, mounting, signing
  43. and unmounting every time the USB stick is inserted. The status LED
  44. indicates whether the program is busy or in standby mode, i.e. ready for
  45. USB stick insertion or removal.
  46. The USB stick must have a partition with the label MMGEN_TX and a user-
  47. writable directory '/tx', where unsigned MMGen transactions are placed.
  48. On the signing machine the directory /mnt/tx must exist and /etc/fstab must
  49. contain the following entry:
  50. LABEL='MMGEN_TX' /mnt/tx auto noauto,user 0 0
  51. The signing wallet or wallets must be in MMGen mnemonic format and
  52. present in /dev/shm. The wallet(s) can be created interactively with
  53. the following command:
  54. $ mmgen-walletconv -i words -o words -d /dev/shm
  55. {} checks that a shared secret is present on the USB stick
  56. before signing transactions. The shared secret is generated by invoking
  57. the command with 'gen_secret' with the USB stick inserted. For good
  58. security, it's advisable to re-generate a new shared secret before each
  59. signing session.
  60. Status LED functionality is supported on Orange Pi and Raspberry Pi boards.
  61. This program is a helper script and is not installed by default. You
  62. may copy it to your executable path if you wish, or just run it in place
  63. in the scripts directory of the MMGen repository root where it resides.
  64. """.format(prog_name)
  65. }
  66. cmd_args = opts.init(opts_data)
  67. if opt.stealth_led: opt.led = True
  68. mountpoint = '/mnt/tx'
  69. tx_dir = os.path.join(mountpoint,'tx')
  70. part_label = 'MMGEN_TX'
  71. shm_dir = '/dev/shm'
  72. secret_fn = 'txsign-secret'
  73. tn_arg = ([],['--testnet=1'])[bool(opt.testnet)]
  74. def check_daemon_running():
  75. try: subprocess.check_output(['mmgen-tool'] + tn_arg + ['getbalance'])
  76. except: die(1,'Daemon not running')
  77. def get_wallet_files():
  78. wfs = [f for f in os.listdir(shm_dir) if f[-8:] == '.mmwords']
  79. if not wfs:
  80. die(1,'No mnemonic files present!')
  81. return [os.path.join(shm_dir,w) for w in wfs]
  82. def get_secret_in_dir(d,on_fail='die'):
  83. try:
  84. with open(os.path.join(d,secret_fn)) as f:
  85. return f.read().rstrip()
  86. except:
  87. msg('Unable to read secret file!')
  88. if on_fail == 'die': sys.exit(1)
  89. else: return None
  90. def do_mount():
  91. if not os.path.ismount(mountpoint):
  92. msg('Mounting '+mountpoint)
  93. subprocess.call(['mount',mountpoint])
  94. try:
  95. ds = os.stat(tx_dir)
  96. assert S_ISDIR(ds.st_mode)
  97. assert ds.st_mode & S_IWUSR|S_IRUSR == S_IWUSR|S_IRUSR
  98. except:
  99. die(1,'{} missing, or not read/writable by user!'.format(tx_dir))
  100. def do_umount():
  101. if os.path.ismount(mountpoint):
  102. subprocess.call(['sync'])
  103. msg('Unmounting '+mountpoint)
  104. subprocess.call(['umount',mountpoint])
  105. def sign():
  106. dirlist = os.listdir(tx_dir)
  107. raw = [f for f in dirlist if f[-6:] == '.rawtx']
  108. signed = [f[:-6] for f in dirlist if f[-6:] == '.sigtx']
  109. unsigned = [os.path.join(tx_dir,f) for f in raw if f[:-6] not in signed]
  110. if unsigned:
  111. cmd = ['mmgen-txsign','--yes','--outdir='+tx_dir] + tn_arg + unsigned + wfs
  112. ret = subprocess.call(cmd)
  113. msg('')
  114. time.sleep(0.3)
  115. return (1,0)[ret==0]
  116. else:
  117. msg('No unsigned transactions')
  118. time.sleep(1)
  119. return 0
  120. def wipe_existing_secret_files():
  121. for d in (tx_dir,shm_dir):
  122. fn = os.path.join(d,secret_fn)
  123. try:
  124. os.stat(fn)
  125. except:
  126. pass
  127. else:
  128. msg('\nWiping existing key {}'.format(fn))
  129. subprocess.call(['wipe','-c',fn])
  130. def create_secret_files():
  131. from binascii import hexlify
  132. secret = hexlify(os.urandom(16))
  133. for d in (tx_dir,shm_dir):
  134. fn = os.path.join(d,secret_fn)
  135. desc = 'secret file in {}'.format(d)
  136. msg('Creating ' + desc)
  137. try:
  138. with open(fn,'w') as f: f.write(secret+'\n')
  139. os.chmod(fn,0400)
  140. msg('Wrote ' + desc)
  141. except:
  142. die(2,'Unable to write ' + desc)
  143. def do_create_secret_files():
  144. if not get_insert_status():
  145. die(2,'USB stick not present!')
  146. do_mount()
  147. wipe_existing_secret_files()
  148. create_secret_files()
  149. do_umount()
  150. def ev_sleep(secs):
  151. ev.wait(secs)
  152. return (False,True)[ev.isSet()]
  153. def do_led(on,off):
  154. if not on:
  155. with open(status_ctl,'w') as f: f.write('0\n')
  156. while True:
  157. if ev_sleep(3600): return
  158. while True:
  159. with open(status_ctl,'w') as f: f.write('255\n')
  160. if ev_sleep(on): return
  161. with open(status_ctl,'w') as f: f.write('0\n')
  162. if ev_sleep(off): return
  163. def set_led(cmd):
  164. if not opt.led: return
  165. timings = {
  166. 'off': ( 0, 0 ),
  167. 'standby': ( 2.2, 0.2 ),
  168. 'busy': ( 0.06, 0.06 ),
  169. 'error': ( 0.5, 0.5 )}[cmd]
  170. vmsg("Executing command '{}'".format(cmd))
  171. global led_thread
  172. if led_thread:
  173. ev.set(); led_thread.join(); ev.clear()
  174. led_thread = threading.Thread(target=do_led,name='LED loop',args=timings)
  175. led_thread.start()
  176. def do_sign():
  177. if not opt.stealth_led: set_led('busy')
  178. do_mount()
  179. ret = get_secret_in_dir(tx_dir,on_fail='return')
  180. if ret == secret:
  181. if opt.stealth_led: set_led('busy')
  182. exit_val = sign()
  183. do_umount()
  184. set_led(('standby','off','error')[bool(exit_val)*2 or bool(opt.stealth_led)])
  185. else:
  186. if ret != None:
  187. msg('Secret is incorrect!')
  188. do_umount()
  189. if not opt.stealth_led: set_led('error')
  190. def get_insert_status():
  191. try: os.stat(os.path.join('/dev/disk/by-label/',part_label))
  192. except: return False
  193. else: return True
  194. def do_loop():
  195. n,prev_status = 0,False
  196. if not opt.stealth_led:
  197. set_led('standby')
  198. while True:
  199. status = get_insert_status()
  200. if status and not prev_status:
  201. msg('Running command...')
  202. do_sign()
  203. prev_status = status
  204. if not n % 10:
  205. msg_r('\r{}\rwaiting'.format(' '*17))
  206. time.sleep(1)
  207. msg_r('.')
  208. n += 1
  209. def check_access(fn,desc='status LED control',init_val=None):
  210. try:
  211. with open(fn) as f: b = f.read().strip()
  212. with open(fn,'w') as f:
  213. f.write('{}\n'.format(init_val or b))
  214. return True
  215. except:
  216. m1 = "You do not have access to the {} file\n".format(desc)
  217. m2 = "To allow access, run 'sudo chmod 0666 {}'".format(fn)
  218. msg(m1+m2)
  219. return False
  220. def check_wipe_present():
  221. try:
  222. subprocess.Popen(['wipe','-v'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  223. except:
  224. die(2,"The 'wipe' utility must be installed before running this program")
  225. if opt.led:
  226. import threading
  227. status = {
  228. 'opi': '/sys/class/leds/orangepi:red:status/brightness',
  229. 'rpi': '/sys/class/leds/led0/brightness'
  230. }
  231. trigger = {
  232. 'rpi': '/sys/class/leds/led0/trigger', # mmc,none
  233. }
  234. for k in ('opi','rpi'):
  235. try: os.stat(status[k])
  236. except: pass
  237. else:
  238. board = k
  239. status_ctl = status[board]
  240. break
  241. else:
  242. die(2,'Control files not found! LED option not supported')
  243. if not check_access(status_ctl) or (
  244. board == 'rpi' and not check_access(trigger[board],desc='LED trigger',init_val='none')):
  245. sys.exit(1)
  246. ev = threading.Event()
  247. led_thread = None
  248. if board == 'rpi':
  249. with open(trigger[board],'w') as f: f.write('none\n')
  250. # main()
  251. if len(cmd_args) == 1 and cmd_args[0] == 'gen_secret':
  252. do_create_secret_files()
  253. sys.exit()
  254. check_wipe_present()
  255. wfs = get_wallet_files()
  256. secret = get_secret_in_dir(shm_dir,on_fail='die')
  257. check_daemon_running()
  258. def at_exit(nl=True):
  259. if opt.led:
  260. set_led('off')
  261. ev.set()
  262. led_thread.join()
  263. if board == 'rpi':
  264. with open(trigger[board],'w') as f: f.write('mmc0\n')
  265. if nl: msg('')
  266. raise SystemExit
  267. def handler(a,b): at_exit()
  268. signal.signal(signal.SIGTERM,handler)
  269. signal.signal(signal.SIGINT,handler)
  270. try:
  271. if len(cmd_args) == 1 and cmd_args[0] == 'wait':
  272. do_loop()
  273. elif len(cmd_args) == 0:
  274. do_sign()
  275. at_exit(nl=False)
  276. else:
  277. msg('Invalid invocation')
  278. except IOError:
  279. at_exit()
  280. except KeyboardInterrupt:
  281. at_exit()