acme.sh 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  1. #!/usr/bin/env sh
  2. VER=2.2.2
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [ -z "$AGREEMENT" ] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _URGLY_PRINTF=""
  20. if [ "$(printf '\x41')" != 'A' ] ; then
  21. _URGLY_PRINTF=1
  22. fi
  23. _info() {
  24. if [ -z "$2" ] ; then
  25. echo "[$(date)] $1"
  26. else
  27. echo "[$(date)] $1"="'$2'"
  28. fi
  29. }
  30. _err() {
  31. _info "$@" >&2
  32. return 1
  33. }
  34. _debug() {
  35. if [ -z "$DEBUG" ] ; then
  36. return
  37. fi
  38. _err "$@"
  39. return 0
  40. }
  41. _debug2() {
  42. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  43. _debug "$@"
  44. fi
  45. return
  46. }
  47. _startswith(){
  48. _str="$1"
  49. _sub="$2"
  50. echo $_str | grep ^$_sub >/dev/null 2>&1
  51. }
  52. _contains(){
  53. _str="$1"
  54. _sub="$2"
  55. echo $_str | grep $_sub >/dev/null 2>&1
  56. }
  57. _exists(){
  58. cmd="$1"
  59. if [ -z "$cmd" ] ; then
  60. _err "Usage: _exists cmd"
  61. return 1
  62. fi
  63. if type command >/dev/null 2>&1 ; then
  64. command -v $cmd >/dev/null 2>&1
  65. else
  66. type $cmd >/dev/null 2>&1
  67. fi
  68. ret="$?"
  69. _debug2 "$cmd exists=$ret"
  70. return $ret
  71. }
  72. #a + b
  73. _math(){
  74. expr "$@"
  75. }
  76. _h_char_2_dec() {
  77. _ch=$1
  78. case "${_ch}" in
  79. a|A)
  80. echo -n 10
  81. ;;
  82. b|B)
  83. echo -n 11
  84. ;;
  85. c|C)
  86. echo -n 12
  87. ;;
  88. d|D)
  89. echo -n 13
  90. ;;
  91. e|E)
  92. echo -n 14
  93. ;;
  94. f|F)
  95. echo -n 15
  96. ;;
  97. *)
  98. echo -n $_ch
  99. ;;
  100. esac
  101. }
  102. _h2b() {
  103. hex=$(cat)
  104. i=1
  105. j=2
  106. if _exists let ; then
  107. uselet="1"
  108. fi
  109. _debug uselet "$uselet"
  110. _debug _URGLY_PRINTF "$_URGLY_PRINTF"
  111. while [ '1' ] ; do
  112. if [ -z "$_URGLY_PRINTF" ] ; then
  113. h=$(printf $hex | cut -c $i-$j)
  114. if [ -z "$h" ] ; then
  115. break;
  116. fi
  117. printf "\x$h"
  118. else
  119. ic=$(printf $hex | cut -c $i)
  120. jc=$(printf $hex | cut -c $j)
  121. if [ -z "$ic$jc" ] ; then
  122. break;
  123. fi
  124. ic="$(_h_char_2_dec $ic)"
  125. jc="$(_h_char_2_dec $jc)"
  126. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  127. fi
  128. if [ "$uselet" ] ; then
  129. let "i+=2" >/dev/null
  130. let "j+=2" >/dev/null
  131. else
  132. i="$(_math $i + 2)"
  133. j="$(_math $j + 2)"
  134. fi
  135. done
  136. }
  137. #options file
  138. _sed_i() {
  139. options="$1"
  140. filename="$2"
  141. if [ -z "$filename" ] ; then
  142. _err "Usage:_sed_i options filename"
  143. return 1
  144. fi
  145. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  146. _debug "Using sed -i"
  147. sed -i ""
  148. else
  149. _debug "No -i support in sed"
  150. text="$(cat $filename)"
  151. echo "$text" | sed "$options" > "$filename"
  152. fi
  153. }
  154. #Usage: file startline endline
  155. _getfile() {
  156. filename="$1"
  157. startline="$2"
  158. endline="$3"
  159. if [ -z "$endline" ] ; then
  160. _err "Usage: file startline endline"
  161. return 1
  162. fi
  163. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  164. if [ -z "$i" ] ; then
  165. _err "Can not find start line: $startline"
  166. return 1
  167. fi
  168. i="$(_math $i + 1)"
  169. _debug i $i
  170. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  171. if [ -z "$j" ] ; then
  172. _err "Can not find end line: $endline"
  173. return 1
  174. fi
  175. j="$(_math $j - 1)"
  176. _debug j $j
  177. sed -n $i,${j}p "$filename"
  178. }
  179. #Usage: multiline
  180. _base64() {
  181. if [ "$1" ] ; then
  182. openssl base64 -e
  183. else
  184. openssl base64 -e | tr -d '\r\n'
  185. fi
  186. }
  187. #Usage: multiline
  188. _dbase64() {
  189. if [ "$1" ] ; then
  190. openssl base64 -d -A
  191. else
  192. openssl base64 -d
  193. fi
  194. }
  195. #Usage: hashalg
  196. #Output Base64-encoded digest
  197. _digest() {
  198. alg="$1"
  199. if [ -z "$alg" ] ; then
  200. _err "Usage: _digest hashalg"
  201. return 1
  202. fi
  203. if [ "$alg" = "sha256" ] ; then
  204. openssl dgst -sha256 -binary | _base64
  205. else
  206. _err "$alg is not supported yet"
  207. return 1
  208. fi
  209. }
  210. #Usage: keyfile hashalg
  211. #Output: Base64-encoded signature value
  212. _sign() {
  213. keyfile="$1"
  214. alg="$2"
  215. if [ -z "$alg" ] ; then
  216. _err "Usage: _sign keyfile hashalg"
  217. return 1
  218. fi
  219. if [ "$alg" = "sha256" ] ; then
  220. openssl dgst -sha256 -sign "$keyfile" | _base64
  221. else
  222. _err "$alg is not supported yet"
  223. return 1
  224. fi
  225. }
  226. _ss() {
  227. _port="$1"
  228. if _exists "ss" ; then
  229. _debug "Using: ss"
  230. ss -ntpl | grep :$_port" "
  231. return 0
  232. fi
  233. if _exists "netstat" ; then
  234. _debug "Using: netstat"
  235. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  236. #for windows version netstat tool
  237. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  238. else
  239. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  240. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  241. else
  242. netstat -ntpl | grep :$_port" "
  243. fi
  244. fi
  245. return 0
  246. fi
  247. return 1
  248. }
  249. toPkcs() {
  250. domain="$1"
  251. pfxPassword="$2"
  252. if [ -z "$domain" ] ; then
  253. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  254. return 1
  255. fi
  256. _initpath "$domain"
  257. if [ "$pfxPassword" ] ; then
  258. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  259. else
  260. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  261. fi
  262. if [ "$?" = "0" ] ; then
  263. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  264. fi
  265. }
  266. #domain [2048]
  267. createAccountKey() {
  268. _info "Creating account key"
  269. if [ -z "$1" ] ; then
  270. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  271. return
  272. fi
  273. account=$1
  274. length=$2
  275. _debug account "$account"
  276. _debug length "$length"
  277. if _startswith "$length" "ec-" ; then
  278. length=2048
  279. fi
  280. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  281. _info "Use default length 2048"
  282. length=2048
  283. fi
  284. _initpath
  285. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  286. _info "Account key exists, skip"
  287. return
  288. else
  289. #generate account key
  290. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  291. fi
  292. }
  293. #domain length
  294. createDomainKey() {
  295. _info "Creating domain key"
  296. if [ -z "$1" ] ; then
  297. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  298. return
  299. fi
  300. domain=$1
  301. length=$2
  302. isec=""
  303. if _startswith "$length" "ec-" ; then
  304. isec="1"
  305. length=$(printf $length | cut -d '-' -f 2-100)
  306. eccname="$length"
  307. fi
  308. if [ -z "$length" ] ; then
  309. if [ "$isec" ] ; then
  310. length=256
  311. else
  312. length=2048
  313. fi
  314. fi
  315. _info "Use length $length"
  316. if [ "$isec" ] ; then
  317. if [ "$length" = "256" ] ; then
  318. eccname="prime256v1"
  319. fi
  320. if [ "$length" = "384" ] ; then
  321. eccname="secp384r1"
  322. fi
  323. if [ "$length" = "521" ] ; then
  324. eccname="secp521r1"
  325. fi
  326. _info "Using ec name: $eccname"
  327. fi
  328. _initpath $domain
  329. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  330. #generate account key
  331. if [ "$isec" ] ; then
  332. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  333. else
  334. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  335. fi
  336. else
  337. if [ "$IS_RENEW" ] ; then
  338. _info "Domain key exists, skip"
  339. return 0
  340. else
  341. _err "Domain key exists, do you want to overwrite the key?"
  342. _err "Add '--force', and try again."
  343. return 1
  344. fi
  345. fi
  346. }
  347. # domain domainlist
  348. createCSR() {
  349. _info "Creating csr"
  350. if [ -z "$1" ] ; then
  351. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  352. return
  353. fi
  354. domain=$1
  355. _initpath $domain
  356. domainlist=$2
  357. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  358. _info "CSR exists, skip"
  359. return
  360. fi
  361. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  362. #single domain
  363. _info "Single domain" $domain
  364. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  365. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  366. else
  367. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  368. #multi
  369. _info "Multi domain" "$alt"
  370. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  371. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  372. fi
  373. }
  374. _urlencode() {
  375. __n=$(cat)
  376. echo $__n | tr '/+' '_-' | tr -d '= '
  377. }
  378. _time2str() {
  379. #BSD
  380. if date -u -d@$1 2>/dev/null ; then
  381. return
  382. fi
  383. #Linux
  384. if date -u -r $1 2>/dev/null ; then
  385. return
  386. fi
  387. }
  388. _stat() {
  389. #Linux
  390. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  391. return
  392. fi
  393. #BSD
  394. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  395. return
  396. fi
  397. }
  398. #keyfile
  399. _calcjwk() {
  400. keyfile="$1"
  401. if [ -z "$keyfile" ] ; then
  402. _err "Usage: _calcjwk keyfile"
  403. return 1
  404. fi
  405. EC_SIGN=""
  406. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  407. _debug "RSA key"
  408. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  409. if [ "${#pub_exp}" = "5" ] ; then
  410. pub_exp=0$pub_exp
  411. fi
  412. _debug2 pub_exp "$pub_exp"
  413. e=$(echo $pub_exp | _h2b | _base64)
  414. _debug2 e "$e"
  415. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  416. _debug2 modulus "$modulus"
  417. n=$(echo -n $modulus| _h2b | _base64 | _urlencode )
  418. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  419. _debug2 jwk "$jwk"
  420. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  421. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  422. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  423. _debug "EC key"
  424. EC_SIGN="1"
  425. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  426. _debug2 crv $crv
  427. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  428. pubi=$(_math $pubi + 1)
  429. _debug2 pubi $pubi
  430. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  431. pubj=$(_math $pubj + 1)
  432. _debug2 pubj $pubj
  433. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  434. _debug2 pubtext "$pubtext"
  435. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  436. xlen=$(_math $xlen / 4)
  437. _debug2 xlen $xlen
  438. xend=$(_math $xend + 1)
  439. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  440. _debug2 x $x
  441. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  442. _debug2 x64 $x64
  443. xend=$(_math $xend + 1)
  444. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  445. _debug2 y $y
  446. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  447. _debug2 y64 $y64
  448. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  449. _debug2 jwk "$jwk"
  450. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  451. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  452. else
  453. _err "Only RSA or EC key is supported."
  454. return 1
  455. fi
  456. _debug2 HEADER "$HEADER"
  457. }
  458. # body url [needbase64]
  459. _post() {
  460. body="$1"
  461. url="$2"
  462. needbase64="$3"
  463. if _exists "curl" ; then
  464. CURL="$CURL --dump-header $HTTP_HEADER "
  465. if [ "$needbase64" ] ; then
  466. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  467. else
  468. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  469. fi
  470. else
  471. if [ "$needbase64" ] ; then
  472. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  473. else
  474. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  475. fi
  476. _sed_i "s/^ *//g" "$HTTP_HEADER"
  477. fi
  478. echo -n "$response"
  479. }
  480. # url getheader
  481. _get() {
  482. url="$1"
  483. onlyheader="$2"
  484. _debug url $url
  485. if _exists "curl" ; then
  486. if [ "$onlyheader" ] ; then
  487. $CURL -I -A "User-Agent: $USER_AGENT" $url
  488. else
  489. $CURL -A "User-Agent: $USER_AGENT" $url
  490. fi
  491. else
  492. _debug "WGET" "$WGET"
  493. if [ "$onlyheader" ] ; then
  494. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  495. else
  496. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  497. fi
  498. fi
  499. ret=$?
  500. return $ret
  501. }
  502. # url payload needbase64 keyfile
  503. _send_signed_request() {
  504. url=$1
  505. payload=$2
  506. needbase64=$3
  507. keyfile=$4
  508. if [ -z "$keyfile" ] ; then
  509. keyfile="$ACCOUNT_KEY_PATH"
  510. fi
  511. _debug url $url
  512. _debug payload "$payload"
  513. if ! _calcjwk "$keyfile" ; then
  514. return 1
  515. fi
  516. payload64=$(echo -n $payload | _base64 | _urlencode)
  517. _debug2 payload64 $payload64
  518. nonceurl="$API/directory"
  519. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  520. _debug nonce "$nonce"
  521. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  522. _debug2 protected "$protected"
  523. protected64="$(printf "$protected" | _base64 | _urlencode)"
  524. _debug2 protected64 "$protected64"
  525. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  526. _debug2 sig "$sig"
  527. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  528. _debug2 body "$body"
  529. response="$(_post "$body" $url "$needbase64" )"
  530. responseHeaders="$(cat $HTTP_HEADER)"
  531. _debug2 responseHeaders "$responseHeaders"
  532. _debug2 response "$response"
  533. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  534. _debug code $code
  535. }
  536. #setopt "file" "opt" "=" "value" [";"]
  537. _setopt() {
  538. __conf="$1"
  539. __opt="$2"
  540. __sep="$3"
  541. __val="$4"
  542. __end="$5"
  543. if [ -z "$__opt" ] ; then
  544. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  545. return
  546. fi
  547. if [ ! -f "$__conf" ] ; then
  548. touch "$__conf"
  549. fi
  550. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  551. _debug2 OK
  552. if _contains "$__val" "&" ; then
  553. __val="$(echo $__val | sed 's/&/\\&/g')"
  554. fi
  555. text="$(cat $__conf)"
  556. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  557. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  558. if _contains "$__val" "&" ; then
  559. __val="$(echo $__val | sed 's/&/\\&/g')"
  560. fi
  561. text="$(cat $__conf)"
  562. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  563. else
  564. _debug2 APP
  565. echo "$__opt$__sep$__val$__end" >> "$__conf"
  566. fi
  567. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  568. }
  569. #_savedomainconf key value
  570. #save to domain.conf
  571. _savedomainconf() {
  572. key="$1"
  573. value="$2"
  574. if [ "$DOMAIN_CONF" ] ; then
  575. _setopt $DOMAIN_CONF "$key" "=" "$value"
  576. else
  577. _err "DOMAIN_CONF is empty, can not save $key=$value"
  578. fi
  579. }
  580. #_saveaccountconf key value
  581. _saveaccountconf() {
  582. key="$1"
  583. value="$2"
  584. if [ "$ACCOUNT_CONF_PATH" ] ; then
  585. _setopt $ACCOUNT_CONF_PATH "$key" "=" "\"$value\""
  586. else
  587. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  588. fi
  589. }
  590. _startserver() {
  591. content="$1"
  592. _debug "startserver: $$"
  593. nchelp="$(nc -h 2>&1)"
  594. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  595. _NC="nc -q 1 -l"
  596. else
  597. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  598. _NC="nc -c -l"
  599. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  600. _NC="nc -N -l"
  601. else
  602. _NC="nc -l"
  603. fi
  604. fi
  605. _debug "_NC" "$_NC"
  606. # while true ; do
  607. if [ "$DEBUG" ] ; then
  608. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  609. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  610. fi
  611. else
  612. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  613. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  614. fi
  615. fi
  616. if [ "$?" != "0" ] ; then
  617. _err "nc listen error."
  618. exit 1
  619. fi
  620. # done
  621. }
  622. _stopserver(){
  623. pid="$1"
  624. _debug "pid" "$pid"
  625. if [ -z "$pid" ] ; then
  626. return
  627. fi
  628. if [ "$(ps | grep "$pid")" ] ; then
  629. _debug "Found proc process, kill it."
  630. kill -s 9 $pid > /dev/null
  631. fi
  632. for ncid in $(echo $(ps | grep nc) | cut -d " " -f 1) ; do
  633. _debug "kill $ncid"
  634. kill -s 9 $ncid > /dev/null
  635. done
  636. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  637. }
  638. _initpath() {
  639. if [ -z "$LE_WORKING_DIR" ] ; then
  640. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  641. fi
  642. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  643. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  644. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  645. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  646. fi
  647. fi
  648. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  649. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  650. fi
  651. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  652. . "$ACCOUNT_CONF_PATH"
  653. fi
  654. if [ "$IN_CRON" ] ; then
  655. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  656. _USER_PATH_EXPORTED=1
  657. export PATH="$USER_PATH:$PATH"
  658. fi
  659. fi
  660. if [ -z "$API" ] ; then
  661. if [ -z "$STAGE" ] ; then
  662. API="$DEFAULT_CA"
  663. else
  664. API="$STAGE_CA"
  665. _info "Using stage api:$API"
  666. fi
  667. fi
  668. if [ -z "$ACME_DIR" ] ; then
  669. ACME_DIR="/home/.acme"
  670. fi
  671. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  672. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  673. fi
  674. if [ -z "$USER_AGENT" ] ; then
  675. USER_AGENT="$DEFAULT_USER_AGENT"
  676. fi
  677. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  678. WGET="wget -q"
  679. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  680. WGET="$WGET -d "
  681. fi
  682. dp="$LE_WORKING_DIR/curl.dump"
  683. CURL="curl -L --silent"
  684. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  685. CURL="$CURL -L --trace-ascii $dp "
  686. fi
  687. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  688. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  689. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  690. fi
  691. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  692. if [ -z "$CERT_HOME" ] ; then
  693. CERT_HOME="$_DEFAULT_CERT_HOME"
  694. fi
  695. domain="$1"
  696. if [ -z "$domain" ] ; then
  697. return 0
  698. fi
  699. domainhome="$CERT_HOME/$domain"
  700. mkdir -p "$domainhome"
  701. if [ -z "$DOMAIN_PATH" ] ; then
  702. DOMAIN_PATH="$domainhome"
  703. fi
  704. if [ -z "$DOMAIN_CONF" ] ; then
  705. DOMAIN_CONF="$domainhome/$domain.conf"
  706. fi
  707. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  708. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  709. fi
  710. if [ -z "$CSR_PATH" ] ; then
  711. CSR_PATH="$domainhome/$domain.csr"
  712. fi
  713. if [ -z "$CERT_KEY_PATH" ] ; then
  714. CERT_KEY_PATH="$domainhome/$domain.key"
  715. fi
  716. if [ -z "$CERT_PATH" ] ; then
  717. CERT_PATH="$domainhome/$domain.cer"
  718. fi
  719. if [ -z "$CA_CERT_PATH" ] ; then
  720. CA_CERT_PATH="$domainhome/ca.cer"
  721. fi
  722. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  723. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  724. fi
  725. if [ -z "$CERT_PFX_PATH" ] ; then
  726. CERT_PFX_PATH="$domainhome/$domain.pfx"
  727. fi
  728. }
  729. _apachePath() {
  730. if ! _exists apachectl ; then
  731. _err "'apachecrl not found. It seems that apache is not installed, or you are not root user.'"
  732. _err "Please use webroot mode to try again."
  733. return 1
  734. fi
  735. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  736. if _startswith "$httpdconfname" '/' ; then
  737. httpdconf="$httpdconfname"
  738. httpdconfname="$(basename $httpdconfname)"
  739. else
  740. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  741. httpdconf="$httpdroot/$httpdconfname"
  742. fi
  743. if [ ! -f $httpdconf ] ; then
  744. _err "Apache Config file not found" $httpdconf
  745. return 1
  746. fi
  747. return 0
  748. }
  749. _restoreApache() {
  750. if [ -z "$usingApache" ] ; then
  751. return 0
  752. fi
  753. _initpath
  754. if ! _apachePath ; then
  755. return 1
  756. fi
  757. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  758. _debug "No config file to restore."
  759. return 0
  760. fi
  761. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  762. _debug "Restored: $httpdconf."
  763. if ! apachectl -t ; then
  764. _err "Sorry, restore apache config error, please contact me."
  765. return 1;
  766. fi
  767. _debug "Restored successfully."
  768. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  769. return 0
  770. }
  771. _setApache() {
  772. _initpath
  773. if ! _apachePath ; then
  774. return 1
  775. fi
  776. #backup the conf
  777. _debug "Backup apache config file" $httpdconf
  778. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  779. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  780. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  781. _info "The backup file will be deleted on sucess, just forget it."
  782. #add alias
  783. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  784. _debug "apacheVer" "$apacheVer"
  785. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  786. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  787. if [ "$apacheVer" ] && [ "$apacheMajer" -ge "2" ] && [ "$apacheMinor" -ge "4" ] ; then
  788. echo "
  789. Alias /.well-known/acme-challenge $ACME_DIR
  790. <Directory $ACME_DIR >
  791. Require all granted
  792. </Directory>
  793. " >> $httpdconf
  794. else
  795. echo "
  796. Alias /.well-known/acme-challenge $ACME_DIR
  797. <Directory $ACME_DIR >
  798. Order allow,deny
  799. Allow from all
  800. </Directory>
  801. " >> $httpdconf
  802. fi
  803. if ! apachectl -t ; then
  804. _err "Sorry, apache config error, please contact me."
  805. _restoreApache
  806. return 1;
  807. fi
  808. if [ ! -d "$ACME_DIR" ] ; then
  809. mkdir -p "$ACME_DIR"
  810. chmod 755 "$ACME_DIR"
  811. fi
  812. if ! apachectl graceful ; then
  813. _err "Sorry, apachectl graceful error, please contact me."
  814. _restoreApache
  815. return 1;
  816. fi
  817. usingApache="1"
  818. return 0
  819. }
  820. _clearup() {
  821. _stopserver $serverproc
  822. serverproc=""
  823. _restoreApache
  824. }
  825. # webroot removelevel tokenfile
  826. _clearupwebbroot() {
  827. __webroot="$1"
  828. if [ -z "$__webroot" ] ; then
  829. _debug "no webroot specified, skip"
  830. return 0
  831. fi
  832. if [ "$2" = '1' ] ; then
  833. _debug "remove $__webroot/.well-known"
  834. rm -rf "$__webroot/.well-known"
  835. elif [ "$2" = '2' ] ; then
  836. _debug "remove $__webroot/.well-known/acme-challenge"
  837. rm -rf "$__webroot/.well-known/acme-challenge"
  838. elif [ "$2" = '3' ] ; then
  839. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  840. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  841. else
  842. _info "Skip for removelevel:$2"
  843. fi
  844. return 0
  845. }
  846. issue() {
  847. if [ -z "$2" ] ; then
  848. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  849. return 1
  850. fi
  851. Le_Webroot="$1"
  852. Le_Domain="$2"
  853. Le_Alt="$3"
  854. Le_Keylength="$4"
  855. Le_RealCertPath="$5"
  856. Le_RealKeyPath="$6"
  857. Le_RealCACertPath="$7"
  858. Le_ReloadCmd="$8"
  859. Le_RealFullChainPath="$9"
  860. #remove these later.
  861. if [ "$Le_Webroot" = "dns-cf" ] ; then
  862. Le_Webroot="dns_cf"
  863. fi
  864. if [ "$Le_Webroot" = "dns-dp" ] ; then
  865. Le_Webroot="dns_dp"
  866. fi
  867. if [ "$Le_Webroot" = "dns-cx" ] ; then
  868. Le_Webroot="dns_cx"
  869. fi
  870. _initpath $Le_Domain
  871. if [ -f "$DOMAIN_CONF" ] ; then
  872. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  873. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  874. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  875. return 2
  876. fi
  877. fi
  878. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  879. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  880. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  881. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  882. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  883. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  884. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  885. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  886. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  887. if [ "$Le_Alt" = "no" ] ; then
  888. Le_Alt=""
  889. fi
  890. if [ "$Le_Keylength" = "no" ] ; then
  891. Le_Keylength=""
  892. fi
  893. if [ "$Le_RealCertPath" = "no" ] ; then
  894. Le_RealCertPath=""
  895. fi
  896. if [ "$Le_RealKeyPath" = "no" ] ; then
  897. Le_RealKeyPath=""
  898. fi
  899. if [ "$Le_RealCACertPath" = "no" ] ; then
  900. Le_RealCACertPath=""
  901. fi
  902. if [ "$Le_ReloadCmd" = "no" ] ; then
  903. Le_ReloadCmd=""
  904. fi
  905. if [ "$Le_RealFullChainPath" = "no" ] ; then
  906. Le_RealFullChainPath=""
  907. fi
  908. if _contains "$Le_Webroot" "no" ; then
  909. _info "Standalone mode."
  910. if ! _exists "nc" ; then
  911. _err "Please install netcat(nc) tools first."
  912. return 1
  913. fi
  914. if [ -z "$Le_HTTPPort" ] ; then
  915. Le_HTTPPort=80
  916. fi
  917. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  918. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  919. if [ "$netprc" ] ; then
  920. _err "$netprc"
  921. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  922. _err "Please stop it first"
  923. return 1
  924. fi
  925. fi
  926. if _contains "$Le_Webroot" "apache" ; then
  927. if ! _setApache ; then
  928. _err "set up apache error. Report error to me."
  929. return 1
  930. fi
  931. else
  932. usingApache=""
  933. fi
  934. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  935. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  936. _err "Create account key error."
  937. if [ "$usingApache" ] ; then
  938. _restoreApache
  939. fi
  940. return 1
  941. fi
  942. fi
  943. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  944. if [ "$usingApache" ] ; then
  945. _restoreApache
  946. fi
  947. return 1
  948. fi
  949. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  950. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  951. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  952. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  953. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  954. _info "Registering account"
  955. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  956. if [ "$ACCOUNT_EMAIL" ] ; then
  957. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  958. fi
  959. _send_signed_request "$API/acme/new-reg" "$regjson"
  960. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  961. _info "Registered"
  962. echo $response > $LE_WORKING_DIR/account.json
  963. elif [ "$code" = '409' ] ; then
  964. _info "Already registered"
  965. else
  966. _err "Register account Error: $response"
  967. _clearup
  968. return 1
  969. fi
  970. ACCOUNT_KEY_HASH="$accountkeyhash"
  971. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  972. else
  973. _info "Skip register account key"
  974. fi
  975. if [ ! -f "$CERT_KEY_PATH" ] ; then
  976. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  977. _err "Create domain key error."
  978. _clearup
  979. return 1
  980. fi
  981. fi
  982. if ! createCSR $Le_Domain $Le_Alt ; then
  983. _err "Create CSR error."
  984. _clearup
  985. return 1
  986. fi
  987. vlist="$Le_Vlist"
  988. # verify each domain
  989. _info "Verify each domain"
  990. sep='#'
  991. if [ -z "$vlist" ] ; then
  992. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  993. _index=1
  994. _currentRoot=""
  995. for d in $alldomains
  996. do
  997. _info "Getting webroot for domain" $d
  998. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  999. _debug _w "$_w"
  1000. if [ "$_w" ] ; then
  1001. _currentRoot="$_w"
  1002. fi
  1003. _debug "_currentRoot" "$_currentRoot"
  1004. _index=$(_math $_index + 1)
  1005. vtype="$VTYPE_HTTP"
  1006. if _startswith "$_currentRoot" "dns" ; then
  1007. vtype="$VTYPE_DNS"
  1008. fi
  1009. _info "Getting token for domain" $d
  1010. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  1011. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1012. _err "new-authz error: $response"
  1013. _clearup
  1014. return 1
  1015. fi
  1016. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  1017. _debug entry "$entry"
  1018. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1019. _debug token $token
  1020. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1021. _debug uri $uri
  1022. keyauthorization="$token.$thumbprint"
  1023. _debug keyauthorization "$keyauthorization"
  1024. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1025. _debug dvlist "$dvlist"
  1026. vlist="$vlist$dvlist,"
  1027. done
  1028. #add entry
  1029. dnsadded=""
  1030. ventries=$(echo "$vlist" | tr ',' ' ' )
  1031. for ventry in $ventries
  1032. do
  1033. d=$(echo $ventry | cut -d $sep -f 1)
  1034. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1035. vtype=$(echo $ventry | cut -d $sep -f 4)
  1036. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1037. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1038. dnsadded='0'
  1039. txtdomain="_acme-challenge.$d"
  1040. _debug txtdomain "$txtdomain"
  1041. txt="$(echo -n $keyauthorization | _digest "sha256" | _urlencode)"
  1042. _debug txt "$txt"
  1043. #dns
  1044. #1. check use api
  1045. d_api=""
  1046. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1047. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1048. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1049. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1050. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1051. d_api="$LE_WORKING_DIR/$_currentRoot"
  1052. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1053. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1054. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1055. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1056. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1057. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1058. fi
  1059. _debug d_api "$d_api"
  1060. if [ "$d_api" ] ; then
  1061. _info "Found domain api file: $d_api"
  1062. else
  1063. _err "Add the following TXT record:"
  1064. _err "Domain: $txtdomain"
  1065. _err "TXT value: $txt"
  1066. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1067. _err "so the resulting subdomain will be: $txtdomain"
  1068. continue
  1069. fi
  1070. (
  1071. if ! . $d_api ; then
  1072. _err "Load file $d_api error. Please check your api file and try again."
  1073. return 1
  1074. fi
  1075. addcommand="${_currentRoot}_add"
  1076. if ! _exists $addcommand ; then
  1077. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1078. return 1
  1079. fi
  1080. if ! $addcommand $txtdomain $txt ; then
  1081. _err "Error add txt for domain:$txtdomain"
  1082. return 1
  1083. fi
  1084. )
  1085. if [ "$?" != "0" ] ; then
  1086. _clearup
  1087. return 1
  1088. fi
  1089. dnsadded='1'
  1090. fi
  1091. done
  1092. if [ "$dnsadded" = '0' ] ; then
  1093. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  1094. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1095. _err "Please add the TXT records to the domains, and retry again."
  1096. _clearup
  1097. return 1
  1098. fi
  1099. fi
  1100. if [ "$dnsadded" = '1' ] ; then
  1101. _info "Sleep 60 seconds for the txt records to take effect"
  1102. sleep 60
  1103. fi
  1104. _debug "ok, let's start to verify"
  1105. ventries=$(echo "$vlist" | tr ',' ' ' )
  1106. for ventry in $ventries
  1107. do
  1108. d=$(echo $ventry | cut -d $sep -f 1)
  1109. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1110. uri=$(echo $ventry | cut -d $sep -f 3)
  1111. vtype=$(echo $ventry | cut -d $sep -f 4)
  1112. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1113. _info "Verifying:$d"
  1114. _debug "d" "$d"
  1115. _debug "keyauthorization" "$keyauthorization"
  1116. _debug "uri" "$uri"
  1117. removelevel=""
  1118. token=""
  1119. _debug "_currentRoot" "$_currentRoot"
  1120. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1121. if [ "$_currentRoot" = "no" ] ; then
  1122. _info "Standalone mode server"
  1123. _startserver "$keyauthorization" &
  1124. if [ "$?" != "0" ] ; then
  1125. _clearup
  1126. return 1
  1127. fi
  1128. serverproc="$!"
  1129. sleep 2
  1130. _debug serverproc $serverproc
  1131. else
  1132. if [ "$_currentRoot" = "apache" ] ; then
  1133. wellknown_path="$ACME_DIR"
  1134. else
  1135. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1136. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1137. removelevel='1'
  1138. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1139. removelevel='2'
  1140. else
  1141. removelevel='3'
  1142. fi
  1143. fi
  1144. _debug wellknown_path "$wellknown_path"
  1145. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  1146. _debug "writing token:$token to $wellknown_path/$token"
  1147. mkdir -p "$wellknown_path"
  1148. echo -n "$keyauthorization" > "$wellknown_path/$token"
  1149. if [ ! "$usingApache" ] ; then
  1150. webroot_owner=$(_stat $_currentRoot)
  1151. _debug "Changing owner/group of .well-known to $webroot_owner"
  1152. chown -R $webroot_owner "$_currentRoot/.well-known"
  1153. fi
  1154. fi
  1155. fi
  1156. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1157. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1158. _err "$d:Challenge error: $response"
  1159. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1160. _clearup
  1161. return 1
  1162. fi
  1163. waittimes=0
  1164. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1165. MAX_RETRY_TIMES=30
  1166. fi
  1167. while [ "1" ] ; do
  1168. waittimes=$(_math $waittimes + 1)
  1169. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1170. _err "$d:Timeout"
  1171. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1172. _clearup
  1173. return 1
  1174. fi
  1175. _debug "sleep 5 secs to verify"
  1176. sleep 5
  1177. _debug "checking"
  1178. response="$(_get $uri)"
  1179. if [ "$?" != "0" ] ; then
  1180. _err "$d:Verify error:$response"
  1181. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1182. _clearup
  1183. return 1
  1184. fi
  1185. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1186. if [ "$status" = "valid" ] ; then
  1187. _info "Success"
  1188. _stopserver $serverproc
  1189. serverproc=""
  1190. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1191. break;
  1192. fi
  1193. if [ "$status" = "invalid" ] ; then
  1194. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1195. _err "$d:Verify error:$error"
  1196. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1197. _clearup
  1198. return 1;
  1199. fi
  1200. if [ "$status" = "pending" ] ; then
  1201. _info "Pending"
  1202. else
  1203. _err "$d:Verify error:$response"
  1204. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1205. _clearup
  1206. return 1
  1207. fi
  1208. done
  1209. done
  1210. _clearup
  1211. _info "Verify finished, start to sign."
  1212. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1213. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1214. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1215. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1216. if [ "$Le_LinkCert" ] ; then
  1217. echo "$BEGIN_CERT" > "$CERT_PATH"
  1218. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1219. echo "$END_CERT" >> "$CERT_PATH"
  1220. _info "Cert success."
  1221. cat "$CERT_PATH"
  1222. _info "Your cert is in $CERT_PATH"
  1223. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1224. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1225. USER_PATH="$PATH"
  1226. _saveaccountconf "USER_PATH" "$USER_PATH"
  1227. fi
  1228. fi
  1229. if [ -z "$Le_LinkCert" ] ; then
  1230. response="$(echo $response | _dbase64 "multiline" )"
  1231. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1232. return 1
  1233. fi
  1234. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1235. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1236. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1237. if [ "$Le_LinkIssuer" ] ; then
  1238. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1239. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1240. echo "$END_CERT" >> "$CA_CERT_PATH"
  1241. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1242. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1243. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1244. fi
  1245. Le_CertCreateTime=$(date -u "+%s")
  1246. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1247. Le_CertCreateTimeStr=$(date -u )
  1248. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1249. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "80" ] ; then
  1250. Le_RenewalDays=80
  1251. fi
  1252. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1253. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1254. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1255. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1256. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1257. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1258. }
  1259. renew() {
  1260. Le_Domain="$1"
  1261. if [ -z "$Le_Domain" ] ; then
  1262. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1263. return 1
  1264. fi
  1265. _initpath $Le_Domain
  1266. if [ ! -f "$DOMAIN_CONF" ] ; then
  1267. _info "$Le_Domain is not a issued domain, skip."
  1268. return 0;
  1269. fi
  1270. . "$DOMAIN_CONF"
  1271. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1272. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1273. return 2
  1274. fi
  1275. IS_RENEW="1"
  1276. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1277. local res=$?
  1278. IS_RENEW=""
  1279. return $res
  1280. }
  1281. renewAll() {
  1282. _initpath
  1283. _info "renewAll"
  1284. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1285. d=$(echo $d | cut -d '/' -f 1)
  1286. _info "renew $d"
  1287. Le_LinkCert=""
  1288. Le_Domain=""
  1289. Le_Alt="no"
  1290. Le_Webroot=""
  1291. Le_Keylength=""
  1292. Le_LinkIssuer=""
  1293. Le_CertCreateTime=""
  1294. Le_CertCreateTimeStr=""
  1295. Le_RenewalDays=""
  1296. Le_NextRenewTime=""
  1297. Le_NextRenewTimeStr=""
  1298. Le_RealCertPath=""
  1299. Le_RealKeyPath=""
  1300. Le_RealCACertPath=""
  1301. Le_ReloadCmd=""
  1302. Le_RealFullChainPath=""
  1303. DOMAIN_PATH=""
  1304. DOMAIN_CONF=""
  1305. DOMAIN_SSL_CONF=""
  1306. CSR_PATH=""
  1307. CERT_KEY_PATH=""
  1308. CERT_PATH=""
  1309. CA_CERT_PATH=""
  1310. CERT_PFX_PATH=""
  1311. CERT_FULLCHAIN_PATH=""
  1312. ACCOUNT_KEY_PATH=""
  1313. wellknown_path=""
  1314. renew "$d"
  1315. done
  1316. }
  1317. installcert() {
  1318. Le_Domain="$1"
  1319. if [ -z "$Le_Domain" ] ; then
  1320. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1321. return 1
  1322. fi
  1323. Le_RealCertPath="$2"
  1324. Le_RealKeyPath="$3"
  1325. Le_RealCACertPath="$4"
  1326. Le_ReloadCmd="$5"
  1327. Le_RealFullChainPath="$6"
  1328. _initpath $Le_Domain
  1329. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1330. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1331. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1332. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1333. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  1334. if [ "$Le_RealCertPath" ] ; then
  1335. if [ -f "$Le_RealCertPath" ] ; then
  1336. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1337. fi
  1338. cat "$CERT_PATH" > "$Le_RealCertPath"
  1339. fi
  1340. if [ "$Le_RealCACertPath" ] ; then
  1341. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1342. echo "" >> "$Le_RealCACertPath"
  1343. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1344. else
  1345. if [ -f "$Le_RealCACertPath" ] ; then
  1346. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1347. fi
  1348. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1349. fi
  1350. fi
  1351. if [ "$Le_RealKeyPath" ] ; then
  1352. if [ -f "$Le_RealKeyPath" ] ; then
  1353. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1354. fi
  1355. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1356. fi
  1357. if [ "$Le_RealFullChainPath" ] ; then
  1358. if [ -f "$Le_RealFullChainPath" ] ; then
  1359. cp -p "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1360. fi
  1361. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1362. fi
  1363. if [ "$Le_ReloadCmd" ] ; then
  1364. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1365. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1366. fi
  1367. }
  1368. installcronjob() {
  1369. _initpath
  1370. if ! _exists "crontab" ; then
  1371. _err "crontab doesn't exist, so, we can not install cron jobs."
  1372. _err "All your certs will not be renewed automatically."
  1373. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1374. return 1
  1375. fi
  1376. _info "Installing cron job"
  1377. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1378. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1379. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1380. else
  1381. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1382. return 1
  1383. fi
  1384. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1385. fi
  1386. if [ "$?" != "0" ] ; then
  1387. _err "Install cron job failed. You need to manually renew your certs."
  1388. _err "Or you can add cronjob by yourself:"
  1389. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1390. return 1
  1391. fi
  1392. }
  1393. uninstallcronjob() {
  1394. if ! _exists "crontab" ; then
  1395. return
  1396. fi
  1397. _info "Removing cron job"
  1398. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1399. if [ "$cr" ] ; then
  1400. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1401. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1402. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1403. fi
  1404. _initpath
  1405. }
  1406. revoke() {
  1407. Le_Domain="$1"
  1408. if [ -z "$Le_Domain" ] ; then
  1409. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1410. return 1
  1411. fi
  1412. _initpath $Le_Domain
  1413. if [ ! -f "$DOMAIN_CONF" ] ; then
  1414. _err "$Le_Domain is not a issued domain, skip."
  1415. return 1;
  1416. fi
  1417. if [ ! -f "$CERT_PATH" ] ; then
  1418. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1419. return 1
  1420. fi
  1421. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1422. if [ -z "$cert" ] ; then
  1423. _err "Cert for $Le_Domain is empty found, skip."
  1424. return 1
  1425. fi
  1426. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1427. uri="$API/acme/revoke-cert"
  1428. _info "Try domain key first."
  1429. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1430. if [ -z "$response" ] ; then
  1431. _info "Revoke success."
  1432. rm -f $CERT_PATH
  1433. return 0
  1434. else
  1435. _err "Revoke error by domain key."
  1436. _err "$resource"
  1437. fi
  1438. fi
  1439. _info "Then try account key."
  1440. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1441. if [ -z "$response" ] ; then
  1442. _info "Revoke success."
  1443. rm -f $CERT_PATH
  1444. return 0
  1445. else
  1446. _err "Revoke error."
  1447. _debug "$resource"
  1448. fi
  1449. fi
  1450. return 1
  1451. }
  1452. # Detect profile file if not specified as environment variable
  1453. _detect_profile() {
  1454. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1455. echo "$PROFILE"
  1456. return
  1457. fi
  1458. local DETECTED_PROFILE
  1459. DETECTED_PROFILE=''
  1460. local SHELLTYPE
  1461. SHELLTYPE="$(basename "/$SHELL")"
  1462. if [ "$SHELLTYPE" = "bash" ] ; then
  1463. if [ -f "$HOME/.bashrc" ] ; then
  1464. DETECTED_PROFILE="$HOME/.bashrc"
  1465. elif [ -f "$HOME/.bash_profile" ] ; then
  1466. DETECTED_PROFILE="$HOME/.bash_profile"
  1467. fi
  1468. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1469. DETECTED_PROFILE="$HOME/.zshrc"
  1470. fi
  1471. if [ -z "$DETECTED_PROFILE" ] ; then
  1472. if [ -f "$HOME/.profile" ] ; then
  1473. DETECTED_PROFILE="$HOME/.profile"
  1474. elif [ -f "$HOME/.bashrc" ] ; then
  1475. DETECTED_PROFILE="$HOME/.bashrc"
  1476. elif [ -f "$HOME/.bash_profile" ] ; then
  1477. DETECTED_PROFILE="$HOME/.bash_profile"
  1478. elif [ -f "$HOME/.zshrc" ] ; then
  1479. DETECTED_PROFILE="$HOME/.zshrc"
  1480. fi
  1481. fi
  1482. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1483. echo "$DETECTED_PROFILE"
  1484. fi
  1485. }
  1486. _initconf() {
  1487. _initpath
  1488. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1489. echo "#ACCOUNT_CONF_PATH=xxxx
  1490. #Account configurations:
  1491. #Here are the supported macros, uncomment them to make them take effect.
  1492. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1493. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1494. #CERT_HOME=\"/path/to/cert/home\"
  1495. #STAGE=1 # Use the staging api
  1496. #FORCE=1 # Force to issue cert
  1497. #DEBUG=1 # Debug mode
  1498. #ACCOUNT_KEY_HASH=account key hash
  1499. USER_AGENT=\"$USER_AGENT\"
  1500. #USER_PATH=""
  1501. #dns api
  1502. #######################
  1503. #Cloudflare:
  1504. #api key
  1505. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1506. #account email
  1507. #CF_Email=\"xxxx@sss.com\"
  1508. #######################
  1509. #Dnspod.cn:
  1510. #api key id
  1511. #DP_Id=\"1234\"
  1512. #api key
  1513. #DP_Key=\"sADDsdasdgdsf\"
  1514. #######################
  1515. #Cloudxns.com:
  1516. #CX_Key=\"1234\"
  1517. #
  1518. #CX_Secret=\"sADDsdasdgdsf\"
  1519. " > $ACCOUNT_CONF_PATH
  1520. fi
  1521. }
  1522. _precheck() {
  1523. if ! _exists "curl" && ! _exists "wget"; then
  1524. _err "Please install curl or wget first, we need to access http resources."
  1525. return 1
  1526. fi
  1527. if ! _exists "crontab" ; then
  1528. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1529. _err "We need to set cron job to renew the certs automatically."
  1530. _err "Otherwise, your certs will not be able to be renewed automatically."
  1531. if [ -z "$FORCE" ] ; then
  1532. _err "Please add '--force' and try install again to go without crontab."
  1533. _err "./$PROJECT_ENTRY --install --force"
  1534. return 1
  1535. fi
  1536. fi
  1537. if ! _exists "openssl" ; then
  1538. _err "Please install openssl first."
  1539. _err "We need openssl to generate keys."
  1540. return 1
  1541. fi
  1542. if ! _exists "nc" ; then
  1543. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1544. _err "We use nc for standalone server if you use standalone mode."
  1545. _err "If you don't use standalone mode, just ignore this warning."
  1546. fi
  1547. return 0
  1548. }
  1549. _setShebang() {
  1550. _file="$1"
  1551. _shebang="$2"
  1552. if [ -z "$_shebang" ] ; then
  1553. _err "Usage: file shebang"
  1554. return 1
  1555. fi
  1556. cp "$_file" "$_file.tmp"
  1557. echo "$_shebang" > "$_file"
  1558. sed -n 2,99999p "$_file.tmp" >> "$_file"
  1559. rm -f "$_file.tmp"
  1560. }
  1561. install() {
  1562. if ! _initpath ; then
  1563. _err "Install failed."
  1564. return 1
  1565. fi
  1566. if ! _precheck ; then
  1567. _err "Pre-check failed, can not install."
  1568. return 1
  1569. fi
  1570. #convert from le
  1571. if [ -d "$HOME/.le" ] ; then
  1572. for envfile in "le.env" "le.sh.env"
  1573. do
  1574. if [ -f "$HOME/.le/$envfile" ] ; then
  1575. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1576. _upgrading="1"
  1577. _info "You are upgrading from le.sh"
  1578. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1579. mv "$HOME/.le" "$LE_WORKING_DIR"
  1580. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1581. break;
  1582. fi
  1583. fi
  1584. done
  1585. fi
  1586. _info "Installing to $LE_WORKING_DIR"
  1587. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1588. _err "Can not craete working dir: $LE_WORKING_DIR"
  1589. return 1
  1590. fi
  1591. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1592. if [ "$?" != "0" ] ; then
  1593. _err "Install failed, can not copy $PROJECT_ENTRY"
  1594. return 1
  1595. fi
  1596. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1597. _profile="$(_detect_profile)"
  1598. if [ "$_profile" ] ; then
  1599. _debug "Found profile: $_profile"
  1600. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1601. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1602. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1603. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1604. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1605. fi
  1606. _setopt "$_envfile" "LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1607. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1608. echo "" >> "$_profile"
  1609. _setopt "$_profile" ". \"$LE_WORKING_DIR/$PROJECT_NAME.env\""
  1610. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1611. else
  1612. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1613. fi
  1614. if [ -d "dnsapi" ] ; then
  1615. mkdir -p $LE_WORKING_DIR/dnsapi
  1616. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1617. fi
  1618. #to keep compatible mv the .acc file to .key file
  1619. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1620. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1621. fi
  1622. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1623. _initconf
  1624. fi
  1625. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  1626. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1627. fi
  1628. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  1629. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1630. fi
  1631. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  1632. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1633. fi
  1634. installcronjob
  1635. if [ -z "$NO_DETECT_SH" ] ; then
  1636. #Modify shebang
  1637. if _exists bash ; then
  1638. _info "Good, bash is installed, change the shebang to use bash as prefered."
  1639. _shebang='#!/usr/bin/env bash'
  1640. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  1641. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  1642. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  1643. _setShebang "$_apifile" "$_shebang"
  1644. done
  1645. fi
  1646. fi
  1647. fi
  1648. _info OK
  1649. }
  1650. uninstall() {
  1651. uninstallcronjob
  1652. _initpath
  1653. _profile="$(_detect_profile)"
  1654. if [ "$_profile" ] ; then
  1655. text="$(cat $_profile)"
  1656. echo "$text" | sed "s|^[.] \"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  1657. fi
  1658. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1659. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1660. }
  1661. cron() {
  1662. IN_CRON=1
  1663. renewAll
  1664. IN_CRON=""
  1665. }
  1666. version() {
  1667. echo "$PROJECT"
  1668. echo "v$VER"
  1669. }
  1670. showhelp() {
  1671. version
  1672. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1673. Commands:
  1674. --help, -h Show this help message.
  1675. --version, -v Show version info.
  1676. --install Install $PROJECT_NAME to your system.
  1677. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1678. --issue Issue a cert.
  1679. --installcert Install the issued cert to apache/nginx or any other server.
  1680. --renew, -r Renew a cert.
  1681. --renewAll Renew all the certs
  1682. --revoke Revoke a cert.
  1683. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1684. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1685. --cron Run cron job to renew all the certs.
  1686. --toPkcs Export the certificate and key to a pfx file.
  1687. --createAccountKey, -cak Create an account private key, professional use.
  1688. --createDomainKey, -cdk Create an domain private key, professional use.
  1689. --createCSR, -ccsr Create CSR , professional use.
  1690. Parameters:
  1691. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1692. --force, -f Used to force to install or force to renew a cert immediately.
  1693. --staging, --test Use staging server, just for test.
  1694. --debug Output debug info.
  1695. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1696. --standalone Use standalone mode.
  1697. --apache Use apache mode.
  1698. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  1699. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1700. --accountkeylength, -ak [2048] Specifies the account key length.
  1701. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1702. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1703. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1704. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1705. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1706. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1707. --accountconf Specifies a customized account config file.
  1708. --home Specifies the home dir for $PROJECT_NAME .
  1709. --certhome Specifies the home dir to save all the certs.
  1710. --useragent Specifies the user agent string. it will be saved for future use too.
  1711. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1712. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1713. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1714. "
  1715. }
  1716. _installOnline() {
  1717. _info "Installing from online archive."
  1718. if [ ! "$BRANCH" ] ; then
  1719. BRANCH="master"
  1720. fi
  1721. _initpath
  1722. target="$PROJECT/archive/$BRANCH.tar.gz"
  1723. _info "Downloading $target"
  1724. localname="$BRANCH.tar.gz"
  1725. if ! _get "$target" > $localname ; then
  1726. _debug "Download error."
  1727. return 1
  1728. fi
  1729. _info "Extracting $localname"
  1730. tar xzf $localname
  1731. cd "$PROJECT_NAME-$BRANCH"
  1732. chmod +x $PROJECT_ENTRY
  1733. if ./$PROJECT_ENTRY install ; then
  1734. _info "Install success!"
  1735. fi
  1736. cd ..
  1737. rm -rf "$PROJECT_NAME-$BRANCH"
  1738. rm -f "$localname"
  1739. }
  1740. _process() {
  1741. _CMD=""
  1742. _domain=""
  1743. _altdomains="no"
  1744. _webroot=""
  1745. _keylength="no"
  1746. _accountkeylength="no"
  1747. _certpath="no"
  1748. _keypath="no"
  1749. _capath="no"
  1750. _fullchainpath="no"
  1751. _reloadcmd="no"
  1752. _password=""
  1753. _accountconf=""
  1754. _useragent=""
  1755. _accountemail=""
  1756. _accountkey=""
  1757. _certhome=""
  1758. while [ ${#} -gt 0 ] ; do
  1759. case "${1}" in
  1760. --help|-h)
  1761. showhelp
  1762. return
  1763. ;;
  1764. --version|-v)
  1765. version
  1766. return
  1767. ;;
  1768. --install)
  1769. _CMD="install"
  1770. ;;
  1771. --uninstall)
  1772. _CMD="uninstall"
  1773. ;;
  1774. --issue)
  1775. _CMD="issue"
  1776. ;;
  1777. --installcert|-i)
  1778. _CMD="installcert"
  1779. ;;
  1780. --renew|-r)
  1781. _CMD="renew"
  1782. ;;
  1783. --renewAll|-renewall)
  1784. _CMD="renewAll"
  1785. ;;
  1786. --revoke)
  1787. _CMD="revoke"
  1788. ;;
  1789. --installcronjob)
  1790. _CMD="installcronjob"
  1791. ;;
  1792. --uninstallcronjob)
  1793. _CMD="uninstallcronjob"
  1794. ;;
  1795. --cron)
  1796. _CMD="cron"
  1797. ;;
  1798. --toPkcs)
  1799. _CMD="toPkcs"
  1800. ;;
  1801. --createAccountKey|--createaccountkey|-cak)
  1802. _CMD="createAccountKey"
  1803. ;;
  1804. --createDomainKey|--createdomainkey|-cdk)
  1805. _CMD="createDomainKey"
  1806. ;;
  1807. --createCSR|--createcsr|-ccr)
  1808. _CMD="createCSR"
  1809. ;;
  1810. --domain|-d)
  1811. _dvalue="$2"
  1812. if [ -z "$_dvalue" ] || _startswith "$_dvalue" "-" ; then
  1813. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1814. return 1
  1815. fi
  1816. if [ -z "$_domain" ] ; then
  1817. _domain="$_dvalue"
  1818. else
  1819. if [ "$_altdomains" = "no" ] ; then
  1820. _altdomains="$_dvalue"
  1821. else
  1822. _altdomains="$_altdomains,$_dvalue"
  1823. fi
  1824. fi
  1825. shift
  1826. ;;
  1827. --force|-f)
  1828. FORCE="1"
  1829. ;;
  1830. --staging|--test)
  1831. STAGE="1"
  1832. ;;
  1833. --debug)
  1834. if [ -z "$2" ] || _startswith "$2" "-" ; then
  1835. DEBUG="1"
  1836. else
  1837. DEBUG="$2"
  1838. shift
  1839. fi
  1840. ;;
  1841. --webroot|-w)
  1842. wvalue="$2"
  1843. if [ -z "$_webroot" ] ; then
  1844. _webroot="$wvalue"
  1845. else
  1846. _webroot="$_webroot,$wvalue"
  1847. fi
  1848. shift
  1849. ;;
  1850. --standalone)
  1851. wvalue="no"
  1852. if [ -z "$_webroot" ] ; then
  1853. _webroot="$wvalue"
  1854. else
  1855. _webroot="$_webroot,$wvalue"
  1856. fi
  1857. ;;
  1858. --apache)
  1859. wvalue="apache"
  1860. if [ -z "$_webroot" ] ; then
  1861. _webroot="$wvalue"
  1862. else
  1863. _webroot="$_webroot,$wvalue"
  1864. fi
  1865. ;;
  1866. --dns)
  1867. wvalue="dns"
  1868. if ! _startswith "$2" "-" ; then
  1869. wvalue="$2"
  1870. shift
  1871. fi
  1872. if [ -z "$_webroot" ] ; then
  1873. _webroot="$wvalue"
  1874. else
  1875. _webroot="$_webroot,$wvalue"
  1876. fi
  1877. ;;
  1878. --keylength|-k)
  1879. _keylength="$2"
  1880. accountkeylength="$2"
  1881. shift
  1882. ;;
  1883. --accountkeylength|-ak)
  1884. accountkeylength="$2"
  1885. shift
  1886. ;;
  1887. --certpath)
  1888. _certpath="$2"
  1889. shift
  1890. ;;
  1891. --keypath)
  1892. _keypath="$2"
  1893. shift
  1894. ;;
  1895. --capath)
  1896. _capath="$2"
  1897. shift
  1898. ;;
  1899. --fullchainpath)
  1900. _fullchainpath="$2"
  1901. shift
  1902. ;;
  1903. --reloadcmd|--reloadCmd)
  1904. _reloadcmd="$2"
  1905. shift
  1906. ;;
  1907. --password)
  1908. _password="$2"
  1909. shift
  1910. ;;
  1911. --accountconf)
  1912. _accountconf="$2"
  1913. ACCOUNT_CONF_PATH="$_accountconf"
  1914. shift
  1915. ;;
  1916. --home)
  1917. LE_WORKING_DIR="$2"
  1918. shift
  1919. ;;
  1920. --certhome)
  1921. _certhome="$2"
  1922. CERT_HOME="$_certhome"
  1923. shift
  1924. ;;
  1925. --useragent)
  1926. _useragent="$2"
  1927. USER_AGENT="$_useragent"
  1928. shift
  1929. ;;
  1930. --accountemail )
  1931. _accountemail="$2"
  1932. ACCOUNT_EMAIL="$_accountemail"
  1933. shift
  1934. ;;
  1935. --accountkey )
  1936. _accountkey="$2"
  1937. ACCOUNT_KEY_PATH="$_accountkey"
  1938. shift
  1939. ;;
  1940. --days )
  1941. _days="$2"
  1942. Le_RenewalDays="$_days"
  1943. shift
  1944. ;;
  1945. *)
  1946. _err "Unknown parameter : $1"
  1947. return 1
  1948. ;;
  1949. esac
  1950. shift 1
  1951. done
  1952. case "${_CMD}" in
  1953. install) install ;;
  1954. uninstall) uninstall ;;
  1955. issue)
  1956. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1957. ;;
  1958. installcert)
  1959. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1960. ;;
  1961. renew)
  1962. renew "$_domain"
  1963. ;;
  1964. renewAll)
  1965. renewAll
  1966. ;;
  1967. revoke)
  1968. revoke "$_domain"
  1969. ;;
  1970. installcronjob) installcronjob ;;
  1971. uninstallcronjob) uninstallcronjob ;;
  1972. cron) cron ;;
  1973. toPkcs)
  1974. toPkcs "$_domain" "$_password"
  1975. ;;
  1976. createAccountKey)
  1977. createAccountKey "$_domain" "$_accountkeylength"
  1978. ;;
  1979. createDomainKey)
  1980. createDomainKey "$_domain" "$_keylength"
  1981. ;;
  1982. createCSR)
  1983. createCSR "$_domain" "$_altdomains"
  1984. ;;
  1985. *)
  1986. _err "Invalid command: $_CMD"
  1987. showhelp;
  1988. return 1
  1989. ;;
  1990. esac
  1991. if [ "$_useragent" ] ; then
  1992. _saveaccountconf "USER_AGENT" "$_useragent"
  1993. fi
  1994. if [ "$_accountemail" ] ; then
  1995. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  1996. fi
  1997. }
  1998. if [ "$INSTALLONLINE" ] ; then
  1999. INSTALLONLINE=""
  2000. _installOnline $BRANCH
  2001. exit
  2002. fi
  2003. if [ -z "$1" ] ; then
  2004. showhelp
  2005. else
  2006. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  2007. _process "$@"
  2008. else
  2009. "$@"
  2010. fi
  2011. fi