acme.sh 59 KB

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